diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index fde8f61..d58659f 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1 +1 @@ -{ "name": "editor", "version": "0.1.0", "description": "Tells agents to have the person fill in a secret or a config file in a Hangar tab, instead of asking for it in chat." } +{ "name": "editor", "version": "0.2.0", "description": "Tells agents to have the person fill in a secret or a config file in a Hangar tab, instead of asking for it in chat." } diff --git a/.gitattributes b/.gitattributes index 1125b70..6f55a12 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,3 +1,4 @@ * text=auto eol=lf *.png binary *.woff2 binary +*.wasm binary diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 69991f7..96fe0d3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,4 +11,17 @@ permissions: jobs: kit-check: - uses: hangar-ai/.github/.github/workflows/kit-check.yml@v1 + uses: hangar-ai/.github/.github/workflows/kit-check.yml@rust-rewrite + + # The native tab: its tests, and the committed module checked against the + # source. Rust comes from native/rust-toolchain.toml, which rustup installs + # with the wasm32-unknown-unknown target on the first cargo call there. + native: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Tests + working-directory: native + run: cargo test --locked + - name: The committed module is the one the source makes + run: scripts/build-native.sh --check diff --git a/.gitignore b/.gitignore index e7f2a8f..8bbb1a0 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ .hangar-ui/ node_modules/ +native/target/ diff --git a/README.md b/README.md index 5e71a53..bf1f1dd 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ check or edit. so plainly, and adds the line only when you click. A template such as `.env.example` is meant to be committed and gets no warning. - **Any other text file opens in a plain editor**: line numbers, the line the agent - pointed at, a diff before saving. JSON is checked by `JSON.parse`. TOML is parsed for + pointed at, a diff before saving. JSON is parsed whole. TOML is parsed for its syntax and YAML is scanned for what is certainly wrong (a tab in the indentation, a quote or a bracket left open): both say it is a basic check, not a proof. A broken file can be saved only after you say you know. @@ -30,6 +30,10 @@ check or edit. English and French, in Hangar's language; light and dark, in Hangar's theme; legible at the side panel's narrowest. +**A native tab, for Hangar 2.0 or later.** The tab is written in Rust and built to +WebAssembly (`tabs/editor.wasm`): Hangar runs that module and draws the tab with its own +widgets, in your theme, with no browser engine. There is no HTML page. + ## What it can touch Three permissions, shown to you before you enable the kit. It runs nothing by itself: no @@ -46,19 +50,28 @@ this is the kit that is for. Nothing under `.git` can be reached, and nothing le machine. **What reaches the agent:** the file's path, key names and counts, in sentences fixed in -[`tabs/editor/answer.js`](tabs/editor/answer.js). Never a value. A name that is also a +[`native/src/answer.rs`](native/src/answer.rs). Never a value. A name that is also a value in the file, or that you typed yourself in the « Add a key » field, is counted and -not named. `test/no-value-reaches-an-agent.test.js` drives the tab over hostile files and -random edits and looks at everything that leaves the page. +not named. `native/tests/no_value_reaches_an_agent.rs` drives the tab over hostile files +and random edits and looks at everything that leaves it, its log included, and checks in the +sources that `panes.send` is called from one place, fed by `answer` alone. The tab logs +nothing, and shows a value only in its own field, dotted until you click Show. What it cannot do: a tab cannot read `.git/info/exclude` or your global excludes, or tell whether a file is already tracked, so a tracked file listed in `.gitignore` reads as ignored and a file excluded elsewhere still gets the warning. `files.read` drops a BOM and -the page cannot know there was one, so saving a file that had one saves it without. +the tab cannot know there was one, so saving a file that had one saves it without. + +Details of the native tab: a value over several lines shows as a dotted one-line field until +you click Show, then in a plain text area (Hangar's text areas have no dotted mode). In the +editor, a line longer than the pane is cut at its edge rather than scrolled to, and Ctrl+S +works anywhere in the tab, not only in a field. It is opened with its params, so it does not +ask Hangar for them again. ## Install -You need Hangar 1.9.0 or later. +You need Hangar 2.0.0 or later: the tab is native, and an older Hangar says the kit needs a +newer one. 1. In Hangar, Settings › Kits, add the GitHub link: `https://github.com/hangar-ai/kit-editor` @@ -91,45 +104,61 @@ other. ``` editor/ -├── hangar-kit.json the kit: id, hangar >=1.9.0, the tab, its params and permissions +├── hangar-kit.json the kit: schema 2, id, hangar >=2.0.0, the tab (its entry is the module), params, permissions ├── icon.svg ├── .claude-plugin/plugin.json the Claude Code plugin (name = the kit's id) ├── skills/editor/SKILL.md -├── tabs/editor/ -│ ├── index.html loads Hangar UI and the SDK, then the scripts below -│ ├── dotenv.js reads a dotenv file, and writes back only what changed -│ ├── answer.js the only sentences an agent ever gets -│ ├── validate.js JSON, YAML, TOML -│ ├── diff.js lines compared, and line endings a textarea drops, restored -│ ├── gitignore.js git's ignore rules -│ ├── logic.js the words in en and fr, params, the picker's order -│ ├── controller.js the behaviour; takes window.hangar as an argument -│ ├── view.js draws a state with Hangar UI's classes, never markup -│ ├── app.js wires them in the page -│ └── style.css the editor's layout, in Hangar UI's tokens -├── test/ node --test, no dependency, a fake window.hangar over made-up files +├── tabs/editor.wasm the native tab, built from native/ and committed: the manifest's `entry` +├── native/ the tab in Rust, on Hangar's kit SDK (hangar-kit-sdk) +│ ├── src/ dotenv.rs (reads a dotenv file, writes back only what changed), +│ │ answer.rs (the only sentences an agent ever gets), validate.rs (JSON, +│ │ YAML, TOML), diff.rs, gitignore.rs (git's ignore rules), logic.rs (the +│ │ words in en and fr, params, the picker's order), editor.rs (the +│ │ behaviour), view.rs (the widgets) +│ ├── tests/ through the SDK's test harness, with a fake Hangar +│ ├── Cargo.toml, Cargo.lock the SDK from Hangar's repository, pinned to a commit +│ └── rust-toolchain.toml the Rust that builds the module +├── scripts/build-native.sh builds native/ into tabs/editor.wasm (--check: fails if it is stale) +├── test/manifest.test.js the manifest, the plugin and the skill, with Node alone └── package.json, run-tests.js let `node --test kits/editor/` find the tests on any Node ``` +### The native tab + +``` +scripts/build-native.sh # builds native/, writes tabs/editor.wasm +scripts/build-native.sh --check # builds it, and fails if tabs/editor.wasm is not what the source makes +``` + +builds `native/` for `wasm32-unknown-unknown` and copies the module to `tabs/editor.wasm`. +It needs Rust; `native/rust-toolchain.toml` names the version and the target, which rustup +installs the first time. Hangar never builds a kit: it runs the module the kit ships, so +`tabs/editor.wasm` is committed, rebuilt in the commit that changes `native/`. The build +takes the paths of the machine out of the module, so it is the same byte for byte wherever +it is built, and CI checks that the committed one is what the source makes. To try a change, +link this folder in Hangar's Settings › Kits (it is read live), run the script, and reload the +tab from its bar. + ## Tests ``` node --test kits/editor/ +cargo test --manifest-path native/Cargo.toml ``` -No install step. No test reads a real file of yours: the fake Hangar holds its files in -memory, and the check of the ignore rules against `git check-ignore` runs in a temporary -folder. +The first needs Node alone and checks the manifest, the plugin and the skill. The second runs +the native tab on the host, with no WebAssembly and no Hangar: a fake Hangar answers its calls +from files in memory, under the manifest's three permissions, and the tests press, type and +read its view as a person would. No test reads a real file of yours: the fake Hangar holds its +files in memory, and the check of the ignore rules against `git check-ignore` runs in a +temporary folder. ## This repository -`node --test` runs the tests, with Node alone. Hangar's own files are not in this repository. CI takes Hangar UI and the docs from the Hangar tag the -manifest's `hangar` names, and `node test/hangar-ui.js --get` does the same here. Without them, these tests -skip what needs those files, and say so: - -- the permissions and methods used are in the docs, when the docs are around -- Hangar UI's classes, and no colour of its own +`node --test` runs the manifest's and the plugin's tests, with Node alone. Hangar's own files +are not needed. -CI calls [kit-check](https://github.com/hangar-ai/.github/blob/main/.github/workflows/kit-check.yml). A release is -a tag, `v` and the manifest's version, and it reaches Hangar's gallery once -[the catalog](https://github.com/hangar-ai/catalog) is updated and reviewed. +CI calls [kit-check](https://github.com/hangar-ai/.github/blob/main/.github/workflows/kit-check.yml), +runs the native tab's tests, and fails if the committed `tabs/editor.wasm` is not the one the +source makes. A release is a tag, `v` and the manifest's version, and it reaches Hangar's gallery +once [the catalog](https://github.com/hangar-ai/catalog) is updated and reviewed. diff --git a/hangar-kit.json b/hangar-kit.json index 49e52f5..13bcc81 100644 --- a/hangar-kit.json +++ b/hangar-kit.json @@ -1,13 +1,13 @@ { - "schema": 1, + "schema": 2, "id": "editor", "name": "Editor", - "version": "0.1.0", + "version": "0.2.0", "description": "Opens a .env or a config file in a tab for you to fill in or check, so that an agent that needs a secret goes on without ever seeing it.", "author": "Hangar", "homepage": "https://github.com/hangar-ai/kit-editor", "icon": "icon.svg", - "hangar": ">=1.9.0", + "hangar": ">=2.0.0", "gallery": { "permissionsSummary": "Reads and changes text files of the workspace, .env and other hidden files included, and tells the agent that asked which keys were set, never their values.", "tags": ["env", "secrets", "config", "tab"] @@ -16,7 +16,7 @@ { "id": "editor", "title": "Editor", - "entry": "tabs/editor/index.html", + "entry": "tabs/editor.wasm", "icon": "icon.svg", "permissions": ["files.read", "files.write", "panes.send"], "params": { diff --git a/native/Cargo.lock b/native/Cargo.lock new file mode 100644 index 0000000..71bf9a7 --- /dev/null +++ b/native/Cargo.lock @@ -0,0 +1,166 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "hangar-kit-sdk" +version = "1.12.1" +source = "git+https://github.com/hangar-ai/hangar?branch=feat%2Fnative-rust#b0ea65b180991f4ecd88984c0a69d168a57545e8" +dependencies = [ + "hangar-kit-ui", + "serde", + "serde_json", +] + +[[package]] +name = "hangar-kit-ui" +version = "1.12.1" +source = "git+https://github.com/hangar-ai/hangar?branch=feat%2Fnative-rust#b0ea65b180991f4ecd88984c0a69d168a57545e8" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "kit-editor-tab" +version = "0.1.0" +dependencies = [ + "hangar-kit-sdk", + "regex", + "serde", + "serde_json", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/native/Cargo.toml b/native/Cargo.toml new file mode 100644 index 0000000..a7dabf7 --- /dev/null +++ b/native/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "kit-editor-tab" +description = "The Editor kit's tab, native: Rust built to WebAssembly" +version = "0.1.0" +edition = "2024" +license = "MIT" +publish = false + +# The cdylib is the module Hangar loads (tabs/editor.wasm, built by +# scripts/build-native.sh); the rlib is for `cargo test`, which runs the tab on +# the host with hangar_kit_sdk::testing. +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +# Until a release tag of Hangar holds the SDK, its branch; Cargo.lock pins the commit. +hangar-kit-sdk = { git = "https://github.com/hangar-ai/hangar", branch = "feat/native-rust" } +serde = { version = "1", features = ["derive"] } +serde_json = "1" + +[profile.release] +opt-level = "s" +lto = true +strip = true +codegen-units = 1 +panic = "abort" + +[dev-dependencies] +regex = "1" diff --git a/native/rust-toolchain.toml b/native/rust-toolchain.toml new file mode 100644 index 0000000..1cc5a8b --- /dev/null +++ b/native/rust-toolchain.toml @@ -0,0 +1,5 @@ +# The Rust that builds tabs/editor.wasm: the same compiler makes the same bytes, +# which is how CI tells a stale module. +[toolchain] +channel = "1.99.1" +targets = ["wasm32-unknown-unknown"] diff --git a/native/src/answer.rs b/native/src/answer.rs new file mode 100644 index 0000000..6efa8ea --- /dev/null +++ b/native/src/answer.rs @@ -0,0 +1,121 @@ +//! The only text this tab ever sends to an agent. Every sentence is fixed +//! here; what varies is the file's path, key names and counts. It is handed +//! names, never a value: `values` is only there so that a name that is also a +//! value stays unsaid. answer.js, ported. + +use std::collections::HashSet; + +use crate::js; + +const NAME_MAX: usize = 64; +const NAMED_MAX: usize = 40; +/// Shorter values match names by chance: `1` in `KEY1`. +const SHORTEST_INSIDE: usize = 4; +const STAY: &str = "The values stay in the file: do not read them back, use them through the program that loads it."; + +/// `[A-Za-z_][A-Za-z0-9_.-]{0,63}`. +fn looks_like_a_name(name: &str) -> bool { + let bytes = name.as_bytes(); + (1..=NAME_MAX).contains(&bytes.len()) + && (bytes[0].is_ascii_alphabetic() || bytes[0] == b'_') + && bytes + .iter() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'-')) +} + +/// A value pasted where a key goes (`sk_live_abc=`, or a value that repeats as +/// another line's key) is still a key to any parser. So a name is said only if +/// it looks like one, is one this file or the agent already knew, and holds no +/// value. +pub fn may_name(name: &str, known: &HashSet, values: &[String]) -> bool { + if !looks_like_a_name(name) || !known.contains(name) { + return false; + } + !values.iter().any(|raw| { + let value = js::trim(raw); + !value.is_empty() + && (value == name || (js::length(value) >= SHORTEST_INSIDE && name.contains(value))) + }) +} + +/// The names that may be said, and how many may not. +fn sayable(names: &[String], known: &HashSet, values: &[String]) -> (Vec, usize) { + let mut named = Vec::new(); + let mut others = 0; + for name in names { + if named.len() < NAMED_MAX && may_name(name, known, values) { + named.push(name.clone()); + } else { + others += 1; + } + } + (named, others) +} + +fn sentence(label: &str, names: &[String]) -> String { + if names.is_empty() { + String::new() + } else { + format!(" {label}: {}.", names.join(", ")) + } +} + +fn others(count: usize, verb: &str) -> String { + match count { + 0 => String::new(), + 1 => format!(" 1 other key {verb}."), + _ => format!(" {count} other keys {verb}."), + } +} + +/// What a sentence about a dotenv file is told: names, and the values only +/// to stay silent about them. +pub struct Facts<'a> { + pub path: &'a str, + pub known: &'a HashSet, + pub values: &'a [String], +} + +/// The person saved a dotenv file. +pub fn dotenv_saved( + facts: &Facts, + set: &[String], + emptied: &[String], + still_empty: &[String], +) -> String { + let (set, set_others) = sayable(set, facts.known, facts.values); + let (emptied, emptied_others) = sayable(emptied, facts.known, facts.values); + let (empty, empty_others) = sayable(still_empty, facts.known, facts.values); + format!( + "The person saved `{}`.{}{}{}{} {STAY}", + facts.path, + sentence("Set", &set), + sentence("Emptied", &emptied), + sentence("Still empty", &empty), + others( + set_others + emptied_others + empty_others, + "changed or empty" + ), + ) +} + +/// The person looked at a dotenv file and had nothing to change. +pub fn dotenv_checked(facts: &Facts, already_set: &[String], still_empty: &[String]) -> String { + let (set, set_others) = sayable(already_set, facts.known, facts.values); + let (empty, empty_others) = sayable(still_empty, facts.known, facts.values); + format!( + "The person checked `{}` and changed nothing.{}{}{} {STAY}", + facts.path, + sentence("Already set", &set), + sentence("Still empty", &empty), + others(set_others + empty_others, "set or empty"), + ) +} + +pub fn text_saved(path: &str) -> String { + format!("The person saved `{path}`: the file changed.") +} + +pub fn text_checked(path: &str) -> String { + format!("The person checked `{path}` and changed nothing.") +} diff --git a/native/src/diff.rs b/native/src/diff.rs new file mode 100644 index 0000000..cab8d78 --- /dev/null +++ b/native/src/diff.rs @@ -0,0 +1,232 @@ +//! Lines compared, for the diff before saving and the conflict view, and the +//! line endings an editor takes away, given back. diff.js, ported. + +use std::collections::HashMap; + +/// Beyond this the changed block is shown as replaced whole. +const LCS_CELLS: usize = 4_000_000; +const CONTEXT: usize = 3; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind { + Same, + Del, + Add, +} + +/// A line of the comparison, with its number on each side. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Op { + pub kind: Kind, + pub text: String, + pub a: Option, + pub b: Option, +} + +/// A line, or unchanged lines folded. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Hunk { + Line(Op), + Skip(usize), +} + +impl Hunk { + pub fn is_change(&self) -> bool { + matches!(self, Hunk::Line(op) if op.kind != Kind::Same) + } +} + +/// What an editor does to a text: it only ever holds `\n`. +pub fn normalize(text: &str) -> String { + text.replace("\r\n", "\n").replace('\r', "\n") +} + +fn middle<'a>(a: &[&'a str], b: &[&'a str], offset: usize, out: &mut Vec) { + let (n, m) = (a.len(), b.len()); + let del = |i: usize| Op { + kind: Kind::Del, + text: a[i].to_owned(), + a: Some(offset + i + 1), + b: None, + }; + let add = |j: usize| Op { + kind: Kind::Add, + text: b[j].to_owned(), + a: None, + b: Some(offset + j + 1), + }; + if n == 0 || m == 0 || n.saturating_mul(m) > LCS_CELLS { + out.extend((0..n).map(del)); + out.extend((0..m).map(add)); + return; + } + // Lines as numbers, so that each cell compares two integers. + let mut ids: HashMap<&'a str, u32> = HashMap::new(); + let mut id = |line: &'a str| { + let next = ids.len() as u32; + *ids.entry(line).or_insert(next) + }; + let a_ids: Vec = a.iter().map(|line| id(line)).collect(); + let b_ids: Vec = b.iter().map(|line| id(line)).collect(); + let width = m + 1; + let mut table = vec![0u32; (n + 1) * width]; + for i in (0..n).rev() { + for j in (0..m).rev() { + table[i * width + j] = if a_ids[i] == b_ids[j] { + table[(i + 1) * width + j + 1] + 1 + } else { + table[(i + 1) * width + j].max(table[i * width + j + 1]) + }; + } + } + let (mut i, mut j) = (0, 0); + while i < n || j < m { + if i < n && j < m && a_ids[i] == b_ids[j] { + out.push(Op { + kind: Kind::Same, + text: a[i].to_owned(), + a: Some(offset + i + 1), + b: Some(offset + j + 1), + }); + i += 1; + j += 1; + } else if j >= m || (i < n && table[(i + 1) * width + j] >= table[i * width + j + 1]) { + out.push(del(i)); + i += 1; + } else { + out.push(add(j)); + j += 1; + } + } +} + +/// Every line of `before` and `after` (both `\n` only), in order: same, del +/// or add, with its numbers. +pub fn diff_lines(before: &str, after: &str) -> Vec { + let a: Vec<&str> = before.split('\n').collect(); + let b: Vec<&str> = after.split('\n').collect(); + let mut head = 0; + while head < a.len() && head < b.len() && a[head] == b[head] { + head += 1; + } + let mut tail = 0; + while tail < a.len() - head + && tail < b.len() - head + && a[a.len() - 1 - tail] == b[b.len() - 1 - tail] + { + tail += 1; + } + let mut out = Vec::with_capacity(a.len().max(b.len())); + for (i, line) in a.iter().enumerate().take(head) { + out.push(Op { + kind: Kind::Same, + text: (*line).to_owned(), + a: Some(i + 1), + b: Some(i + 1), + }); + } + middle( + &a[head..a.len() - tail], + &b[head..b.len() - tail], + head, + &mut out, + ); + for i in (1..=tail).rev() { + out.push(Op { + kind: Kind::Same, + text: a[a.len() - i].to_owned(), + a: Some(a.len() - i + 1), + b: Some(b.len() - i + 1), + }); + } + out +} + +/// The same, unchanged stretches folded into skips. +pub fn hunks(ops: Vec) -> Vec { + let mut near = vec![false; ops.len()]; + for (index, op) in ops.iter().enumerate() { + if op.kind == Kind::Same { + continue; + } + let end = (index + CONTEXT).min(ops.len() - 1); + for flag in &mut near[index.saturating_sub(CONTEXT)..=end] { + *flag = true; + } + } + let mut out = Vec::new(); + let mut skipped = 0; + for (op, near) in ops.into_iter().zip(near) { + if near { + if skipped > 0 { + out.push(Hunk::Skip(skipped)); + } + skipped = 0; + out.push(Hunk::Line(op)); + } else { + skipped += 1; + } + } + if skipped > 0 { + out.push(Hunk::Skip(skipped)); + } + out +} + +pub fn has_changes(ops: &[Op]) -> bool { + ops.iter().any(|op| op.kind != Kind::Same) +} + +/// `edited` (`\n` only) with the line endings of `original` back: each line +/// that did not change keeps its own, and a new one takes the file's most +/// common. +pub fn restore_eols(original: &str, edited: &str) -> String { + let bytes = original.as_bytes(); + let mut eols: Vec<&str> = Vec::new(); + let mut i = 0; + while i < bytes.len() { + match bytes[i] { + b'\r' if bytes.get(i + 1) == Some(&b'\n') => { + eols.push("\r\n"); + i += 1; + } + b'\r' => eols.push("\r"), + b'\n' => eols.push("\n"), + _ => {} + } + i += 1; + } + let count = |eol: &str| eols.iter().filter(|other| **other == eol).count(); + let counts = [ + ("\n", count("\n")), + ("\r\n", count("\r\n")), + ("\r", count("\r")), + ]; + if counts[0].1 == eols.len() { + return edited.to_owned(); + } + if counts[1].1 == eols.len() { + return edited.replace('\n', "\r\n"); + } + let mut common = counts[0]; + for each in &counts[1..] { + if each.1 > common.1 { + common = *each; + } + } + let lines: Vec<&str> = edited.split('\n').collect(); + let mut kept: Vec> = vec![None; lines.len()]; + for op in diff_lines(&normalize(original), edited) { + if let (Kind::Same, Some(a), Some(b)) = (op.kind, op.a, op.b) { + kept[b - 1] = eols.get(a - 1).copied(); + } + } + let mut out = String::with_capacity(edited.len() + lines.len()); + for (index, line) in lines.iter().enumerate() { + out.push_str(line); + if index + 1 < lines.len() { + out.push_str(kept[index].unwrap_or(common.0)); + } + } + out +} diff --git a/native/src/dotenv.rs b/native/src/dotenv.rs new file mode 100644 index 0000000..0ad216d --- /dev/null +++ b/native/src/dotenv.rs @@ -0,0 +1,587 @@ +//! Reads a dotenv file so that saving it changes only what was edited: every +//! line keeps its exact bytes (comments, blanks, order, line endings, quotes) +//! unless its own value changed. dotenv.js, ported: no SDK, no Hangar. + +use std::collections::{HashMap, HashSet}; + +use crate::js::{self, cut, from}; + +const HINT_MAX: usize = 300; + +/// A line of the file, or several when a quoted value spans them. +#[derive(Debug, Clone, PartialEq)] +pub enum Entry { + Pair(Pair), + Other(Other), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Pair { + pub key: String, + /// What parsers read: unquoted, unescaped. + pub value: String, + /// The indent, `export `, and the key. + pub prefix: String, + /// ` = `, as written. + pub separator: String, + /// `"`, `'`, `` ` `` or nothing. + pub quote: String, + /// What follows the value: blanks and a comment. + pub trailing: String, + /// The entry as the file holds it, its end of line apart. + pub raw: String, + pub eol: String, +} + +/// A line kept as it is: a comment, a blank, what is not `KEY=value`. +#[derive(Debug, Clone, PartialEq)] +pub struct Other { + pub raw: String, + pub eol: String, + pub blank: bool, + pub comment: bool, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Doc { + pub entries: Vec, + /// The file's most common line ending, for what is added. + pub eol: String, +} + +/// One row per key, in the file's order. +#[derive(Debug, Clone, PartialEq)] +pub struct Row { + pub key: String, + /// The value parsers keep: the last line's. + pub value: String, + /// How many lines define it. + pub count: usize, + /// The comment above its first line. + pub hint: String, +} + +/// Values set by key, in the order they were given: a key the file does not +/// have goes at its end in this order. +pub type Edits = Vec<(String, String)>; + +fn is_key_start(byte: u8) -> bool { + byte.is_ascii_alphabetic() || byte == b'_' +} + +fn is_key_byte(byte: u8) -> bool { + byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'-') +} + +fn is_blank(byte: u8) -> bool { + byte == b' ' || byte == b'\t' +} + +/// `[A-Za-z_][A-Za-z0-9_.-]*`, whole. +pub fn is_key(name: &str) -> bool { + let bytes = name.as_bytes(); + !bytes.is_empty() && is_key_start(bytes[0]) && bytes.iter().all(|byte| is_key_byte(*byte)) +} + +/// A key from `at` then `[ \t]*=[ \t]*`: where the key and the separator end. +fn key_and_separator(line: &[u8], at: usize) -> Option<(usize, usize)> { + if !line.get(at).is_some_and(|byte| is_key_start(*byte)) { + return None; + } + let mut key_end = at + 1; + while line.get(key_end).is_some_and(|byte| is_key_byte(*byte)) { + key_end += 1; + } + let mut i = key_end; + while line.get(i).is_some_and(|byte| is_blank(*byte)) { + i += 1; + } + if line.get(i) != Some(&b'=') { + return None; + } + i += 1; + while line.get(i).is_some_and(|byte| is_blank(*byte)) { + i += 1; + } + Some((key_end, i)) +} + +/// `^([ \t]*(?:export[ \t]+)?)([A-Za-z_][A-Za-z0-9_.-]*)([ \t]*=[ \t]*)`: where +/// the lead, the key and the separator end. +fn assignment(line: &[u8]) -> Option<(usize, usize, usize)> { + let mut lead = 0; + while line.get(lead).is_some_and(|byte| is_blank(*byte)) { + lead += 1; + } + if line[lead..].starts_with(b"export") && line.get(lead + 6).is_some_and(|b| is_blank(*b)) { + let mut after = lead + 6; + while line.get(after).is_some_and(|byte| is_blank(*byte)) { + after += 1; + } + if let Some((key_end, end)) = key_and_separator(line, after) { + return Some((after, key_end, end)); + } + } + key_and_separator(line, lead).map(|(key_end, end)| (lead, key_end, end)) +} + +/// `# OLD_TOKEN=abc` is a value put aside, not an explanation: never a hint. +fn is_commented_assignment(line: &str) -> bool { + let rest = line.trim_start_matches('#'); + rest.len() < line.len() && assignment(rest.as_bytes()).is_some() +} + +fn line_end(text: &[u8], at: usize) -> usize { + text[at.min(text.len())..] + .iter() + .position(|byte| *byte == b'\n' || *byte == b'\r') + .map_or(text.len(), |offset| at + offset) +} + +fn eol_at(text: &[u8], at: usize) -> &'static str { + match (text.get(at), text.get(at + 1)) { + (Some(b'\r'), Some(b'\n')) => "\r\n", + (Some(b'\r'), _) => "\r", + (Some(b'\n'), _) => "\n", + _ => "", + } +} + +/// Where the quote opened before `at` closes. +fn closing(text: &[u8], at: usize, quote: u8, escapes: bool) -> Option { + let mut i = at; + while i < text.len() { + if escapes && text[i] == b'\\' { + i += 1; + } else if text[i] == quote { + return Some(i); + } + i += 1; + } + None +} + +fn unquoted(inner: &str, quote: u8, escapes: bool) -> String { + if quote == b'"' { + let mut out = String::with_capacity(inner.len()); + let mut chars = inner.chars(); + while let Some(c) = chars.next() { + if c != '\\' { + out.push(c); + continue; + } + match chars.next() { + Some(next) => match next { + 'n' => out.push('\n'), + 'r' => out.push('\r'), + 't' => out.push('\t'), + '"' | '\\' | '$' => out.push(next), + _ => { + out.push('\\'); + out.push(next); + } + }, + None => out.push('\\'), + } + } + return out; + } + if escapes { + let escaped = format!("\\{}", quote as char); + return inner.replace(&escaped, &(quote as char).to_string()); + } + inner.to_owned() +} + +struct Read { + value: String, + quote: String, + trailing: String, + /// Where the entry ends, for a quoted value: the end of its last line. + end: Option, +} + +/// A quoted value, over several lines if it says so. A quote counts as closed +/// only when nothing but a comment follows it: otherwise `A="x` would swallow +/// the lines below it, and what is a value would be read as keys. +fn read_quoted(text: &str, start: usize) -> Option { + let bytes = text.as_bytes(); + let quote = bytes[start]; + let tries: &[bool] = if quote == b'"' { + &[true] + } else { + &[false, true] + }; + for &escapes in tries { + let Some(close) = closing(bytes, start + 1, quote, escapes) else { + continue; + }; + let end = line_end(bytes, close + 1); + let rest = cut(text, close + 1, end); + let blanks = rest.bytes().take_while(|byte| is_blank(*byte)).count(); + if !(blanks == rest.len() || rest.as_bytes()[blanks] == b'#') { + continue; + } + return Some(Read { + value: unquoted(cut(text, start + 1, close), quote, escapes), + quote: (quote as char).to_string(), + trailing: rest.to_owned(), + end: Some(end), + }); + } + None +} + +fn read_bare(rest: &str, after_blank: bool) -> Read { + let bytes = rest.as_bytes(); + let mut cut_at = bytes.len(); + for (i, byte) in bytes.iter().enumerate() { + let opens = if i > 0 { + is_blank(bytes[i - 1]) + } else { + after_blank + }; + if *byte == b'#' && opens { + cut_at = i; + break; + } + } + let mut end = cut_at; + while end > 0 && is_blank(bytes[end - 1]) { + end -= 1; + } + Read { + value: cut(rest, 0, end).to_owned(), + quote: String::new(), + trailing: from(rest, end).to_owned(), + end: None, + } +} + +/// The text, as entries: a pair, or a line kept as it is. [`serialize`] gives +/// back the same text. +pub fn parse(text: &str) -> Doc { + let bytes = text.as_bytes(); + let mut entries = Vec::new(); + let mut at = 0; + let (mut crlf, mut lf) = (0, 0); + while at < bytes.len() { + let end = line_end(bytes, at); + let line = cut(text, at, end); + let mut entry_end = end; + match assignment(line.as_bytes()) { + Some((lead_end, key_end, head)) => { + let start = at + head; + let quoted = match bytes.get(start) { + Some(b'"' | b'\'' | b'`') => read_quoted(text, start), + _ => None, + }; + let separator = cut(line, key_end, head); + let read = match quoted { + Some(read) => read, + None => read_bare(cut(text, start, end), separator.ends_with([' ', '\t'])), + }; + if let Some(quoted_end) = read.end { + entry_end = quoted_end; + } + entries.push(Entry::Pair(Pair { + key: cut(line, lead_end, key_end).to_owned(), + value: read.value, + prefix: cut(line, 0, key_end).to_owned(), + separator: separator.to_owned(), + quote: read.quote, + trailing: read.trailing, + raw: cut(text, at, entry_end).to_owned(), + eol: eol_at(bytes, entry_end).to_owned(), + })); + } + None => { + let trimmed = js::trim(line); + entries.push(Entry::Other(Other { + raw: line.to_owned(), + eol: eol_at(bytes, end).to_owned(), + blank: trimmed.is_empty(), + comment: trimmed.starts_with('#'), + })); + } + } + let eol = eol_at(bytes, entry_end); + match eol { + "\r\n" => crlf += 1, + "\n" => lf += 1, + _ => {} + } + at = entry_end + eol.len(); + } + Doc { + entries, + eol: if crlf > lf { "\r\n" } else { "\n" }.to_owned(), + } +} + +pub fn serialize(doc: &Doc) -> String { + let mut out = String::new(); + for entry in &doc.entries { + let (raw, eol) = match entry { + Entry::Pair(pair) => (&pair.raw, &pair.eol), + Entry::Other(other) => (&other.raw, &other.eol), + }; + out.push_str(raw); + out.push_str(eol); + } + out +} + +/// `[A-Za-z0-9_./:@%+,=~-]+`: a value that needs no quotes anywhere. +fn bare_safe(value: &str) -> bool { + !value.is_empty() + && value.bytes().all(|byte| { + byte.is_ascii_alphanumeric() + || matches!( + byte, + b'_' | b'.' | b'/' | b':' | b'@' | b'%' | b'+' | b',' | b'=' | b'~' | b'-' + ) + }) +} + +/// A value as the file should hold it. Single quotes are the least magical: +/// no escape, no expansion, several lines allowed. A value holding one needs +/// double quotes, and then every parser reads \\ \" \n and \r back. +fn quoted(value: &str, previous: &str) -> String { + if value.is_empty() { + return format!("{previous}{previous}"); + } + if bare_safe(value) { + return format!("{previous}{value}{previous}"); + } + if !value.contains('\'') { + return format!("'{value}'"); + } + let escaped = value + .replace('\\', "\\\\") + .replace('"', "\\\"") + .replace('\r', "\\r") + .replace('\n', "\\n"); + format!("\"{escaped}\"") +} + +fn rendered(pair: &Pair, value: &str) -> String { + let body = quoted(value, &pair.quote); + let gap = if !body.is_empty() && pair.trailing.starts_with('#') { + " " + } else { + "" + }; + format!( + "{}{}{body}{gap}{}", + pair.prefix, pair.separator, pair.trailing + ) +} + +/// The doc with these values set, each on the last line that defines its +/// key, the one parsers keep. A key the file does not have goes at the end. +/// Nothing else moves. +pub fn with_values(doc: &Doc, edits: &[(String, String)]) -> Doc { + let mut remaining: Vec<(String, String)> = Vec::new(); + for (key, value) in edits { + match remaining.iter_mut().find(|(other, _)| other == key) { + Some(slot) => slot.1 = value.clone(), + None => remaining.push((key.clone(), value.clone())), + } + } + let mut last: HashMap<&str, usize> = HashMap::new(); + for (index, entry) in doc.entries.iter().enumerate() { + if let Entry::Pair(pair) = entry { + last.insert(&pair.key, index); + } + } + let mut entries: Vec = doc + .entries + .iter() + .enumerate() + .map(|(index, entry)| { + let Entry::Pair(pair) = entry else { + return entry.clone(); + }; + if last.get(pair.key.as_str()) != Some(&index) { + return entry.clone(); + } + let Some(at) = remaining.iter().position(|(key, _)| *key == pair.key) else { + return entry.clone(); + }; + let (_, value) = remaining.remove(at); + if value == pair.value { + return entry.clone(); + } + let raw = rendered(pair, &value); + Entry::Pair(Pair { + value, + raw, + ..pair.clone() + }) + }) + .collect(); + for (key, value) in remaining { + if let Some(tail) = entries.last_mut() { + let eol = match tail { + Entry::Pair(pair) => &mut pair.eol, + Entry::Other(other) => &mut other.eol, + }; + if eol.is_empty() { + *eol = doc.eol.clone(); + } + } + let mut fresh = Pair { + key: key.clone(), + value: value.clone(), + prefix: key, + separator: "=".to_owned(), + quote: String::new(), + trailing: String::new(), + raw: String::new(), + eol: doc.eol.clone(), + }; + fresh.raw = rendered(&fresh, &value); + entries.push(Entry::Pair(fresh)); + } + Doc { + entries, + eol: doc.eol.clone(), + } +} + +/// One row per key, in the file's order: the value parsers keep, the comment +/// above it, how many lines define it. +pub fn rows(doc: &Doc) -> Vec { + let mut found: Vec = Vec::new(); + let mut index: HashMap = HashMap::new(); + let mut comments: Vec = Vec::new(); + for entry in &doc.entries { + match entry { + Entry::Other(other) => { + let line = js::trim(&other.raw); + if other.comment && !is_commented_assignment(line) { + let text = line.trim_start_matches('#'); + let text = text.strip_prefix([' ', '\t']).unwrap_or(text); + comments.push(text.to_owned()); + } else if !other.comment { + comments.clear(); + } + } + Entry::Pair(pair) => { + match index.get(&pair.key) { + Some(&at) => { + found[at].value = pair.value.clone(); + found[at].count += 1; + } + None => { + index.insert(pair.key.clone(), found.len()); + found.push(Row { + key: pair.key.clone(), + value: pair.value.clone(), + count: 1, + hint: js::first_chars(&comments.join(" "), HINT_MAX), + }); + } + } + comments.clear(); + } + } + } + found +} + +/// Every value the file holds, those a later line overrides included. +pub fn all_values(doc: &Doc) -> Vec { + doc.entries + .iter() + .filter_map(|entry| match entry { + Entry::Pair(pair) => Some(pair.value.clone()), + Entry::Other(_) => None, + }) + .collect() +} + +/// Lines that are neither a pair, a comment nor blank: never shown, kept. +pub fn other_lines(doc: &Doc) -> usize { + doc.entries + .iter() + .filter(|entry| matches!(entry, Entry::Other(other) if !other.blank && !other.comment)) + .count() +} + +/// Which keys got a value and which lost theirs, by name. It returns no value. +pub struct Changed { + pub set: Vec, + pub emptied: Vec, +} + +pub fn changed_keys(before: &Doc, after: &Doc) -> Changed { + let old: HashMap = rows(before) + .into_iter() + .map(|row| (row.key, row.value)) + .collect(); + let mut changed = Changed { + set: Vec::new(), + emptied: Vec::new(), + }; + for row in rows(after) { + match old.get(&row.key) { + Some(value) if *value == row.value => continue, + Some(_) if row.value.is_empty() => changed.emptied.push(row.key), + _ if !row.value.is_empty() => changed.set.push(row.key), + _ => {} + } + } + changed +} + +/// `.env`, `.env.local`, `app.env`, any case. +pub fn is_dotenv_path(path: &str) -> bool { + let name = js::base_name(path).to_lowercase(); + let after_env = |rest: &str| !rest.is_empty() && !rest.chars().any(js::is_line_terminator); + if name == ".env" || name.strip_prefix(".env.").is_some_and(after_env) { + return true; + } + name.strip_suffix(".env") + .and_then(|before| before.chars().last()) + .is_some_and(|c| !js::is_line_terminator(c)) +} + +/// A template meant to be committed, with no secret to protect. +pub fn is_example_path(path: &str) -> bool { + if !is_dotenv_path(path) { + return false; + } + let name = js::base_name(path).to_lowercase(); + [ + ".example", + ".sample", + ".template", + ".dist", + ".default", + ".defaults", + ] + .iter() + .any(|end| name.ends_with(end)) +} + +/// Where this file's template may be, the nearest name first. +pub fn example_candidates(path: &str) -> Vec { + let dir = js::dir_name(path); + let name = js::base_name(path); + let names = [ + format!("{name}.example"), + format!("{name}.sample"), + ".env.example".to_owned(), + ".env.sample".to_owned(), + ".env.template".to_owned(), + ".env.dist".to_owned(), + ]; + let mut seen = HashSet::new(); + names + .into_iter() + .filter(|other| seen.insert(other.clone()) && other != name) + .map(|other| format!("{dir}{other}")) + .collect() +} diff --git a/native/src/editor.rs b/native/src/editor.rs new file mode 100644 index 0000000..d75f9e5 --- /dev/null +++ b/native/src/editor.rs @@ -0,0 +1,1810 @@ +//! The tab's behaviour: controller.js, as a [`Kit`]. Each `await` of the page +//! is a call here, answered by a message of its own, and each answer is +//! measured against `generation`, as the page's were: a later file makes the +//! earlier answers stale. Values go to `files.write` and nowhere else; the +//! one text an agent gets is made by `answer`, from names and counts. + +use std::collections::{HashMap, HashSet, VecDeque}; + +use hangar_kit_sdk::api::{ + BadgeState, Done, FileListing, KitError, Queued, TabParamsAnswer, Theme, +}; +use hangar_kit_sdk::prelude::*; +use hangar_kit_sdk::ui::Range; + +use crate::answer; +use crate::diff::{self, Hunk}; +use crate::dotenv::{self, Doc, Edits}; +use crate::gitignore; +use crate::js; +use crate::logic::{self, Groups, Params}; +use crate::validate::{self, Check}; + +/// Larger texts are checked when reviewing, not at each keystroke. +const VALIDATE_WHILE_TYPING_MAX: usize = 100_000; +/// The diff's lines given to Hangar at once: it asks for others as they scroll in. +pub const DIFF_WINDOW: u32 = 400; + +/// What the page shows. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Screen { + Loading, + Picker, + Dotenv, + Text, + Error, +} + +/// A key of the form. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct KeyRow { + pub key: String, + pub asked: bool, + /// In the file when it was read. + pub present: bool, + pub original: Option, + pub value: String, + pub hint: String, + pub count: usize, + pub revealed: bool, + /// Added by a click: written even empty. + pub added: bool, + /// Typed by the person: counted, never named, to the agent. + pub typed: bool, +} + +impl KeyRow { + fn fresh(key: String, asked: bool, hint: String, added: bool, typed: bool) -> Self { + KeyRow { + key, + asked, + present: false, + original: None, + value: String::new(), + hint, + count: 0, + revealed: false, + added, + typed, + } + } + + pub fn missing(&self) -> bool { + self.asked && self.value.is_empty() + } + + pub fn changed(&self) -> bool { + match &self.original { + Some(original) if self.present => self.value != *original, + _ => !self.value.is_empty(), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Offer { + pub key: String, + pub hint: String, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Form { + pub rows: Vec, + /// Keys of the template, missing here. + pub offered: Vec, + pub example_name: Option, + pub other_lines: usize, + pub new_key: String, + /// Its string's key: `newKeyBad`, `newKeyTaken`. + pub new_key_problem: Option<&'static str>, +} + +impl Form { + fn row_mut(&mut self, key: &str) -> Option<&mut KeyRow> { + self.rows.iter_mut().find(|row| row.key == key) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum IgnoreStatus { + Ignored, + NotIgnored, + NoFile, + Unknown, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Ignore { + pub status: IgnoreStatus, + pub busy: bool, + /// What the write of .gitignore was answered: a code. + pub problem: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Stage { + Edit, + Review, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TextState { + pub value: String, + /// What the disk holds, as the editor holds it (`\n` only). + pub original: String, + pub stage: Stage, + pub check: Check, + /// The person said they know it is broken. + pub ack: bool, + pub hunks: Option>, + /// The line asked for, marked. + pub target: Option, + /// The line asked for and how many the file has, when it is past its end. + pub far: Option<(u32, usize)>, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Side { + Mine, + Theirs, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ConflictRow { + pub key: String, + pub mine: String, + /// None: absent on disk. + pub theirs: Option, + pub choice: Side, + pub revealed: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ConflictKind { + Text { + hunks: Vec, + }, + Dotenv { + rows: Vec, + edits: Edits, + changed_on_disk: usize, + }, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Conflict { + /// What the disk holds now; none when the file is gone. + pub theirs: Option, + pub kind: ConflictKind, +} + +impl Conflict { + pub fn gone(&self) -> bool { + self.theirs.is_none() + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TellStatus { + Sent, + Checked, + Failed, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Told { + pub status: TellStatus, + pub pane: String, + pub code: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Problem { + /// `denied`, `rate_limited`, `invalid` or `other`. + pub code: String, + pub detail: String, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PageError { + /// `denied`, `invalid`, `bad-path`, `failed`, `unavailable`, `timeout`, `error`. + pub kind: String, + pub detail: String, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Picker { + pub groups: Groups, + pub filter: String, + pub truncated: bool, +} + +/// The .gitignore files that have a say, read one after the other. +#[derive(Debug, Clone)] +struct Scan { + remaining: VecDeque<(String, String)>, + reading: Option, + found: Vec, +} + +impl Scan { + /// The scan, or the answer at once: a template is meant to be committed. + fn of(path: &str) -> Result { + if dotenv::is_example_path(path) { + return Err(IgnoreStatus::Ignored); + } + Ok(Scan { + remaining: gitignore::sources_for(path).into(), + reading: None, + found: Vec::new(), + }) + } + + /// The next file to read, or none when all are read. + fn next(&mut self) -> Option { + let (dir, path) = self.remaining.pop_front()?; + self.reading = Some(dir); + Some(path) + } + + /// The answer to the read of the last file asked for: none to go on. + fn take(&mut self, answer: Result) -> Option { + let dir = self.reading.take().unwrap_or_default(); + match answer { + Ok(text) => self.found.push(gitignore::Source { dir, text }), + Err(error) if error.is(KitError::NOT_FOUND) => {} + Err(_) => return Some(IgnoreStatus::Unknown), + } + None + } + + fn status(&self, path: &str) -> IgnoreStatus { + if self.found.is_empty() { + IgnoreStatus::NoFile + } else if gitignore::is_ignored(&self.found, path) { + IgnoreStatus::Ignored + } else { + IgnoreStatus::NotIgnored + } + } +} + +/// A dotenv file being opened: its template looked for, then git asked. +#[derive(Debug, Clone)] +struct Opening { + token: u64, + path: String, + text: Option, + candidates: VecDeque, + reading: Option, + example: Option<(String, Doc)>, + scan: Option, +} + +/// A line being added to .gitignore, then git asked again. +#[derive(Debug, Clone)] +struct Adding { + token: u64, + path: String, + scan: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum SaveKind { + Form, + Text, +} + +/// A save under way: `files.write`, with what was read as `expected`, or +/// after a look that the new file is still absent. +#[derive(Debug, Clone)] +struct Saving { + token: u64, + text: String, + kind: SaveKind, + expected: bool, +} + +enum Outcome { + Written, + Conflict(Option), + Refused(KitError), +} + +/// What comes once the agent's answer is sent, or could not be. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AfterSend { + /// A save ends. + Saved(u64), + /// A message sent on its own ends. + Done(u64), +} + +#[derive(Debug, Clone)] +pub enum Message { + // Hangar. + Params(TabParamsAnswer), + Theme(Theme), + Opened { + token: u64, + line: Option, + answer: Result, + }, + ExampleRead { + token: u64, + answer: Result, + }, + IgnoreRead { + token: u64, + answer: Result, + }, + Listed { + token: u64, + answer: Result, + }, + SaveChecked { + token: u64, + answer: Result, + }, + SaveWritten { + token: u64, + answer: Result, + }, + SaveTheirs { + token: u64, + answer: Result, + }, + Sent { + token: u64, + pane: String, + status: TellStatus, + after: AfterSend, + answer: Result, + }, + GitignoreRead { + token: u64, + answer: Result, + }, + GitignoreWritten { + token: u64, + answer: Result, + }, + AddScanRead { + token: u64, + answer: Result, + }, + Leave(bool), + // The person. + Pick(String), + Filter(String), + Back, + Retry, + EditRow(String, String), + ToggleReveal(String), + AddOffered(String), + AddAllOffered, + NewKey(String), + AddNewKey, + AddToGitignore, + SaveForm, + EditText(String), + Review, + BackToEdit, + Ack(bool), + SaveText, + DiffRange(Range), + ConflictChoose(String, Side), + ConflictReveal(String), + ConflictKeepMine, + ConflictTakeTheirs, + ConflictBack, + TellNoChange, + RetryTell, + /// Ctrl+S: in the form it saves, in the editor it reviews. + SaveKey, +} + +pub struct Editor { + pub(crate) t: Strings, + pub screen: Screen, + pub path: Option, + /// The pane that asked. + pub caller: Option, + pub why: Option, + pub asked: Vec, + pub from_picker: bool, + pub exists: bool, + pub busy: bool, + pub problem: Option, + pub saved: bool, + pub told: Option, + pub error: Option, + pub picker: Option, + pub form: Option
, + pub ignore: Option, + pub text: Option, + pub conflict: Option, + /// The diff's lines given: from, to. + pub diff_range: (u32, u32), + + generation: u64, + last_title: Option, + last_badge: Option, + /// The dotenv file as last read or written. + doc: Doc, + /// The exact text the file held when last read; none when absent. + last_read: Option, + example_rows: Vec, + example_name: Option, + example_values: Vec, + /// An answer that could not be sent, to try again as it is. + unsent: Option<(String, TellStatus)>, + opening: Option, + adding: Option, + saving: Option, +} + +/// Names, and the values only to keep them unsaid. +struct DotenvFacts { + known: HashSet, + values: Vec, + still_empty: Vec, + already_set: Vec, +} + +impl Editor { + pub fn t(&self) -> &Strings { + &self.t + } + + fn set_title(&mut self, title: String, cx: &mut Context) { + if self.last_title.as_ref() == Some(&title) { + return; + } + self.last_title = Some(title.clone()); + // A refused title leaves the tab's own. + cx.call_quietly(api::TabSetTitle { title }); + } + + pub fn missing_count(&self) -> usize { + match (&self.form, self.screen) { + (Some(form), Screen::Dotenv) => form.rows.iter().filter(|row| row.missing()).count(), + _ => 0, + } + } + + fn set_badge(&mut self, cx: &mut Context) { + let missing = self.missing_count(); + let badge = if missing > 0 { + Some(( + BadgeState::Neutral, + self.t.tn("badgeMissing", missing as i64, &[]), + )) + } else if self.saved { + Some((BadgeState::Success, self.t.t("badgeSaved"))) + } else { + None + }; + let badge = badge.map(|(state, text)| (state, js::first_chars(&text, 12))); + let key = match &badge { + Some((state, text)) => format!("{state:?}|{text}"), + None => "none".to_owned(), + }; + if self.last_badge.as_ref() == Some(&key) { + return; + } + self.last_badge = Some(key); + let (state, text) = match badge { + Some((state, text)) => (Some(state), Some(text)), + None => (None, None), + }; + cx.call_quietly(api::TabSetBadge { state, text }); + } + + fn show_error( + &mut self, + error: Option<&KitError>, + kind: Option<&str>, + cx: &mut Context, + ) { + const KNOWN: [&str; 5] = ["denied", "invalid", "failed", "unavailable", "timeout"]; + let code = error.map(|error| error.code.as_str()).unwrap_or(""); + let kind = kind.unwrap_or(if KNOWN.contains(&code) { code } else { "error" }); + self.screen = Screen::Error; + self.error = Some(PageError { + kind: kind.to_owned(), + detail: error.map(|error| error.message.clone()).unwrap_or_default(), + }); + self.busy = false; + self.set_badge(cx); + } + + /// Everything a file shows, cleared, and every answer still on its way + /// made stale. + fn reset(&mut self) -> u64 { + self.generation += 1; + self.screen = Screen::Loading; + self.busy = false; + self.problem = None; + self.saved = false; + self.told = None; + self.error = None; + self.conflict = None; + self.form = None; + self.text = None; + self.ignore = None; + self.unsent = None; + self.opening = None; + self.adding = None; + self.saving = None; + self.generation + } + + /* ── the agent's answer ───────────────────────────────────────── */ + + /// The one place that speaks to an agent. `message` comes from + /// `answer`, which is handed no value. + fn send( + &mut self, + message: String, + status: TellStatus, + after: AfterSend, + cx: &mut Context, + ) { + let Some(pane) = self.caller.clone() else { + self.told = None; + self.unsent = None; + self.after_send(after, cx); + return; + }; + self.unsent = Some((message.clone(), status)); + let token = self.generation; + cx.call( + api::PanesSend { + pane: pane.clone(), + text: message, + }, + move |answer| Message::Sent { + token, + pane, + status, + after, + answer, + }, + ); + } + + fn after_send(&mut self, after: AfterSend, cx: &mut Context) { + match after { + AfterSend::Saved(token) if token == self.generation => { + self.busy = false; + self.set_badge(cx); + } + AfterSend::Done(token) if token == self.generation => self.busy = false, + _ => {} + } + } + + fn retry_tell(&mut self, cx: &mut Context) { + if self.busy { + return; + } + let Some((message, status)) = self.unsent.clone() else { + return; + }; + self.busy = true; + self.send(message, status, AfterSend::Done(self.generation), cx); + } + + /* ── dotenv: the form ─────────────────────────────────────────── */ + + fn build_form(&self, doc: &Doc) -> Form { + let present = dotenv::rows(doc); + let by_key: HashMap<&str, &dotenv::Row> = + present.iter().map(|row| (row.key.as_str(), row)).collect(); + let hints: HashMap<&str, &str> = self + .example_rows + .iter() + .map(|row| (row.key.as_str(), row.hint.as_str())) + .collect(); + let make_row = |key: &str, asked: bool| { + let found = by_key.get(key); + let hint = found + .map(|row| row.hint.as_str()) + .filter(|hint| !hint.is_empty()) + .or_else(|| hints.get(key).copied()) + .unwrap_or(""); + KeyRow { + key: key.to_owned(), + asked, + present: found.is_some(), + original: found.map(|row| row.value.clone()), + value: found.map(|row| row.value.clone()).unwrap_or_default(), + hint: hint.to_owned(), + count: found.map_or(0, |row| row.count), + revealed: false, + added: false, + typed: false, + } + }; + let mut rows: Vec = self.asked.iter().map(|key| make_row(key, true)).collect(); + for row in &present { + if !self.asked.contains(&row.key) { + rows.push(make_row(&row.key, false)); + } + } + let shown: HashSet<&str> = rows.iter().map(|row| row.key.as_str()).collect(); + let offered = self + .example_rows + .iter() + .filter(|row| !shown.contains(row.key.as_str())) + .map(|row| Offer { + key: row.key.clone(), + hint: row.hint.clone(), + }) + .collect(); + Form { + rows, + offered, + example_name: self.example_name.clone(), + other_lines: dotenv::other_lines(doc), + new_key: String::new(), + new_key_problem: None, + } + } + + /// What the form changes: key → value. + pub fn form_edits(&self) -> Edits { + let Some(form) = &self.form else { + return Vec::new(); + }; + form.rows + .iter() + .filter(|row| { + if row.present { + row.original.as_ref() != Some(&row.value) + } else { + row.added || !row.value.is_empty() + } + }) + .map(|row| (row.key.clone(), row.value.clone())) + .collect() + } + + fn start_opening(&mut self, path: String, text: Option, cx: &mut Context) { + let candidates = if dotenv::is_example_path(&path) { + VecDeque::new() + } else { + dotenv::example_candidates(&path).into() + }; + self.opening = Some(Opening { + token: self.generation, + path, + text, + candidates, + reading: None, + example: None, + scan: None, + }); + self.step_opening(cx); + } + + /// The next read of a dotenv file being opened, or the form once all are in. + fn step_opening(&mut self, cx: &mut Context) { + let Some(opening) = &mut self.opening else { + return; + }; + let token = opening.token; + if opening.scan.is_none() { + if let Some(candidate) = opening.candidates.pop_front() { + opening.reading = Some(js::base_name(&candidate).to_owned()); + cx.call(api::FilesRead { path: candidate }, move |answer| { + Message::ExampleRead { token, answer } + }); + return; + } + match Scan::of(&opening.path) { + Ok(scan) => opening.scan = Some(scan), + Err(status) => return self.finish_opening(status, cx), + } + } + let scan = opening.scan.as_mut().expect("scanning"); + match scan.next() { + Some(path) => cx.call(api::FilesRead { path }, move |answer| Message::IgnoreRead { + token, + answer, + }), + None => { + let status = scan.status(&opening.path); + self.finish_opening(status, cx); + } + } + } + + fn finish_opening(&mut self, ignore: IgnoreStatus, cx: &mut Context) { + let Some(opening) = self.opening.take() else { + return; + }; + if opening.token != self.generation { + return; + } + self.doc = dotenv::parse(opening.text.as_deref().unwrap_or("")); + match &opening.example { + Some((name, doc)) => { + self.example_rows = dotenv::rows(doc); + self.example_name = Some(name.clone()); + self.example_values = dotenv::all_values(doc); + } + None => { + self.example_rows = Vec::new(); + self.example_name = None; + self.example_values = Vec::new(); + } + } + self.screen = Screen::Dotenv; + self.form = Some(self.build_form(&self.doc)); + self.ignore = Some(Ignore { + status: ignore, + busy: false, + problem: None, + }); + self.text = None; + self.busy = false; + self.set_badge(cx); + } + + fn edit_row(&mut self, key: &str, value: String, cx: &mut Context) { + let Some(row) = self.form.as_mut().and_then(|form| form.row_mut(key)) else { + return; + }; + row.value = diff::normalize(&value); + self.saved = false; + self.set_badge(cx); + } + + fn toggle_reveal(&mut self, key: &str) { + if let Some(row) = self.form.as_mut().and_then(|form| form.row_mut(key)) { + row.revealed = !row.revealed; + } + } + + fn add_offered(&mut self, key: &str) { + let Some(form) = &mut self.form else { + return; + }; + let Some(at) = form.offered.iter().position(|offer| offer.key == key) else { + return; + }; + let offer = form.offered.remove(at); + form.rows + .push(KeyRow::fresh(offer.key, false, offer.hint, true, false)); + } + + fn add_all_offered(&mut self) { + let keys: Vec = match &self.form { + Some(form) => form.offered.iter().map(|offer| offer.key.clone()).collect(), + None => return, + }; + for key in keys { + self.add_offered(&key); + } + } + + /// A key the person types. It may be a secret pasted in the wrong field, + /// so it is never named to the agent. + fn add_new_key(&mut self) { + let Some(form) = &mut self.form else { + return; + }; + let name = js::trim(&form.new_key).to_owned(); + if !dotenv::is_key(&name) { + form.new_key_problem = Some("newKeyBad"); + } else if form.rows.iter().any(|row| row.key == name) { + form.new_key_problem = Some("newKeyTaken"); + } else { + form.offered.retain(|offer| offer.key != name); + form.rows + .push(KeyRow::fresh(name, false, String::new(), true, true)); + form.new_key = String::new(); + form.new_key_problem = None; + } + } + + /// Names and counts for the agent, read from what the file holds now. + fn dotenv_facts(&self, before: &Doc, after: &Doc) -> DotenvFacts { + let value: HashMap = dotenv::rows(after) + .into_iter() + .map(|row| (row.key, row.value)) + .collect(); + let typed: HashSet<&str> = self + .form + .iter() + .flat_map(|form| &form.rows) + .filter(|row| row.typed) + .map(|row| row.key.as_str()) + .collect(); + let mut known: HashSet = self.asked.iter().cloned().collect(); + known.extend(self.example_rows.iter().map(|row| row.key.clone())); + known.extend(dotenv::rows(before).into_iter().map(|row| row.key)); + known.retain(|name| !typed.contains(name.as_str())); + let mut values = dotenv::all_values(before); + values.extend(dotenv::all_values(after)); + values.extend(self.example_values.iter().cloned()); + let filled = |key: &String| value.get(key).is_some_and(|value| !value.is_empty()); + DotenvFacts { + known, + values, + still_empty: self + .asked + .iter() + .filter(|key| !filled(key)) + .cloned() + .collect(), + already_set: self + .asked + .iter() + .filter(|key| filled(key)) + .cloned() + .collect(), + } + } + + fn after_form_save(&mut self, written: &str, token: u64, cx: &mut Context) { + let before = self.doc.clone(); + let after = dotenv::parse(written); + let changed = dotenv::changed_keys(&before, &after); + let facts = self.dotenv_facts(&before, &after); + let path = self.path.clone().unwrap_or_default(); + let message = answer::dotenv_saved( + &answer::Facts { + path: &path, + known: &facts.known, + values: &facts.values, + }, + &changed.set, + &changed.emptied, + &facts.still_empty, + ); + self.form = Some(self.build_form(&after)); + self.doc = after; + self.exists = true; + self.saved = true; + self.send(message, TellStatus::Sent, AfterSend::Saved(token), cx); + } + + fn save_form(&mut self, cx: &mut Context) { + if self.screen != Screen::Dotenv || self.busy || self.conflict.is_some() { + return; + } + let edits = self.form_edits(); + if edits.is_empty() { + return; + } + let text = dotenv::serialize(&dotenv::with_values(&self.doc, &edits)); + self.persist(text, SaveKind::Form, cx); + } + + fn add_to_gitignore(&mut self, cx: &mut Context) { + let Some(path) = self.path.clone() else { + return; + }; + let Some(ignore) = &mut self.ignore else { + return; + }; + if ignore.busy { + return; + } + ignore.busy = true; + ignore.problem = None; + let token = self.generation; + self.adding = Some(Adding { + token, + path, + scan: None, + }); + cx.call( + api::FilesRead { + path: ".gitignore".into(), + }, + move |answer| Message::GitignoreRead { token, answer }, + ); + } + + fn adding_failed(&mut self, code: &str) { + self.adding = None; + if let Some(ignore) = &mut self.ignore { + ignore.busy = false; + ignore.problem = Some(if code.is_empty() { "other" } else { code }.to_owned()); + } + } + + fn step_adding(&mut self, cx: &mut Context) { + let Some(adding) = &mut self.adding else { + return; + }; + let token = adding.token; + let status = match &mut adding.scan { + None => match Scan::of(&adding.path) { + Ok(scan) => { + adding.scan = Some(scan); + return self.step_adding(cx); + } + Err(status) => status, + }, + Some(scan) => match scan.next() { + Some(path) => { + cx.call(api::FilesRead { path }, move |answer| { + Message::AddScanRead { token, answer } + }); + return; + } + None => scan.status(&adding.path), + }, + }; + self.adding = None; + self.ignore = Some(Ignore { + status, + busy: false, + problem: None, + }); + } + + /* ── any other text file: the editor ──────────────────────────── */ + + fn open_text( + &mut self, + path: &str, + text: Option<&str>, + line: Option, + cx: &mut Context, + ) { + let original = diff::normalize(text.unwrap_or("")); + let total = original.split('\n').count(); + let jump = line.map(|line| (line as usize).min(total) as u32); + self.screen = Screen::Text; + self.form = None; + self.ignore = None; + self.busy = false; + self.text = Some(TextState { + value: original.clone(), + check: validate::validate(path, &original), + original, + stage: Stage::Edit, + ack: false, + hunks: None, + target: jump, + far: line + .filter(|line| *line as usize > total) + .map(|line| (line, total)), + }); + self.set_badge(cx); + // The cursor goes there, and the editor scrolls to it. + if let Some(jump) = jump { + cx.cursor_to("editor", jump, 1); + } + } + + fn edit_text(&mut self, value: String, cx: &mut Context) { + let path = self.path.clone().unwrap_or_default(); + let Some(text) = &mut self.text else { + return; + }; + text.value = diff::normalize(&value); + if js::length(&text.value) <= VALIDATE_WHILE_TYPING_MAX { + text.check = validate::validate(&path, &text.value); + text.ack = false; + } + self.saved = false; + self.set_badge(cx); + } + + fn review(&mut self) { + let path = self.path.clone().unwrap_or_default(); + if self.screen != Screen::Text { + return; + } + let Some(text) = &mut self.text else { + return; + }; + text.check = validate::validate(&path, &text.value); + text.ack = false; + text.hunks = Some(diff::hunks(diff::diff_lines(&text.original, &text.value))); + text.stage = Stage::Review; + self.problem = None; + self.diff_range = (0, DIFF_WINDOW); + } + + fn after_text_save(&mut self, written: &str, token: u64, cx: &mut Context) { + let path = self.path.clone().unwrap_or_default(); + if let Some(text) = &mut self.text { + text.original = diff::normalize(written); + text.value = text.original.clone(); + text.stage = Stage::Edit; + text.hunks = None; + text.ack = false; + } + self.exists = true; + self.saved = true; + self.send( + answer::text_saved(&path), + TellStatus::Sent, + AfterSend::Saved(token), + cx, + ); + } + + /// A broken file goes through only once the person has said they know. + fn save_text(&mut self, cx: &mut Context) { + if self.screen != Screen::Text || self.busy || self.conflict.is_some() { + return; + } + let path = self.path.clone().unwrap_or_default(); + let exists = self.exists; + let Some(text) = &mut self.text else { + return; + }; + text.check = validate::validate(&path, &text.value); + if !text.check.ok && !text.ack { + return; + } + if text.value == text.original && exists { + return; + } + let written = diff::restore_eols(self.last_read.as_deref().unwrap_or(""), &text.value); + self.persist(written, SaveKind::Text, cx); + } + + /* ── writing, and what happens when the file moved ────────────── */ + + /// `expected` cannot say "still absent", so a new file is looked for + /// again just before. + fn persist(&mut self, text: String, kind: SaveKind, cx: &mut Context) { + let token = self.generation; + self.busy = true; + self.problem = None; + self.saved = false; + self.told = None; + let path = self.path.clone().unwrap_or_default(); + self.saving = Some(Saving { + token, + text: text.clone(), + kind, + expected: self.last_read.is_some(), + }); + match self.last_read.clone() { + None => cx.call(api::FilesRead { path }, move |answer| { + Message::SaveChecked { token, answer } + }), + Some(expected) => cx.call( + api::FilesWrite { + path, + text, + expected: Some(expected), + }, + move |answer| Message::SaveWritten { token, answer }, + ), + } + } + + fn saving(&self, token: u64) -> Option<&Saving> { + self.saving.as_ref().filter(|saving| saving.token == token) + } + + fn saved_as(&mut self, outcome: Outcome, cx: &mut Context) { + let Some(saving) = self.saving.take() else { + return; + }; + if saving.token != self.generation { + return; + } + match outcome { + Outcome::Refused(error) => { + self.busy = false; + let code = if ["denied", "rate_limited", "invalid"].contains(&error.code.as_str()) { + error.code + } else { + "other".to_owned() + }; + self.problem = Some(Problem { + code, + detail: error.message, + }); + } + Outcome::Conflict(theirs) => { + self.busy = false; + self.conflict = Some(if self.screen == Screen::Dotenv { + self.form_conflict(theirs) + } else { + self.text_conflict(theirs) + }); + self.diff_range = (0, DIFF_WINDOW); + } + Outcome::Written => { + self.last_read = Some(saving.text.clone()); + match saving.kind { + SaveKind::Form => self.after_form_save(&saving.text, saving.token, cx), + SaveKind::Text => self.after_text_save(&saving.text, saving.token, cx), + } + } + } + } + + fn text_conflict(&self, theirs: Option) -> Conflict { + let mine = self + .text + .as_ref() + .map(|text| text.value.as_str()) + .unwrap_or(""); + let disk = diff::normalize(theirs.as_deref().unwrap_or("")); + Conflict { + kind: ConflictKind::Text { + hunks: diff::hunks(diff::diff_lines(&disk, mine)), + }, + theirs, + } + } + + fn form_conflict(&self, theirs: Option) -> Conflict { + let edits = self.form_edits(); + let their_doc = dotenv::parse(theirs.as_deref().unwrap_or("")); + let disk: HashMap = dotenv::rows(&their_doc) + .into_iter() + .map(|row| (row.key, row.value)) + .collect(); + let rows = edits + .iter() + .filter(|(key, mine)| disk.get(key) != Some(mine)) + .map(|(key, mine)| ConflictRow { + key: key.clone(), + mine: mine.clone(), + theirs: disk.get(key).cloned(), + choice: Side::Mine, + revealed: false, + }) + .collect(); + let was: Vec = dotenv::rows(&self.doc); + let was_map: HashMap<&str, &str> = was + .iter() + .map(|row| (row.key.as_str(), row.value.as_str())) + .collect(); + let edited: HashSet<&str> = edits.iter().map(|(key, _)| key.as_str()).collect(); + let mut keys: Vec<&str> = was.iter().map(|row| row.key.as_str()).collect(); + let their_rows = dotenv::rows(&their_doc); + keys.extend(their_rows.iter().map(|row| row.key.as_str())); + let mut seen = HashSet::new(); + let changed_on_disk = keys + .into_iter() + .filter(|key| seen.insert(*key)) + .filter(|key| { + !edited.contains(key) + && was_map.get(key).copied() != disk.get(*key).map(String::as_str) + }) + .count(); + Conflict { + kind: ConflictKind::Dotenv { + rows, + edits, + changed_on_disk, + }, + theirs, + } + } + + fn conflict_row(&mut self, key: &str) -> Option<&mut ConflictRow> { + match &mut self.conflict { + Some(Conflict { + kind: ConflictKind::Dotenv { rows, .. }, + .. + }) => rows.iter_mut().find(|row| row.key == key), + _ => None, + } + } + + /// Mine wins, on top of what the disk holds now. Only ever on the + /// person's click. + fn conflict_keep_mine(&mut self, cx: &mut Context) { + if self.busy { + return; + } + let Some(conflict) = self.conflict.take() else { + return; + }; + self.last_read = conflict.theirs.clone(); + let theirs = conflict.theirs.as_deref().unwrap_or(""); + match conflict.kind { + ConflictKind::Text { .. } => { + let Some(text) = &mut self.text else { + return; + }; + text.original = diff::normalize(theirs); + let written = diff::restore_eols(theirs, &text.value); + self.persist(written, SaveKind::Text, cx); + } + ConflictKind::Dotenv { rows, edits, .. } => { + let dropped: HashSet<&str> = rows + .iter() + .filter(|row| row.choice == Side::Theirs) + .map(|row| row.key.as_str()) + .collect(); + let edits: Edits = edits + .into_iter() + .filter(|(key, _)| !dropped.contains(key.as_str())) + .collect(); + self.doc = dotenv::parse(theirs); + let written = dotenv::serialize(&dotenv::with_values(&self.doc, &edits)); + self.persist(written, SaveKind::Form, cx); + } + } + } + + /// What is on disk wins, and what the person typed is dropped: only on + /// their click too. + fn conflict_take_theirs(&mut self, cx: &mut Context) { + if self.busy { + return; + } + let Some(conflict) = self.conflict.take() else { + return; + }; + self.last_read = conflict.theirs.clone(); + self.exists = conflict.theirs.is_some(); + self.saved = false; + self.told = None; + self.problem = None; + let path = self.path.clone().unwrap_or_default(); + self.load_into(path, conflict.theirs, None, cx); + } + + /// Back to the text with mine, measured against what the disk holds now. + fn conflict_back(&mut self) { + if !matches!( + &self.conflict, + Some(Conflict { + kind: ConflictKind::Text { .. }, + .. + }) + ) { + return; + } + let Some(conflict) = self.conflict.take() else { + return; + }; + self.exists = conflict.theirs.is_some(); + if let Some(text) = &mut self.text { + text.original = diff::normalize(conflict.theirs.as_deref().unwrap_or("")); + text.stage = Stage::Edit; + } + self.last_read = conflict.theirs; + } + + /// The person looked and has nothing to change: the waiting agent still + /// hears of it. + fn tell_no_change(&mut self, cx: &mut Context) { + if self.caller.is_none() || self.busy { + return; + } + let path = self.path.clone().unwrap_or_default(); + let message = match self.screen { + Screen::Dotenv => { + if !self.form_edits().is_empty() { + return; + } + let facts = self.dotenv_facts(&self.doc, &self.doc); + answer::dotenv_checked( + &answer::Facts { + path: &path, + known: &facts.known, + values: &facts.values, + }, + &facts.already_set, + &facts.still_empty, + ) + } + Screen::Text => { + match &self.text { + Some(text) if text.value == text.original => {} + _ => return, + } + answer::text_checked(&path) + } + _ => return, + }; + self.busy = true; + self.send( + message, + TellStatus::Checked, + AfterSend::Done(self.generation), + cx, + ); + } + + /* ── opening ──────────────────────────────────────────────────── */ + + fn load_into( + &mut self, + path: String, + text: Option, + line: Option, + cx: &mut Context, + ) { + if dotenv::is_dotenv_path(&path) { + // Its template and git are asked first: nothing to edit meanwhile. + self.screen = Screen::Loading; + self.start_opening(path, text, cx); + } else { + self.open_text(&path, text.as_deref(), line, cx); + } + } + + fn open(&mut self, path: String, line: Option, cx: &mut Context) { + let token = self.reset(); + self.path = Some(path.clone()); + self.set_title(logic::tab_title(&path), cx); + cx.call(api::FilesRead { path }, move |answer| Message::Opened { + token, + line, + answer, + }); + } + + fn show_picker(&mut self, cx: &mut Context) { + let token = self.reset(); + self.path = None; + self.from_picker = false; + let title = self.t.t("tab"); + self.set_title(title, cx); + self.set_badge(cx); + cx.call(api::FilesList::default(), move |answer| Message::Listed { + token, + answer, + }); + } + + fn pick(&mut self, path: &str, cx: &mut Context) { + let Some(checked) = logic::check_path(path) else { + return; + }; + self.from_picker = true; + self.open(checked, None, cx); + } + + pub fn is_dirty(&self) -> bool { + match self.screen { + Screen::Dotenv if self.form.is_some() => !self.form_edits().is_empty(), + Screen::Text => self + .text + .as_ref() + .is_some_and(|text| text.value != text.original), + _ => false, + } + } + + /// Asked for again: the latest to ask is the one to answer, and what was + /// typed stays. + fn handle_params(&mut self, read: Params, cx: &mut Context) { + self.caller = read.caller; + self.unsent = None; + let editing = matches!(self.screen, Screen::Dotenv | Screen::Text) && self.path.is_some(); + if editing && (read.path.is_none() || read.path == self.path) { + self.why = read.why; + if self.screen == Screen::Dotenv && !read.keys.is_empty() { + let fresh: Vec = read + .keys + .into_iter() + .filter(|key| !self.asked.contains(key)) + .collect(); + self.asked.extend(fresh.iter().cloned()); + if let Some(form) = &mut self.form { + for key in fresh { + match form.row_mut(&key) { + Some(row) => row.asked = true, + None => { + form.offered.retain(|offer| offer.key != key); + form.rows.push(KeyRow::fresh( + key, + true, + String::new(), + false, + false, + )); + } + } + } + form.rows.sort_by_key(|row| !row.asked); + } + } + self.told = None; + self.saved = false; + self.set_badge(cx); + return; + } + if read.bad_path { + self.path = None; + self.show_error(None, Some("bad-path"), cx); + return; + } + self.why = read.why; + self.asked = read.keys; + self.from_picker = false; + match read.path { + Some(path) => self.open(path, read.line, cx), + None => self.show_picker(cx), + } + } + + fn go_back(&mut self, cx: &mut Context) { + if !self.is_dirty() { + return self.show_picker(cx); + } + cx.confirm( + api::Confirm { + message: self.t.t("leaveMessage"), + confirm: Some(self.t.t("leaveConfirm")), + cancel: Some(self.t.t("leaveCancel")), + danger: true, + }, + Message::Leave, + ); + } + + /// Whether Ctrl+S means something now. + pub fn save_key(&self) -> bool { + self.conflict.is_none() + && match self.screen { + Screen::Dotenv => true, + Screen::Text => self + .text + .as_ref() + .is_some_and(|text| text.stage == Stage::Edit), + _ => false, + } + } +} + +fn read_or_none(answer: Result) -> Result, KitError> { + match answer { + Ok(text) => Ok(Some(text)), + Err(error) if error.is(KitError::NOT_FOUND) => Ok(None), + Err(error) => Err(error), + } +} + +impl Kit for Editor { + type Message = Message; + + fn init(start: &Start, cx: &mut Context) -> Self { + let mut editor = Editor { + t: logic::strings(&start.theme.locale), + screen: Screen::Loading, + path: None, + caller: None, + why: None, + asked: Vec::new(), + from_picker: false, + exists: false, + busy: false, + problem: None, + saved: false, + told: None, + error: None, + picker: None, + form: None, + ignore: None, + text: None, + conflict: None, + diff_range: (0, DIFF_WINDOW), + generation: 0, + last_title: None, + last_badge: None, + doc: dotenv::parse(""), + last_read: None, + example_rows: Vec::new(), + example_name: None, + example_values: Vec::new(), + unsent: None, + opening: None, + adding: None, + saving: None, + }; + // The page asked `tab.params`; a native tab is started with them. + let caller = start.tab.caller.as_ref().map(|caller| caller.pane.as_str()); + editor.handle_params(logic::read_params(&start.tab.params, caller), cx); + editor + } + + fn update(&mut self, message: Message, cx: &mut Context) { + match message { + Message::Params(answer) => { + let caller = answer.caller.as_ref().map(|caller| caller.pane.as_str()); + let read = logic::read_params(&answer.params, caller); + self.handle_params(read, cx); + } + Message::Theme(theme) => self.t.set_locale(theme.locale), + Message::Opened { + token, + line, + answer, + } => { + if token != self.generation { + return; + } + let text = match read_or_none(answer) { + Ok(text) => text, + Err(error) => return self.show_error(Some(&error), None, cx), + }; + self.last_read = text.clone(); + self.exists = text.is_some(); + let path = self.path.clone().unwrap_or_default(); + self.load_into(path, text, line, cx); + } + Message::ExampleRead { token, answer } => { + let Some(opening) = self + .opening + .as_mut() + .filter(|opening| opening.token == token) + else { + return; + }; + let name = opening.reading.take().unwrap_or_default(); + match read_or_none(answer) { + Ok(Some(text)) => { + opening.example = Some((name, dotenv::parse(&text))); + opening.candidates.clear(); + } + Ok(None) => {} + // No template to offer: the form works without. + Err(_) => opening.candidates.clear(), + } + self.step_opening(cx); + } + Message::IgnoreRead { token, answer } => { + let Some(opening) = self + .opening + .as_mut() + .filter(|opening| opening.token == token) + else { + return; + }; + let Some(scan) = opening.scan.as_mut() else { + return; + }; + match scan.take(answer) { + Some(status) => self.finish_opening(status, cx), + None => self.step_opening(cx), + } + } + Message::Listed { token, answer } => { + if token != self.generation { + return; + } + match answer { + Err(error) => self.show_error(Some(&error), None, cx), + Ok(listing) => { + self.picker = Some(Picker { + groups: logic::rank_files( + listing.files.iter().map(|file| file.path.as_str()), + ), + filter: String::new(), + truncated: listing.truncated, + }); + self.screen = Screen::Picker; + } + } + } + Message::SaveChecked { token, answer } => { + let Some(saving) = self.saving(token).cloned() else { + return; + }; + match read_or_none(answer) { + Ok(Some(now)) => self.saved_as(Outcome::Conflict(Some(now)), cx), + Ok(None) => { + let path = self.path.clone().unwrap_or_default(); + cx.call( + api::FilesWrite { + path, + text: saving.text, + expected: None, + }, + move |answer| Message::SaveWritten { token, answer }, + ); + } + Err(error) => self.saved_as(Outcome::Refused(error), cx), + } + } + Message::SaveWritten { token, answer } => { + let Some(saving) = self.saving(token).cloned() else { + return; + }; + match answer { + Ok(_) => self.saved_as(Outcome::Written, cx), + Err(error) if error.is(KitError::CONFLICT) && saving.expected => { + let path = self.path.clone().unwrap_or_default(); + cx.call(api::FilesRead { path }, move |answer| Message::SaveTheirs { + token, + answer, + }); + } + Err(error) => self.saved_as(Outcome::Refused(error), cx), + } + } + Message::SaveTheirs { token, answer } => { + if self.saving(token).is_none() { + return; + } + match read_or_none(answer) { + Ok(theirs) => self.saved_as(Outcome::Conflict(theirs), cx), + Err(error) => self.saved_as(Outcome::Refused(error), cx), + } + } + Message::Sent { + token, + pane, + status, + after, + answer, + } => { + if token == self.generation { + match answer { + Ok(_) => { + self.told = Some(Told { + status, + pane, + code: None, + }); + self.unsent = None; + } + Err(error) => { + let code = if error.code.is_empty() { + "other".to_owned() + } else { + error.code + }; + self.told = Some(Told { + status: TellStatus::Failed, + pane, + code: Some(code), + }); + } + } + } + self.after_send(after, cx); + } + Message::GitignoreRead { token, answer } => { + let Some(adding) = self.adding.as_ref().filter(|adding| adding.token == token) + else { + return; + }; + let current = match read_or_none(answer) { + Ok(current) => current, + Err(error) => return self.adding_failed(&error.code), + }; + let text = gitignore::with_pattern( + current.as_deref().unwrap_or(""), + &gitignore::pattern_for(&adding.path), + ); + cx.call( + api::FilesWrite { + path: ".gitignore".into(), + text, + expected: current, + }, + move |answer| Message::GitignoreWritten { token, answer }, + ); + } + Message::GitignoreWritten { token, answer } => { + if !self + .adding + .as_ref() + .is_some_and(|adding| adding.token == token) + { + return; + } + match answer { + Ok(_) => self.step_adding(cx), + Err(error) => self.adding_failed(&error.code), + } + } + Message::AddScanRead { token, answer } => { + let Some(adding) = self.adding.as_mut().filter(|adding| adding.token == token) + else { + return; + }; + let Some(scan) = adding.scan.as_mut() else { + return; + }; + match scan.take(answer) { + Some(status) => { + self.adding = None; + self.ignore = Some(Ignore { + status, + busy: false, + problem: None, + }); + } + None => self.step_adding(cx), + } + } + Message::Leave(true) => self.show_picker(cx), + Message::Leave(false) => {} + Message::Pick(path) => self.pick(&path, cx), + Message::Filter(filter) => { + if let Some(picker) = &mut self.picker { + picker.filter = filter; + } + } + Message::Back => self.go_back(cx), + Message::Retry => match self.path.clone() { + Some(path) => self.open(path, None, cx), + None => self.show_picker(cx), + }, + Message::EditRow(key, value) => self.edit_row(&key, value, cx), + Message::ToggleReveal(key) => self.toggle_reveal(&key), + Message::AddOffered(key) => self.add_offered(&key), + Message::AddAllOffered => self.add_all_offered(), + Message::NewKey(name) => { + if let Some(form) = &mut self.form { + form.new_key = name; + form.new_key_problem = None; + } + } + Message::AddNewKey => self.add_new_key(), + Message::AddToGitignore => self.add_to_gitignore(cx), + Message::SaveForm => self.save_form(cx), + Message::EditText(value) => self.edit_text(value, cx), + Message::Review => self.review(), + Message::BackToEdit => { + if let Some(text) = &mut self.text { + text.stage = Stage::Edit; + } + } + Message::Ack(on) => { + if let Some(text) = &mut self.text { + text.ack = on; + } + } + Message::SaveText => self.save_text(cx), + Message::DiffRange(range) => { + self.diff_range = (range.start, range.end.max(range.start)) + } + Message::ConflictChoose(key, side) => { + if let Some(row) = self.conflict_row(&key) { + row.choice = side; + } + } + Message::ConflictReveal(key) => { + if let Some(row) = self.conflict_row(&key) { + row.revealed = !row.revealed; + } + } + Message::ConflictKeepMine => self.conflict_keep_mine(cx), + Message::ConflictTakeTheirs => self.conflict_take_theirs(cx), + Message::ConflictBack => self.conflict_back(), + Message::TellNoChange => self.tell_no_change(cx), + Message::RetryTell => self.retry_tell(cx), + Message::SaveKey => { + if !self.save_key() { + return; + } + match self.screen { + Screen::Dotenv => self.save_form(cx), + _ => self.review(), + } + } + } + } + + fn view(&self) -> Element { + crate::view::view(self) + } + + fn subscriptions(&self) -> Subscriptions { + let subscriptions = Subscriptions::none() + .tab_params(Message::Params) + .theme(Message::Theme); + if self.save_key() { + subscriptions.shortcut("mod+s", Message::SaveKey) + } else { + subscriptions + } + } +} diff --git a/native/src/gitignore.rs b/native/src/gitignore.rs new file mode 100644 index 0000000..861e184 --- /dev/null +++ b/native/src/gitignore.rs @@ -0,0 +1,343 @@ +//! Whether .gitignore files ignore a path, by git's own rules. What git also +//! reads and a tab cannot (.git/info/exclude, the global excludes, whether the +//! file is already tracked) is said in the README. gitignore.js, ported: the +//! page turned each pattern into a regular expression; this matches the same +//! strings with the same rules, without one. + +use crate::js; + +/// A character class's member. +#[derive(Debug, Clone, PartialEq)] +enum Member { + One(char), + Range(char, char), +} + +#[derive(Debug, Clone, PartialEq)] +enum Token { + Literal(char), + /// `*`: `[^/]*`. + Star, + /// `?`: `[^/]`. + One, + /// `[…]`. + Class { + negated: bool, + members: Vec, + }, + /// `**/`, and what an unanchored pattern starts with: `(?:.*/)?`. + Dirs, + /// A trailing `/**`: `.+`. + Rest, +} + +#[derive(Debug, Clone, PartialEq)] +struct Pattern { + tokens: Vec, +} + +/// What the page escaped before putting a character in a class: an escaped +/// `-` is no range. +fn special(c: char) -> bool { + "\\^$.*+?()[]{}|/-".contains(c) +} + +/// A character class at `at`, and where it ends; none if it never closes or +/// is no class a regular expression takes. +fn char_class(glob: &[char], at: usize) -> Option> { + let mut i = at + 1; + let mut negated = false; + // Its characters, and whether each is an escaped one. + let mut atoms: Vec<(char, bool)> = Vec::new(); + if matches!(glob.get(i), Some('!' | '^')) { + negated = true; + i += 1; + } + if glob.get(i) == Some(&']') { + atoms.push((']', true)); + i += 1; + } + let mut end = None; + while i < glob.len() { + let c = glob[i]; + if c == ']' { + end = Some(i); + break; + } + if c == '\\' && i + 1 < glob.len() { + i += 1; + atoms.push((glob[i], special(glob[i]))); + } else if c == '[' { + atoms.push(('[', true)); + } else { + atoms.push((c, false)); + } + i += 1; + } + let end = end?; + let mut members = Vec::new(); + let mut k = 0; + while k < atoms.len() { + let (c, _) = atoms[k]; + if k + 2 < atoms.len() && atoms[k + 1] == ('-', false) { + let to = atoms[k + 2].0; + if to < c { + // A range out of order: the page's RegExp threw, and the rule went. + return Some(Err(())); + } + members.push(Member::Range(c, to)); + k += 3; + } else { + members.push(Member::One(c)); + k += 1; + } + } + Some(Ok((Token::Class { negated, members }, end))) +} + +fn compile(glob: &str) -> Option { + let anchored = glob.contains('/'); + let body: Vec = glob.strip_prefix('/').unwrap_or(glob).chars().collect(); + let mut tokens = Vec::new(); + if !anchored { + tokens.push(Token::Dirs); + } + let mut i = 0; + while i < body.len() { + let c = body[i]; + if c == '*' && body.get(i + 1) == Some(&'*') && (i == 0 || body[i - 1] == '/') { + if body.get(i + 2) == Some(&'/') { + tokens.push(Token::Dirs); + i += 3; + continue; + } + if i + 2 == body.len() { + tokens.push(Token::Rest); + i += 2; + continue; + } + } + if c == '*' { + while body.get(i + 1) == Some(&'*') { + i += 1; + } + tokens.push(Token::Star); + } else if c == '?' { + tokens.push(Token::One); + } else if c == '\\' && i + 1 < body.len() { + i += 1; + tokens.push(Token::Literal(body[i])); + } else if c == '[' { + match char_class(&body, i) { + Some(Ok((class, end))) => { + tokens.push(class); + i = end; + } + // Never closes: git's wildmatch matches nothing. + None | Some(Err(())) => return None, + } + } else { + tokens.push(Token::Literal(c)); + } + i += 1; + } + Some(Pattern { tokens }) +} + +impl Pattern { + fn matches(&self, path: &str) -> bool { + let chars: Vec = path.chars().collect(); + let mut memo = vec![None; (self.tokens.len() + 1) * (chars.len() + 1)]; + self.from(0, 0, &chars, &mut memo) + } + + fn from(&self, k: usize, j: usize, s: &[char], memo: &mut Vec>) -> bool { + let slot = k * (s.len() + 1) + j; + if let Some(known) = memo[slot] { + return known; + } + let answer = match self.tokens.get(k) { + None => j == s.len(), + Some(Token::Literal(c)) => s.get(j) == Some(c) && self.from(k + 1, j + 1, s, memo), + Some(Token::One) => { + s.get(j).is_some_and(|c| *c != '/') && self.from(k + 1, j + 1, s, memo) + } + Some(Token::Class { negated, members }) => { + s.get(j).is_some_and(|c| { + let inside = members.iter().any(|member| match member { + Member::One(one) => c == one, + Member::Range(low, high) => (low..=high).contains(&c), + }); + inside != *negated + }) && self.from(k + 1, j + 1, s, memo) + } + Some(Token::Star) => { + let mut end = j; + loop { + if self.from(k + 1, end, s, memo) { + break true; + } + if end >= s.len() || s[end] == '/' { + break false; + } + end += 1; + } + } + Some(Token::Dirs) => { + self.from(k + 1, j, s, memo) + || (j..s.len()) + .take_while(|at| !js::is_line_terminator(s[*at])) + .any(|at| s[at] == '/' && self.from(k + 1, at + 1, s, memo)) + } + Some(Token::Rest) => (j + 1..=s.len()).any(|end| { + !s[j..end].iter().any(|c| js::is_line_terminator(*c)) + && self.from(k + 1, end, s, memo) + }), + }; + memo[slot] = Some(answer); + answer + } +} + +struct Rule { + negated: bool, + dir_only: bool, + pattern: Pattern, +} + +/// The rules of one .gitignore, in order. +fn rules_of(text: &str) -> Vec { + let mut rules = Vec::new(); + for raw in text.split("\r\n").flat_map(|part| part.split(['\n', '\r'])) { + let chars: Vec = raw.chars().collect(); + // Trailing blanks do not count, unless the last is escaped. + let mut end = chars.len(); + while end > 0 && (chars[end - 1] == ' ' || chars[end - 1] == '\t') { + end -= 1; + } + if end < chars.len() && end > 0 && chars[end - 1] == '\\' { + end += 1; + } + let line: String = chars[..end].iter().collect(); + if line.is_empty() || line.starts_with('#') { + continue; + } + let (negated, line) = match line.strip_prefix('!') { + Some(rest) => (true, rest), + None => (false, line.as_str()), + }; + let (dir_only, line) = match line.strip_suffix('/') { + Some(rest) => (true, rest), + None => (false, line), + }; + if line.is_empty() { + continue; + } + if let Some(pattern) = compile(line) { + rules.push(Rule { + negated, + dir_only, + pattern, + }); + } + } + rules +} + +/// A .gitignore and the folder it is in: `""` for the root. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Source { + pub dir: String, + pub text: String, +} + +struct Compiled { + dir: String, + rules: Vec, +} + +/// What the sources say of this path: the last rule that matches wins, +/// deeper files last. +fn decision(sources: &[Compiled], path: &str, is_dir: bool) -> bool { + let mut ignored = false; + for source in sources { + let inside = if source.dir.is_empty() { + path + } else { + match path.strip_prefix(&format!("{}/", source.dir)) { + Some(inside) => inside, + None => continue, + } + }; + for rule in &source.rules { + if (!rule.dir_only || is_dir) && rule.pattern.matches(inside) { + ignored = !rule.negated; + } + } + } + ignored +} + +/// `sources`, root first; `path` relative to the root, with `/`. +pub fn is_ignored(sources: &[Source], path: &str) -> bool { + let compiled: Vec = sources + .iter() + .map(|source| Compiled { + dir: source.dir.clone(), + rules: rules_of(&source.text), + }) + .collect(); + let parts: Vec<&str> = path.split('/').collect(); + // A file cannot be brought back when one of its folders is ignored. + for i in 1..parts.len() { + if decision(&compiled, &parts[..i].join("/"), true) { + return true; + } + } + decision(&compiled, path, false) +} + +/// The .gitignore files that have a say on this path, root first: `(dir, +/// path)`. +pub fn sources_for(path: &str) -> Vec<(String, String)> { + let parts: Vec<&str> = path.split('/').collect(); + let dirs = &parts[..parts.len().saturating_sub(1)]; + let mut out = vec![(String::new(), ".gitignore".to_owned())]; + for i in 1..=dirs.len() { + let dir = dirs[..i].join("/"); + out.push((dir.clone(), format!("{dir}/.gitignore"))); + } + out +} + +/// The line that ignores this very file, for the root's .gitignore. +pub fn pattern_for(path: &str) -> String { + let mut escaped = String::with_capacity(path.len() + 4); + for c in path.chars() { + if matches!(c, '\\' | '*' | '?' | '[') { + escaped.push('\\'); + } + escaped.push(c); + } + let spaces = escaped.len() - escaped.trim_end_matches(' ').len(); + if spaces > 0 { + escaped.truncate(escaped.len() - spaces); + escaped.push_str(&"\\ ".repeat(spaces)); + } + if escaped.starts_with(['#', '!']) { + format!("\\{escaped}") + } else { + escaped + } +} + +/// The text with that line added, in the file's line endings. +pub fn with_pattern(text: &str, pattern: &str) -> String { + let eol = if text.contains("\r\n") { "\r\n" } else { "\n" }; + let closed = if text.is_empty() || text.ends_with(['\r', '\n']) { + text.to_owned() + } else { + format!("{text}{eol}") + }; + format!("{closed}{pattern}{eol}") +} diff --git a/native/src/js.rs b/native/src/js.rs new file mode 100644 index 0000000..5ab2eb1 --- /dev/null +++ b/native/src/js.rs @@ -0,0 +1,117 @@ +//! What the page's code took from JavaScript and Rust spells otherwise: its +//! `trim`, its `.` in a regular expression, its string lengths. And slicing +//! that never panics: a panic's message is logged, and Rust's for a cut +//! inside a character quotes the text, which may be a value. + +/// What `String.prototype.trim` takes away: JavaScript's white space and line +/// terminators, BOM included, U+0085 not. +pub fn is_space(c: char) -> bool { + matches!( + c, + '\u{9}'..='\u{d}' + | ' ' + | '\u{a0}' + | '\u{1680}' + | '\u{2000}'..='\u{200a}' + | '\u{2028}' + | '\u{2029}' + | '\u{202f}' + | '\u{205f}' + | '\u{3000}' + | '\u{feff}' + ) +} + +pub fn trim(text: &str) -> &str { + text.trim_matches(is_space) +} + +/// What `.` in a regular expression does not match. +pub fn is_line_terminator(c: char) -> bool { + matches!(c, '\n' | '\r' | '\u{2028}' | '\u{2029}') +} + +/// `text.length`: UTF-16 code units. +pub fn length(text: &str) -> usize { + text.encode_utf16().count() +} + +/// `text.slice(from, to)` by bytes, or nothing when a bound is not a +/// character's: the parsers only cut where they found an ASCII byte, so the +/// empty answer never happens, and a mistake never becomes a panic. +pub fn cut(text: &str, from: usize, to: usize) -> &str { + text.get(from..to.min(text.len())).unwrap_or("") +} + +/// `text.slice(from)` by bytes, as [`cut`]. +pub fn from(text: &str, at: usize) -> &str { + text.get(at.min(text.len())..).unwrap_or("") +} + +/// The first `n` characters (`Array.from(text).slice(0, n)`). +pub fn first_chars(text: &str, n: usize) -> String { + text.chars().take(n).collect() +} + +/// After the last `/`. +pub fn base_name(path: &str) -> &str { + match path.rfind('/') { + Some(slash) => from(path, slash + 1), + None => path, + } +} + +/// Up to and with the last `/`; empty at the root. +pub fn dir_name(path: &str) -> &str { + match path.rfind('/') { + Some(slash) => cut(path, 0, slash + 1), + None => "", + } +} + +/// Where a 1-based line and column are, in UTF-16 units as the page counted +/// them, of byte `at` of `text`. +pub fn line_of(text: &[u8], at: usize) -> (usize, usize) { + let limit = at.min(text.len()); + let mut line = 1; + let mut start = 0; + for (index, byte) in text[..limit].iter().enumerate() { + if *byte == b'\n' { + line += 1; + start = index + 1; + } + } + let units: usize = text[start..limit] + .iter() + .map(|byte| match byte { + 0x80..=0xbf => 0, // inside a character + 0xf0..=0xff => 2, // a character outside the BMP: a surrogate pair + _ => 1, + }) + .sum(); + (line, units + 1) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn trims_as_javascript_does() { + assert_eq!(trim("\u{feff} a \u{a0}\n"), "a"); + assert_eq!(trim("\u{85}a"), "\u{85}a"); + } + + #[test] + fn cuts_never_panic() { + assert_eq!(cut("é", 0, 1), ""); + assert_eq!(cut("abc", 1, 9), "bc"); + assert_eq!(from("abc", 9), ""); + } + + #[test] + fn lines_and_columns_in_utf16_units() { + assert_eq!(line_of(b"ab\ncd", 4), (2, 2)); + assert_eq!(line_of("é😀x".as_bytes(), 6), (1, 4)); + } +} diff --git a/native/src/lib.rs b/native/src/lib.rs new file mode 100644 index 0000000..dce393a --- /dev/null +++ b/native/src/lib.rs @@ -0,0 +1,29 @@ +//! The Editor kit's tab, native: written in Rust, drawn by Hangar with its +//! own widgets, no page. Built to WebAssembly by scripts/build-native.sh +//! into tabs/editor.wasm, which the manifest's tab `entry` names (schema 2, +//! Hangar 2.0 or later). +//! +//! The parts are the page's, each ported from its file: `dotenv` (reading a +//! dotenv file and writing back only what changed), `answer` (the only +//! sentences an agent ever gets), `validate` (JSON, YAML, TOML), `diff`, +//! `gitignore` (git's ignore rules), `logic` (the words in en and fr, params, +//! the picker's order), `editor` (the behaviour) and `view`. +//! +//! A secret never reaches an agent or a log: the agent's text is built by +//! `answer` from names and counts, this crate logs nothing, a value shows only +//! in its own field (dotted until revealed), and no slicing here can panic, +//! since a panic's message is logged and Rust's quotes the text it cut. + +pub mod answer; +pub mod diff; +pub mod dotenv; +pub mod editor; +pub mod gitignore; +pub mod js; +pub mod logic; +pub mod validate; +pub mod view; + +pub use editor::{Editor, Message}; + +hangar_kit_sdk::export_kit!(Editor); diff --git a/native/src/logic.rs b/native/src/logic.rs new file mode 100644 index 0000000..43e38bf --- /dev/null +++ b/native/src/logic.rs @@ -0,0 +1,786 @@ +//! What is neither a file format nor the behaviour: the tab's words in en and +//! fr, its params read like form input, and the picker's order. logic.js, +//! ported. + +use std::collections::{BTreeMap, HashSet}; + +use hangar_kit_sdk::i18n::Strings; + +use crate::dotenv; +use crate::js; + +pub const EN: &[(&str, &str)] = &[ + ("tab", "Editor"), + ("loading", "Loading…"), + ("retry", "Try again"), + ("back", "← Files"), + ("pickTitle", "Choose a file"), + ("pickFilter", "Filter by name"), + ("groupEnv", "Environment files"), + ("groupConfig", "Configuration files"), + ("groupOther", "Other files"), + ("pickEmpty", "No file matches."), + ("pickNew", "new"), + ( + "pickTruncated", + "This folder holds more files than Hangar lists: use the filter, or ask for the file by its path.", + ), + ("pickMore", "{n} more: filter to find them."), + ("askedBy", "{pane} asks:"), + ("askedAnon", "An agent asks:"), + ( + "newFile", + "This file does not exist yet. Saving creates it.", + ), + ("save", "Save"), + ("saving", "Saving…"), + ("savedLocal", "Saved."), + ("nothingToSave", "Nothing to save yet."), + ("told", "{pane} was told, without any value."), + ("toldText", "{pane} was told the file changed."), + ( + "notTold", + "Saved, but {pane} could not be told: {reason} No value was sent.", + ), + ("tellAgain", "Tell {pane} again"), + ("tellNoChange", "Tell {pane}: nothing to change"), + ("toldNoChange", "{pane} was told you changed nothing."), + ("tell.not_found", "that pane is gone."), + ( + "tell.denied", + "only a Claude Code agent can be told, and this tab must be granted panes.send.", + ), + ( + "tell.unavailable", + "its session does not run Hangar's bridge.", + ), + ("tell.rate_limited", "too many messages this minute."), + ("tell.other", "Hangar refused."), + ("leaveMessage", "Your changes are not saved."), + ("leaveConfirm", "Lose them"), + ("leaveCancel", "Keep editing"), + ("keyMissing", "missing"), + ("keyAsked", "asked"), + ("keySet", "set"), + ("keyChanged", "changed"), + ( + "keyTwice", + "Defined {n} times: this edits the last, the one that is read.", + ), + ("valueHidden", "Hidden"), + ("valueEmpty", "Empty"), + ("valueLines", "Several lines"), + ("show", "Show"), + ("hide", "Hide"), + ("offeredTitle", "In {file}, missing here"), + ("add", "Add"), + ("addAll", "Add all"), + ("newKeyLabel", "Add a key"), + ("newKeyPlaceholder", "KEY_NAME"), + ( + "newKeyBad", + "A key is letters, digits, _ . and -, not starting with a digit.", + ), + ("newKeyTaken", "This key is already in the list."), + ( + "otherLines_one", + "1 line that is not KEY=value is kept as it is.", + ), + ( + "otherLines_other", + "{n} lines that are not KEY=value are kept as they are.", + ), + ("sectionAsked", "Asked for"), + ("sectionFile", "In this file"), + ("noKeys", "No key in this file yet."), + ( + "ignoreWarning", + "{file} is not ignored by git: git would commit it, secrets included.", + ), + ( + "ignoreNoFile", + "There is no .gitignore here: git would commit {file}, secrets included.", + ), + ( + "ignoreUnknown", + "Could not read .gitignore, so this tab cannot say whether git ignores {file}.", + ), + ("ignoreAdd", "Add {pattern} to .gitignore"), + ("ignoreAdding", "Adding…"), + ("ignoreFailed", ".gitignore was not changed: {reason}"), + ("editorLabel", "File contents"), + ("review", "Review changes"), + ("backToEdit", "← Back to editing"), + ("diffTitle", "Changes to save"), + ("diffNone", "Nothing changed."), + ("diffSkip_one", "1 unchanged line"), + ("diffSkip_other", "{n} unchanged lines"), + ("stateNew", "New file"), + ("checkOk", "Valid {kind}"), + ("checkBasic", "{kind}: basic check"), + ("checkBroken", "Broken {kind}"), + ("checkBrokenAt", "Broken {kind}, line {line}"), + ( + "checkPartial", + "{kind}: no problem found. This is a basic check, not a proof.", + ), + ("checkBad", "Broken {kind}: {reason}"), + ("checkBadAt", "Broken {kind}, line {line}: {reason}"), + ("ackBroken", "I know this file is broken: save it anyway."), + ("check.json", "JSON cannot be read past this point."), + ( + "check.yaml-tab", + "a tab in the indentation. YAML indents with spaces.", + ), + ("check.yaml-quote", "a quote that never closes."), + ("check.yaml-bracket", "a bracket that does not match."), + ( + "check.yaml-reserved", + "a value cannot start with @ or ` without quotes.", + ), + ( + "check.toml-trailing", + "something follows the value on this line.", + ), + ("check.toml-string", "a string that never closes."), + ("check.toml-escape", "an escape TOML does not know."), + ("check.toml-key", "a key is expected here."), + ("check.toml-equals", "a key must be followed by =."), + ("check.toml-value", "this value cannot be read."), + ("check.toml-header", "a table header that does not close."), + ("check.toml-duplicate", "this key or table is given twice."), + ( + "lineJumpFar", + "Line {line} was asked for; the file has {total}.", + ), + ( + "conflictTitle", + "This file changed while you were editing it", + ), + ("conflictHint", "Nothing was written. Choose what to keep."), + ( + "conflictGone", + "The file was deleted while you were editing it. Nothing was written.", + ), + ("conflictDiff", "− on disk now + yours"), + ("conflictKeepMine", "Replace it with mine"), + ("conflictWriteMine", "Write mine"), + ("conflictTakeTheirs", "Keep what is on disk, lose mine"), + ("conflictEdit", "Back to editing, with mine"), + ("conflictRows", "Keys that differ"), + ( + "conflictNone", + "No key disagrees: your changes can go in the new file as they are.", + ), + ("conflictApply", "Save with these choices"), + ( + "conflictTheirsChanged_one", + "1 other key changed on disk, and stays as it is there.", + ), + ( + "conflictTheirsChanged_other", + "{n} other keys changed on disk, and stay as they are there.", + ), + ("stateConflict", "Changed on disk"), + ("mine", "Yours"), + ("theirs", "On disk"), + ("absent", "absent"), + ("err.denied.title", "This tab may not read or write here"), + ( + "err.denied.hint", + "Accept files.read and files.write for this kit in Settings › Kits.", + ), + ("err.invalid.title", "Hangar refused this path"), + ( + "err.invalid.hint", + "A hidden file needs both files.read and files.write. The path must stay inside the workspace folder, outside .git.", + ), + ("err.bad-path.title", "This path cannot be opened"), + ( + "err.bad-path.hint", + "The path must be relative to the workspace folder, with no .. and no drive, outside .git.", + ), + ("err.failed.title", "This file cannot be opened"), + ( + "err.failed.hint", + "Only UTF-8 text files of 1 MB at most can be opened here.", + ), + ("err.unavailable.title", "Hangar cannot do this now"), + ( + "err.unavailable.hint", + "The workspace or its folder may be gone. Reload the tab in a moment.", + ), + ("err.timeout.title", "Hangar did not answer in time"), + ("err.timeout.hint", "Try again."), + ("err.error.title", "Something went wrong"), + ("err.error.hint", "Hangar said:"), + ( + "write.denied", + "this tab was not granted files.write. Your changes are still here.", + ), + ( + "write.rate_limited", + "at most 10 saves a minute. Your changes are still here: try again shortly.", + ), + ( + "write.invalid", + "Hangar refused it (a file holds 1 MB at most). Your changes are still here.", + ), + ( + "write.other", + "it could not be written. Your changes are still here.", + ), + ( + "write.conflict", + ".gitignore changed in the meantime. Click again to use the new one.", + ), + ("badgeMissing", "{n} missing"), + ("stateMissing_one", "{n} missing"), + ("stateMissing_other", "{n} missing"), + ("stateSaved", "Saved"), + ("badgeSaved", "saved"), +]; + +pub const FR: &[(&str, &str)] = &[ + ("tab", "Éditeur"), + ("loading", "Chargement…"), + ("retry", "Réessayer"), + ("back", "← Fichiers"), + ("pickTitle", "Choisir un fichier"), + ("pickFilter", "Filtrer par nom"), + ("groupEnv", "Fichiers d'environnement"), + ("groupConfig", "Fichiers de configuration"), + ("groupOther", "Autres fichiers"), + ("pickEmpty", "Aucun fichier ne correspond."), + ("pickNew", "nouveau"), + ( + "pickTruncated", + "Ce dossier contient plus de fichiers que Hangar n'en liste : utilisez le filtre, ou demandez le fichier par son chemin.", + ), + ("pickMore", "{n} de plus : filtrez pour les trouver."), + ("askedBy", "{pane} demande :"), + ("askedAnon", "Un agent demande :"), + ( + "newFile", + "Ce fichier n'existe pas encore. L'enregistrer le crée.", + ), + ("save", "Enregistrer"), + ("saving", "Enregistrement…"), + ("savedLocal", "Enregistré."), + ("nothingToSave", "Rien à enregistrer pour l'instant."), + ("told", "{pane} a été prévenu, sans aucune valeur."), + ("toldText", "{pane} a été prévenu que le fichier a changé."), + ( + "notTold", + "Enregistré, mais {pane} n'a pas pu être prévenu : {reason} Aucune valeur n'a été envoyée.", + ), + ("tellAgain", "Prévenir {pane} à nouveau"), + ("tellNoChange", "Dire à {pane} : rien à changer"), + ("toldNoChange", "{pane} sait que vous n'avez rien changé."), + ("tell.not_found", "ce panneau n'existe plus."), + ( + "tell.denied", + "seul un agent Claude Code peut être prévenu, et cet onglet doit avoir panes.send.", + ), + ( + "tell.unavailable", + "sa session ne fait pas tourner le pont de Hangar.", + ), + ("tell.rate_limited", "trop de messages cette minute."), + ("tell.other", "Hangar a refusé."), + ("leaveMessage", "Vos changements ne sont pas enregistrés."), + ("leaveConfirm", "Les perdre"), + ("leaveCancel", "Continuer à modifier"), + ("keyMissing", "manquante"), + ("keyAsked", "demandée"), + ("keySet", "remplie"), + ("keyChanged", "modifiée"), + ( + "keyTwice", + "Définie {n} fois : ceci modifie la dernière, celle qui est lue.", + ), + ("valueHidden", "Masquée"), + ("valueEmpty", "Vide"), + ("valueLines", "Plusieurs lignes"), + ("show", "Afficher"), + ("hide", "Masquer"), + ("offeredTitle", "Dans {file}, absentes ici"), + ("add", "Ajouter"), + ("addAll", "Tout ajouter"), + ("newKeyLabel", "Ajouter une clé"), + ("newKeyPlaceholder", "NOM_DE_CLÉ"), + ( + "newKeyBad", + "Une clé s'écrit avec des lettres, des chiffres, _ . et -, sans commencer par un chiffre.", + ), + ("newKeyTaken", "Cette clé est déjà dans la liste."), + ( + "otherLines_one", + "1 ligne qui n'est pas de la forme CLÉ=valeur reste telle quelle.", + ), + ( + "otherLines_other", + "{n} lignes qui ne sont pas de la forme CLÉ=valeur restent telles quelles.", + ), + ("sectionAsked", "Demandées"), + ("sectionFile", "Dans ce fichier"), + ("noKeys", "Aucune clé dans ce fichier pour l'instant."), + ( + "ignoreWarning", + "{file} n'est pas ignoré par git : git le committerait, secrets compris.", + ), + ( + "ignoreNoFile", + "Il n'y a pas de .gitignore ici : git committerait {file}, secrets compris.", + ), + ( + "ignoreUnknown", + "Le .gitignore n'a pas pu être lu : cet onglet ne peut pas dire si git ignore {file}.", + ), + ("ignoreAdd", "Ajouter {pattern} au .gitignore"), + ("ignoreAdding", "Ajout…"), + ( + "ignoreFailed", + "Le .gitignore n'a pas été modifié : {reason}", + ), + ("editorLabel", "Contenu du fichier"), + ("review", "Voir les changements"), + ("backToEdit", "← Revenir à l'édition"), + ("diffTitle", "Changements à enregistrer"), + ("diffNone", "Rien n'a changé."), + ("diffSkip_one", "1 ligne inchangée"), + ("diffSkip_other", "{n} lignes inchangées"), + ("stateNew", "Nouveau fichier"), + ("checkOk", "{kind} valide"), + ("checkBasic", "{kind} : vérification de base"), + ("checkBroken", "{kind} cassé"), + ("checkBrokenAt", "{kind} cassé, ligne {line}"), + ( + "checkPartial", + "{kind} : aucun problème trouvé. C'est une vérification de base, pas une preuve.", + ), + ("checkBad", "{kind} cassé : {reason}"), + ("checkBadAt", "{kind} cassé, ligne {line} : {reason}"), + ( + "ackBroken", + "Je sais que ce fichier est cassé : l'enregistrer quand même.", + ), + ("check.json", "le JSON n'est plus lisible à partir d'ici."), + ( + "check.yaml-tab", + "une tabulation dans l'indentation. YAML indente avec des espaces.", + ), + ("check.yaml-quote", "un guillemet jamais refermé."), + ( + "check.yaml-bracket", + "un crochet ou une accolade qui ne correspond pas.", + ), + ( + "check.yaml-reserved", + "une valeur ne peut pas commencer par @ ou ` sans guillemets.", + ), + ( + "check.toml-trailing", + "quelque chose suit la valeur sur cette ligne.", + ), + ("check.toml-string", "une chaîne jamais refermée."), + ( + "check.toml-escape", + "un échappement que TOML ne connaît pas.", + ), + ("check.toml-key", "une clé est attendue ici."), + ("check.toml-equals", "une clé doit être suivie de =."), + ("check.toml-value", "cette valeur n'est pas lisible."), + ( + "check.toml-header", + "un en-tête de table qui ne se referme pas.", + ), + ( + "check.toml-duplicate", + "cette clé ou cette table apparaît deux fois.", + ), + ( + "lineJumpFar", + "La ligne {line} était demandée ; le fichier en a {total}.", + ), + ( + "conflictTitle", + "Ce fichier a changé pendant que vous le modifiiez", + ), + ( + "conflictHint", + "Rien n'a été écrit. Choisissez ce que vous gardez.", + ), + ( + "conflictGone", + "Le fichier a été supprimé pendant que vous le modifiiez. Rien n'a été écrit.", + ), + ("conflictDiff", "− sur le disque + le vôtre"), + ("conflictKeepMine", "Le remplacer par le mien"), + ("conflictWriteMine", "Écrire le mien"), + ( + "conflictTakeTheirs", + "Garder celui du disque, perdre le mien", + ), + ("conflictEdit", "Revenir à l'édition, avec le mien"), + ("conflictRows", "Clés qui diffèrent"), + ( + "conflictNone", + "Aucune clé ne diverge : vos changements peuvent aller tels quels dans le nouveau fichier.", + ), + ("conflictApply", "Enregistrer avec ces choix"), + ( + "conflictTheirsChanged_one", + "1 autre clé a changé sur le disque, et y reste telle quelle.", + ), + ( + "conflictTheirsChanged_other", + "{n} autres clés ont changé sur le disque, et y restent telles quelles.", + ), + ("stateConflict", "Modifié sur le disque"), + ("mine", "La vôtre"), + ("theirs", "Sur le disque"), + ("absent", "absente"), + ( + "err.denied.title", + "Cet onglet n'a pas le droit de lire ou d'écrire ici", + ), + ( + "err.denied.hint", + "Acceptez files.read et files.write pour ce kit dans Réglages › Kits.", + ), + ("err.invalid.title", "Hangar a refusé ce chemin"), + ( + "err.invalid.hint", + "Un fichier caché demande files.read et files.write à la fois. Le chemin doit rester dans le dossier de l'espace de travail, hors de .git.", + ), + ("err.bad-path.title", "Ce chemin ne peut pas être ouvert"), + ( + "err.bad-path.hint", + "Le chemin doit être relatif au dossier de l'espace de travail, sans .. ni lecteur, hors de .git.", + ), + ("err.failed.title", "Ce fichier ne peut pas être ouvert"), + ( + "err.failed.hint", + "Seuls les fichiers texte UTF-8 de 1 Mo au plus s'ouvrent ici.", + ), + ( + "err.unavailable.title", + "Hangar ne peut pas le faire maintenant", + ), + ( + "err.unavailable.hint", + "L'espace de travail ou son dossier n'existe peut-être plus. Rechargez l'onglet dans un instant.", + ), + ("err.timeout.title", "Hangar n'a pas répondu à temps"), + ("err.timeout.hint", "Réessayez."), + ("err.error.title", "Quelque chose s'est mal passé"), + ("err.error.hint", "Hangar a dit :"), + ( + "write.denied", + "cet onglet n'a pas reçu files.write. Vos changements sont toujours là.", + ), + ( + "write.rate_limited", + "10 enregistrements par minute au plus. Vos changements sont toujours là : réessayez bientôt.", + ), + ( + "write.invalid", + "Hangar a refusé (un fichier fait 1 Mo au plus). Vos changements sont toujours là.", + ), + ( + "write.other", + "il n'a pas pu être écrit. Vos changements sont toujours là.", + ), + ( + "write.conflict", + "le .gitignore a changé entre-temps. Cliquez à nouveau pour partir du nouveau.", + ), + ("badgeMissing", "{n} à remplir"), + ("stateMissing_one", "{n} manquante"), + ("stateMissing_other", "{n} manquantes"), + ("stateSaved", "Enregistré"), + ("badgeSaved", "enregistré"), +]; + +/// The tab's words, in Hangar's language, typeset as `hangar.ui.i18n` does. +pub fn strings(locale: &str) -> Strings { + Strings::new(locale).add("en", EN).add("fr", FR) +} + +/// Whether English has `key`, as the page asked `STRINGS.en[key]`. +pub fn has(key: &str) -> bool { + EN.iter().any(|(known, _)| *known == key) +} + +/// A name for the tab strip: one line, 40 characters at most. +pub fn tab_title(path: &str) -> String { + js::first_chars(js::base_name(path), 40) +} + +/// The path in `/` form, or none when Hangar would refuse it. Hangar checks it +/// again; this is so that a path a caller got wrong is said to be wrong, not +/// read as a failure. +pub fn check_path(raw: &str) -> Option { + if js::trim(raw).is_empty() || js::length(raw) > 1024 { + return None; + } + if raw.chars().any(|c| c <= '\u{1f}' || c == '\u{7f}') { + return None; + } + if raw.starts_with(['/', '\\']) { + return None; + } + let parts: Vec<&str> = raw + .split(['/', '\\']) + .filter(|part| !part.is_empty() && *part != ".") + .collect(); + if parts.is_empty() { + return None; + } + for part in &parts { + if *part == ".." + || part.contains(':') + || part.to_lowercase() == ".git" + || part.ends_with(['.', ' ']) + { + return None; + } + } + Some(parts.join("/")) +} + +/// `keys` is one string: names separated by commas. What is not a key name +/// is dropped. +pub fn parse_keys(raw: Option<&str>) -> Vec { + let Some(raw) = raw else { + return Vec::new(); + }; + let mut seen = HashSet::new(); + raw.split(',') + .map(js::trim) + .filter(|key| dotenv::is_key(key) && seen.insert(key.to_string())) + .map(str::to_owned) + .collect() +} + +pub fn parse_line(raw: Option<&str>) -> Option { + let raw = raw?; + let bytes = raw.as_bytes(); + let well_formed = (1..=9).contains(&bytes.len()) + && (b'1'..=b'9').contains(&bytes[0]) + && bytes.iter().all(u8::is_ascii_digit); + well_formed.then(|| raw.parse().ok()).flatten() +} + +/// What `tab.params` said, read as anything typed into a form. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Params { + pub path: Option, + pub bad_path: bool, + pub keys: Vec, + pub why: Option, + pub line: Option, + /// The pane that asked. + pub caller: Option, +} + +pub fn read_params(params: &BTreeMap, caller: Option<&str>) -> Params { + let given = params.get("path").filter(|path| !path.is_empty()); + let path = given.and_then(|path| check_path(path)); + let why = params + .get("why") + .map(|why| js::trim(why)) + .filter(|why| !why.is_empty()) + .map(str::to_owned); + Params { + bad_path: given.is_some() && path.is_none(), + path, + keys: parse_keys(params.get("keys").map(String::as_str)), + why, + line: parse_line(params.get("line").map(String::as_str)), + caller: caller.filter(|pane| !pane.is_empty()).map(str::to_owned), + } +} + +/* ── the picker ───────────────────────────────────────────────────── */ + +const SHOWN_PER_GROUP: usize = 200; + +const CONFIG_EXTENSIONS: &[&str] = &[ + "json", + "jsonc", + "json5", + "yaml", + "yml", + "toml", + "ini", + "cfg", + "conf", + "config", + "properties", + "xml", + "plist", +]; + +const NOT_TEXT: &[&str] = &[ + "png", "jpg", "jpeg", "gif", "webp", "avif", "bmp", "ico", "tif", "tiff", "pdf", "zip", "gz", + "tgz", "bz2", "xz", "7z", "rar", "tar", "exe", "dll", "so", "dylib", "bin", "class", "o", + "obj", "a", "lib", "wasm", "woff", "woff2", "ttf", "otf", "eot", "mp3", "mp4", "wav", "ogg", + "m4a", "webm", "mov", "avi", "mkv", "sqlite", "sqlite3", "db", "pyc", "node", +]; + +fn extension_in(name: &str, list: &[&str]) -> bool { + name.rsplit_once('.') + .is_some_and(|(_, extension)| list.contains(&extension)) +} + +/// `^(\.[\w.-]*(rc|ignore|config|attributes)|dockerfile|.*\.dockerfile|docker-compose\..*)$`, any case. +fn config_name(name: &str) -> bool { + let dotted = name.strip_prefix('.').is_some_and(|rest| { + rest.bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'-')) + && ["rc", "ignore", "config", "attributes"] + .iter() + .any(|end| rest.ends_with(end)) + }); + let plain = |rest: &str| !rest.chars().any(js::is_line_terminator); + dotted + || name == "dockerfile" + || name.strip_suffix(".dockerfile").is_some_and(plain) + || name.strip_prefix("docker-compose.").is_some_and(plain) +} + +/// `(^|[-.])lock(\.[a-z]+)?$`, and the lock files by their names, any case. +fn generated(name: &str) -> bool { + let bytes = name.as_bytes(); + let lock = (0..bytes.len()).any(|at| { + bytes[at..].starts_with(b"lock") + && (at == 0 || matches!(bytes[at - 1], b'-' | b'.')) + && match &bytes[at + 4..] { + [] => true, + [b'.', rest @ ..] => !rest.is_empty() && rest.iter().all(u8::is_ascii_alphabetic), + _ => false, + } + }); + lock || matches!(name, "package-lock.json" | "pnpm-lock.yaml" | "yarn.lock") +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Group { + Env, + Config, + Other, +} + +impl Group { + pub const ALL: [Group; 3] = [Group::Env, Group::Config, Group::Other]; + + /// Its title's key. + pub fn title(self) -> &'static str { + match self { + Group::Env => "groupEnv", + Group::Config => "groupConfig", + Group::Other => "groupOther", + } + } +} + +/// Which group of the picker a file goes in; none for what is not text. +pub fn classify(path: &str) -> Option { + let name = js::base_name(path).to_lowercase(); + if extension_in(&name, NOT_TEXT) { + return None; + } + if dotenv::is_dotenv_path(path) { + return Some(Group::Env); + } + if generated(&name) { + return Some(Group::Other); + } + if extension_in(&name, CONFIG_EXTENSIONS) || config_name(&name) { + Some(Group::Config) + } else { + Some(Group::Other) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PickFile { + pub path: String, + /// Not there yet: `.env`, offered all the same. + pub is_new: bool, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Groups { + pub env: Vec, + pub config: Vec, + pub other: Vec, +} + +impl Groups { + pub fn get(&self, group: Group) -> &[PickFile] { + match group { + Group::Env => &self.env, + Group::Config => &self.config, + Group::Other => &self.other, + } + } +} + +/// Env files first, then configuration, in Hangar's order (the nearest +/// first); what is not text is left out. +pub fn rank_files<'a>(paths: impl IntoIterator) -> Groups { + let mut groups = Groups::default(); + for path in paths { + let file = PickFile { + path: path.to_owned(), + is_new: false, + }; + match classify(path) { + Some(Group::Env) => groups.env.push(file), + Some(Group::Config) => groups.config.push(file), + Some(Group::Other) => groups.other.push(file), + None => {} + } + } + // The file an agent or a person usually wants is the one that is not there yet. + if !groups.env.iter().any(|file| file.path == ".env") { + groups.env.insert( + 0, + PickFile { + path: ".env".to_owned(), + is_new: true, + }, + ); + } + groups +} + +/// A group a filter leaves, cut to what a page can hold, saying how many it cut. +pub struct Shown<'a> { + pub group: Group, + pub files: Vec<&'a PickFile>, + pub more: usize, +} + +pub fn filter_groups<'a>(groups: &'a Groups, query: &str) -> Vec> { + let needle = js::trim(query).to_lowercase(); + Group::ALL + .iter() + .map(|&group| { + let all: Vec<&PickFile> = groups + .get(group) + .iter() + .filter(|file| file.path.to_lowercase().contains(&needle)) + .collect(); + let more = all.len().saturating_sub(SHOWN_PER_GROUP); + Shown { + group, + files: all.into_iter().take(SHOWN_PER_GROUP).collect(), + more, + } + }) + .collect() +} diff --git a/native/src/validate.rs b/native/src/validate.rs new file mode 100644 index 0000000..12dd81f --- /dev/null +++ b/native/src/validate.rs @@ -0,0 +1,989 @@ +//! Is this file broken? JSON is checked whole, so "valid" means valid. TOML is +//! parsed for its syntax, and YAML is only scanned for what is certainly +//! wrong; both answer `partial`, and the page says it is a basic check. An +//! error gives a code the page translates, and a line when one can be told. +//! validate.js, ported. + +use std::collections::HashSet; + +use crate::js; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Checker { + Json, + Jsonc, + Yaml, + Toml, +} + +impl Checker { + /// How the page names it. + pub fn name(self) -> &'static str { + match self { + Checker::Json => "JSON", + Checker::Jsonc => "JSONC", + Checker::Yaml => "YAML", + Checker::Toml => "TOML", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Check { + /// None: no check applies, so nothing is claimed. + pub kind: Option, + pub ok: bool, + /// A basic check, not a proof. + pub partial: bool, + /// What is wrong, as `check.` names it. + pub code: Option<&'static str>, + pub line: Option, + pub column: Option, +} + +impl Check { + fn ok(kind: Option, partial: bool) -> Self { + Check { + kind, + ok: true, + partial, + code: None, + line: None, + column: None, + } + } + + fn broken( + kind: Checker, + partial: bool, + code: &'static str, + at: Option<(usize, usize)>, + ) -> Self { + Check { + kind: Some(kind), + ok: false, + partial, + code: Some(code), + line: at.map(|(line, _)| line), + column: at.map(|(_, column)| column), + } + } +} + +fn not_terminated(text: &str) -> bool { + !text.chars().any(js::is_line_terminator) +} + +/// Which check applies. +pub fn checker_for(path: &str) -> Option { + let name = js::base_name(path).to_lowercase(); + if name.ends_with(".jsonc") || name.ends_with(".code-workspace") { + return Some(Checker::Jsonc); + } + if name.ends_with(".json") { + // These are read with comments and trailing commas by what uses them. + let config = ["tsconfig", "jsconfig"].iter().any(|start| { + name.strip_prefix(start).is_some_and(|rest| { + rest == ".json" + || (rest.len() >= 6 + && rest.starts_with(['.', '-']) + && rest.ends_with(".json") + && not_terminated(rest)) + }) + }); + if config + || matches!( + name.as_str(), + ".eslintrc.json" | "devcontainer.json" | ".devcontainer.json" + ) + { + return Some(Checker::Jsonc); + } + let lower = path.to_lowercase(); + let under = |dir: &str| { + lower.starts_with(&format!("{dir}/")) || lower.contains(&format!("/{dir}/")) + }; + if under(".vscode") || under(".devcontainer") { + return Some(Checker::Jsonc); + } + return Some(Checker::Json); + } + if name.ends_with(".yaml") || name.ends_with(".yml") { + return Some(Checker::Yaml); + } + if name.ends_with(".toml") { + return Some(Checker::Toml); + } + None +} + +pub fn validate(path: &str, text: &str) -> Check { + match checker_for(path) { + Some(kind @ (Checker::Json | Checker::Jsonc)) => check_json(text, kind), + Some(Checker::Yaml) => check_yaml(text), + Some(Checker::Toml) => check_toml(text), + None => Check::ok(None, false), + } +} + +/* ── JSON ─────────────────────────────────────────────────────────── */ + +/// Comments and trailing commas blanked, every other character where it was. +fn blank_jsonc(text: &str) -> String { + let mut out: Vec = text.chars().collect(); + let source = out.clone(); + let blank = |out: &mut Vec, from: usize, to: usize| { + for c in &mut out[from..to] { + if *c != '\n' && *c != '\r' { + *c = ' '; + } + } + }; + let mut last_comma: Option = None; + let mut i = 0; + while i < source.len() { + let c = source[i]; + let next = source.get(i + 1).copied(); + if c == '"' { + i += 1; + while i < source.len() && source[i] != '"' { + if source[i] == '\\' { + i += 1; + } + i += 1; + } + last_comma = None; + } else if c == '/' && next == Some('/') { + let mut end = i; + while end < source.len() && source[end] != '\n' { + end += 1; + } + blank(&mut out, i, end); + i = end.saturating_sub(1).max(i); + } else if c == '/' && next == Some('*') { + let close = (i + 2..source.len().saturating_sub(1)) + .find(|&at| source[at] == '*' && source[at + 1] == '/'); + let end = close.map_or(source.len(), |close| close + 2); + blank(&mut out, i, end); + i = end - 1; + } else if c == ',' { + last_comma = Some(i); + } else if c == ']' || c == '}' { + if let Some(comma) = last_comma.take() { + out[comma] = ' '; + } + } else if !js::is_space(c) { + last_comma = None; + } + i += 1; + } + out.into_iter().collect() +} + +/// Where JSON goes wrong, or none when it is valid: the grammar walked +/// without a stack of calls, so that no depth is too deep. +fn json_error_at(text: &[u8]) -> Option { + let mut i = 0; + let blanks = |i: &mut usize| { + while text + .get(*i) + .is_some_and(|byte| matches!(byte, b' ' | b'\t' | b'\r' | b'\n')) + { + *i += 1; + } + }; + let hex = |at: usize, n: usize| { + text.len() >= at + n && text[at..at + n].iter().all(u8::is_ascii_hexdigit) + }; + let string = |i: &mut usize| -> Result<(), usize> { + *i += 1; + loop { + match text.get(*i) { + None => return Err(*i), + Some(byte) if *byte < 0x20 => return Err(*i), + Some(b'"') => { + *i += 1; + return Ok(()); + } + Some(b'\\') => match text.get(*i + 1) { + Some(b'u') if hex(*i + 2, 4) => *i += 6, + Some(b'"' | b'\\' | b'/' | b'b' | b'f' | b'n' | b'r' | b't') => *i += 2, + _ => return Err(*i), + }, + Some(_) => *i += 1, + } + } + }; + let scalar = |i: &mut usize| -> Result<(), usize> { + let rest = &text[*i..]; + let number = { + let mut n = 0; + if rest.first() == Some(&b'-') { + n += 1; + } + match rest.get(n) { + Some(b'0') => { + n += 1; + Some(n) + } + Some(b'1'..=b'9') => { + n += 1; + while rest.get(n).is_some_and(u8::is_ascii_digit) { + n += 1; + } + Some(n) + } + _ => None, + } + .map(|mut n| { + if rest.get(n) == Some(&b'.') && rest.get(n + 1).is_some_and(u8::is_ascii_digit) { + n += 2; + while rest.get(n).is_some_and(u8::is_ascii_digit) { + n += 1; + } + } + if matches!(rest.get(n), Some(b'e' | b'E')) { + let sign = usize::from(matches!(rest.get(n + 1), Some(b'+' | b'-'))); + if rest.get(n + 1 + sign).is_some_and(u8::is_ascii_digit) { + n += 1 + sign; + while rest.get(n).is_some_and(u8::is_ascii_digit) { + n += 1; + } + } + } + n + }) + }; + let length = number.or_else(|| { + ["true", "false", "null"] + .iter() + .find(|word| rest.starts_with(word.as_bytes())) + .map(|word| word.len()) + }); + match length { + Some(length) => { + *i += length; + Ok(()) + } + None => Err(*i), + } + }; + // A member's key and colon, `i` at its quote. + let key = |i: &mut usize| -> Result<(), usize> { + blanks(i); + if text.get(*i) != Some(&b'"') { + return Err(*i); + } + string(i)?; + blanks(i); + if text.get(*i) != Some(&b':') { + return Err(*i); + } + *i += 1; + Ok(()) + }; + let walk = |i: &mut usize| -> Result<(), usize> { + let mut open: Vec = Vec::new(); + 'value: loop { + blanks(i); + match text.get(*i) { + Some(b'"') => string(i)?, + Some(&bracket @ (b'[' | b'{')) => { + let close = if bracket == b'[' { b']' } else { b'}' }; + *i += 1; + blanks(i); + if text.get(*i) == Some(&close) { + *i += 1; + } else { + open.push(bracket); + if bracket == b'{' { + key(i)?; + } + continue 'value; + } + } + _ => scalar(i)?, + } + // A value ended: close what it ends, or go on to the next one. + loop { + let Some(&bracket) = open.last() else { + return Ok(()); + }; + let close = if bracket == b'[' { b']' } else { b'}' }; + blanks(i); + if text.get(*i) == Some(&close) { + *i += 1; + open.pop(); + continue; + } + if text.get(*i) != Some(&b',') { + return Err(*i); + } + *i += 1; + if bracket == b'{' { + key(i)?; + } + continue 'value; + } + } + }; + match walk(&mut i) { + Err(at) => Some(at), + Ok(()) => { + blanks(&mut i); + (i < text.len()).then_some(i) + } + } +} + +fn check_json(text: &str, kind: Checker) -> Check { + let source = if kind == Checker::Jsonc { + blank_jsonc(text) + } else { + text.to_owned() + }; + match json_error_at(source.as_bytes()) { + None => Check::ok(Some(kind), false), + Some(at) => Check::broken( + kind, + false, + "json", + Some(js::line_of(source.as_bytes(), at)), + ), + } +} + +/* ── YAML: only what is certainly wrong ───────────────────────────── */ + +fn split_lines(text: &str) -> Vec<&str> { + text.split("\r\n") + .flat_map(|part| part.split(['\n', '\r'])) + .collect() +} + +/// `^[|>][-+0-9]*[ \t]*(#.*)?$`: a block scalar's header. +fn block_header(rest: &[char]) -> bool { + let mut i = 1; + while rest + .get(i) + .is_some_and(|c| *c == '-' || *c == '+' || c.is_ascii_digit()) + { + i += 1; + } + while rest.get(i).is_some_and(|c| *c == ' ' || *c == '\t') { + i += 1; + } + match rest.get(i) { + None => true, + Some('#') => !rest[i..].iter().any(|c| js::is_line_terminator(*c)), + Some(_) => false, + } +} + +fn check_yaml(text: &str) -> Check { + let fail = |code, line, column| Check::broken(Checker::Yaml, true, code, Some((line, column))); + let mut flow: Vec<(char, usize, usize)> = Vec::new(); + let mut quote: Option<(char, usize, usize)> = None; + let mut block_indent: Option = None; + // The indent of the line that ended in a plain scalar, which may go on below. + let mut plain_indent: Option = None; + + for (n, raw) in split_lines(text).into_iter().enumerate() { + let line: Vec = raw.chars().collect(); + let mut at = 0; + // A token may start here: a quote or a bracket means something. + let mut start = true; + let indent = line.iter().take_while(|c| **c == ' ').count(); + + if quote.is_none() && flow.is_empty() { + let lead = line + .iter() + .take_while(|c| **c == ' ' || **c == '\t') + .count(); + let rest = &line[lead..]; + if rest.is_empty() { + continue; + } + if let Some(block) = block_indent { + if indent > block { + continue; + } + block_indent = None; + } + if rest[0] == '#' { + continue; + } + if plain_indent.is_some_and(|plain| indent > plain) { + continue; + } + plain_indent = None; + if let Some(tab) = line[..lead].iter().position(|c| *c == '\t') { + return fail("yaml-tab", n + 1, tab + 1); + } + if line.first() == Some(&'%') { + continue; + } + at = lead; + let marker = rest.starts_with(&['-', '-', '-']) || rest.starts_with(&['.', '.', '.']); + if marker && rest.get(3).is_none_or(|c| *c == ' ' || *c == '\t') { + at += 3; + } + } + + let mut plain = false; + while at < line.len() { + let c = line[at]; + if let Some((open, _, _)) = quote { + if open == '"' && c == '\\' { + at += 1; + } else if c == open { + if open == '\'' && line.get(at + 1) == Some(&'\'') { + at += 1; + } else { + quote = None; + } + } + plain = false; + start = false; + at += 1; + continue; + } + let previous = at.checked_sub(1).map(|before| line[before]); + let next = line.get(at + 1).copied(); + let blank_next = next.is_none_or(|next| next == ' ' || next == '\t'); + if c == ' ' || c == '\t' { + at += 1; + continue; + } + if c == '#' && previous.is_none_or(|before| before == ' ' || before == '\t') { + break; + } + if start { + if c == '"' || c == '\'' { + quote = Some((c, n + 1, at + 1)); + start = false; + at += 1; + continue; + } + if c == '[' || c == '{' { + flow.push((c, n + 1, at + 1)); + at += 1; + continue; + } + if (c == ']' || c == '}') && flow.is_empty() { + return fail("yaml-bracket", n + 1, at + 1); + } + if flow.is_empty() && (c == '|' || c == '>') && block_header(&line[at..]) { + block_indent = Some(indent); + plain = false; + break; + } + if (c == '&' || c == '!') && !blank_next { + while line + .get(at + 1) + .is_some_and(|after| *after != ' ' && *after != '\t') + { + at += 1; + } + at += 1; + continue; + } + if matches!(c, '-' | '?' | ':') && blank_next { + at += 1; + continue; + } + if c == '@' || c == '`' { + return fail("yaml-reserved", n + 1, at + 1); + } + start = false; + plain = true; + } + if c == ':' + && (blank_next + || (!flow.is_empty() && next.is_some_and(|next| ",[]{}".contains(next)))) + { + start = true; + plain = false; + } else if !flow.is_empty() { + if c == ',' || (c == ':' && previous == Some('"')) { + start = true; + plain = false; + } else if c == ']' || c == '}' { + let (open, _, _) = flow.pop().unwrap_or((' ', 0, 0)); + let closes = if open == '[' { ']' } else { '}' }; + if closes != c { + return fail("yaml-bracket", n + 1, at + 1); + } + plain = false; + } + } + at += 1; + } + plain_indent = (plain && quote.is_none() && flow.is_empty()).then_some(indent); + } + if let Some((_, line, column)) = quote { + return fail("yaml-quote", line, column); + } + if let Some((_, line, column)) = flow.last() { + return fail("yaml-bracket", *line, *column); + } + Check::ok(Some(Checker::Yaml), true) +} + +/* ── TOML: its syntax, and keys or tables given twice ─────────────── */ + +struct Toml<'a> { + text: &'a str, + b: &'a [u8], + i: usize, +} + +type Stop = (&'static str, usize); + +fn digits(b: &[u8], at: usize, n: usize) -> bool { + b.len() >= at + n && b[at..at + n].iter().all(u8::is_ascii_digit) +} + +/// `first(?:_?more)*` from `at`, `first` and `more` the same class: its end. +fn underscored(b: &[u8], at: usize, class: impl Fn(u8) -> bool) -> Option { + if !b.get(at).is_some_and(|byte| class(*byte)) { + return None; + } + let mut end = at + 1; + loop { + match b.get(end) { + Some(byte) if class(*byte) => end += 1, + Some(b'_') if b.get(end + 1).is_some_and(|byte| class(*byte)) => end += 2, + _ => return Some(end), + } + } +} + +/// The length of what TOML's numbers and dates read at `at`: the first of +/// the page's alternatives that matches. +fn number_or_date(b: &[u8], at: usize) -> Option { + let rest = &b[at..]; + let signed = usize::from(matches!(rest.first(), Some(b'+' | b'-'))); + // [+-]?(?:inf|nan) + if rest[signed..].starts_with(b"inf") || rest[signed..].starts_with(b"nan") { + return Some(signed + 3); + } + // 0x…, 0o…, 0b… + for (prefix, class) in [ + (b"0x", u8::is_ascii_hexdigit as fn(&u8) -> bool), + (b"0o", |byte: &u8| (b'0'..=b'7').contains(byte)), + (b"0b", |byte: &u8| *byte == b'0' || *byte == b'1'), + ] { + if rest.starts_with(prefix) + && let Some(end) = underscored(rest, 2, |byte| class(&byte)) + { + return Some(end); + } + } + // \d{4}-\d{2}-\d{2}(?:[Tt ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:[Zz]|[+-]\d{2}:\d{2})?)? + if digits(rest, 0, 4) + && rest.get(4) == Some(&b'-') + && digits(rest, 5, 2) + && rest.get(7) == Some(&b'-') + && digits(rest, 8, 2) + { + let mut end = 10; + if matches!(rest.get(10), Some(b'T' | b't' | b' ')) + && digits(rest, 11, 2) + && rest.get(13) == Some(&b':') + && digits(rest, 14, 2) + && rest.get(16) == Some(&b':') + && digits(rest, 17, 2) + { + end = 19; + if rest.get(end) == Some(&b'.') && digits(rest, end + 1, 1) { + end += 2; + while digits(rest, end, 1) { + end += 1; + } + } + match rest.get(end) { + Some(b'Z' | b'z') => end += 1, + Some(b'+' | b'-') + if digits(rest, end + 1, 2) + && rest.get(end + 3) == Some(&b':') + && digits(rest, end + 4, 2) => + { + end += 6 + } + _ => {} + } + } + return Some(end); + } + // \d{2}:\d{2}:\d{2}(?:\.\d+)? + if digits(rest, 0, 2) + && rest.get(2) == Some(&b':') + && digits(rest, 3, 2) + && rest.get(5) == Some(&b':') + && digits(rest, 6, 2) + { + let mut end = 8; + if rest.get(end) == Some(&b'.') && digits(rest, end + 1, 1) { + end += 2; + while digits(rest, end, 1) { + end += 1; + } + } + return Some(end); + } + // [+-]?(?:0|[1-9](?:_?\d)*)(?:\.\d(?:_?\d)*)?(?:[eE][+-]?\d(?:_?\d)*)? + let digit = |byte: u8| byte.is_ascii_digit(); + let mut end = match rest.get(signed) { + Some(b'0') => signed + 1, + Some(b'1'..=b'9') => underscored(rest, signed, digit)?, + _ => return None, + }; + if rest.get(end) == Some(&b'.') + && let Some(after) = underscored(rest, end + 1, digit) + { + end = after; + } + if matches!(rest.get(end), Some(b'e' | b'E')) { + let sign = usize::from(matches!(rest.get(end + 1), Some(b'+' | b'-'))); + if let Some(after) = underscored(rest, end + 1 + sign, digit) { + end = after; + } + } + Some(end) +} + +impl Toml<'_> { + fn at(&self, i: usize) -> Option { + self.b.get(i).copied() + } + + fn here(&self) -> Option { + self.at(self.i) + } + + fn starts(&self, what: &[u8]) -> bool { + self.b[self.i.min(self.b.len())..].starts_with(what) + } + + fn blanks(&mut self) { + while matches!(self.here(), Some(b' ' | b'\t')) { + self.i += 1; + } + } + + fn comment(&mut self) { + if self.here() == Some(b'#') { + while self.i < self.b.len() && self.b[self.i] != b'\n' { + self.i += 1; + } + } + } + + fn at_eol(&self) -> bool { + self.i >= self.b.len() + || self.here() == Some(b'\n') + || (self.here() == Some(b'\r') && self.at(self.i + 1) == Some(b'\n')) + } + + fn step_eol(&mut self) { + self.i += if self.here() == Some(b'\r') { 2 } else { 1 }; + } + + fn end_of_line(&mut self) -> Result<(), Stop> { + self.blanks(); + self.comment(); + if !self.at_eol() { + return Err(("toml-trailing", self.i)); + } + self.step_eol(); + Ok(()) + } + + fn skip_blank_lines(&mut self) { + loop { + self.blanks(); + self.comment(); + if self.i >= self.b.len() || !self.at_eol() { + return; + } + self.step_eol(); + } + } + + fn basic_string(&mut self, multi: bool) -> Result<(), Stop> { + let open = self.i; + self.i += if multi { 3 } else { 1 }; + loop { + let Some(c) = self.here() else { + return Err(("toml-string", open)); + }; + if multi && self.starts(b"\"\"\"") { + self.i += 3; + while self.here() == Some(b'"') && self.i - open < self.b.len() { + self.i += 1; + } + return Ok(()); + } + if !multi && c == b'"' { + self.i += 1; + return Ok(()); + } + if !multi && (c == b'\n' || c == b'\r') { + return Err(("toml-string", open)); + } + if c == b'\\' { + let hex = |at: usize, n: usize| { + self.b.len() >= at + n && self.b[at..at + n].iter().all(u8::is_ascii_hexdigit) + }; + match self.at(self.i + 1) { + Some(b'b' | b't' | b'n' | b'f' | b'r' | b'"' | b'\\') => self.i += 2, + Some(b'u') if hex(self.i + 2, 4) => self.i += 6, + Some(b'U') if hex(self.i + 2, 8) => self.i += 10, + _ if multi && self.line_ending_backslash() => self.i += 2, + _ => return Err(("toml-escape", self.i)), + } + } else { + self.i += 1; + } + } + } + + /// `^\\[ \t]*\r?\n` within 200 characters. + fn line_ending_backslash(&self) -> bool { + let window = &self.b[self.i..(self.i + 200).min(self.b.len())]; + let mut k = 1; + while matches!(window.get(k), Some(b' ' | b'\t')) { + k += 1; + } + if window.get(k) == Some(&b'\r') { + k += 1; + } + window.get(k) == Some(&b'\n') + } + + fn literal_string(&mut self, multi: bool) -> Result<(), Stop> { + let open = self.i; + self.i += if multi { 3 } else { 1 }; + loop { + let Some(c) = self.here() else { + return Err(("toml-string", open)); + }; + if multi && self.starts(b"'''") { + self.i += 3; + while self.here() == Some(b'\'') { + self.i += 1; + } + return Ok(()); + } + if !multi && c == b'\'' { + self.i += 1; + return Ok(()); + } + if !multi && (c == b'\n' || c == b'\r') { + return Err(("toml-string", open)); + } + self.i += 1; + } + } + + /// One part of a key, as written, for telling duplicates. + fn key_part(&mut self) -> Result { + let open = self.i; + match self.here() { + Some(b'"') => self.basic_string(false)?, + Some(b'\'') => self.literal_string(false)?, + _ => { + while self + .here() + .is_some_and(|c| c.is_ascii_alphanumeric() || c == b'_' || c == b'-') + { + self.i += 1; + } + if self.i == open { + return Err(("toml-key", self.i)); + } + } + } + Ok(js::cut(self.text, open, self.i).to_owned()) + } + + fn key(&mut self) -> Result, Stop> { + let mut parts = vec![self.key_part()?]; + loop { + self.blanks(); + if self.here() != Some(b'.') { + return Ok(parts); + } + self.i += 1; + self.blanks(); + parts.push(self.key_part()?); + } + } + + fn array_gap(&mut self) { + loop { + self.blanks(); + self.comment(); + if self.i < self.b.len() && self.at_eol() { + self.step_eol(); + } else { + return; + } + } + } + + fn array(&mut self) -> Result<(), Stop> { + let open = self.i; + self.i += 1; + self.array_gap(); + while self.here() != Some(b']') { + if self.i >= self.b.len() { + return Err(("toml-value", open)); + } + self.value()?; + self.array_gap(); + if self.here() == Some(b',') { + self.i += 1; + self.array_gap(); + } else if self.here() != Some(b']') { + let at = if self.i >= self.b.len() { open } else { self.i }; + return Err(("toml-value", at)); + } + } + self.i += 1; + Ok(()) + } + + fn inline_table(&mut self) -> Result<(), Stop> { + self.i += 1; + self.blanks(); + if self.here() == Some(b'}') { + self.i += 1; + return Ok(()); + } + loop { + self.key()?; + if self.here() != Some(b'=') { + return Err(("toml-equals", self.i)); + } + self.i += 1; + self.blanks(); + self.value()?; + self.blanks(); + match self.here() { + Some(b',') => { + self.i += 1; + self.blanks(); + } + Some(b'}') => { + self.i += 1; + return Ok(()); + } + _ => return Err(("toml-value", self.i)), + } + } + } + + fn value(&mut self) -> Result<(), Stop> { + if self.starts(b"\"\"\"") { + return self.basic_string(true); + } + if self.starts(b"'''") { + return self.literal_string(true); + } + match self.here() { + Some(b'"') => return self.basic_string(false), + Some(b'\'') => return self.literal_string(false), + Some(b'[') => return self.array(), + Some(b'{') => return self.inline_table(), + _ => {} + } + if self.starts(b"true") { + self.i += 4; + } else if self.starts(b"false") { + self.i += 5; + } else { + match number_or_date(self.b, self.i.min(self.b.len())) { + Some(length) if length > 0 => self.i += length, + _ => return Err(("toml-value", self.i)), + } + } + if self.i < self.b.len() { + let ends = js::from(self.text, self.i) + .chars() + .next() + .is_some_and(|c| js::is_space(c) || ",]}#".contains(c)); + if !ends { + return Err(("toml-value", self.i)); + } + } + Ok(()) + } + + fn document(&mut self) -> Result<(), Stop> { + let mut seen: HashSet = HashSet::new(); + let mut table = String::new(); + loop { + self.skip_blank_lines(); + if self.i >= self.b.len() { + return Ok(()); + } + let start = self.i; + if self.here() == Some(b'[') { + let is_array = self.at(self.i + 1) == Some(b'['); + self.i += if is_array { 2 } else { 1 }; + self.blanks(); + let name = self.key()?.join("\u{0}"); + if self.here() != Some(b']') || (is_array && self.at(self.i + 1) != Some(b']')) { + return Err(("toml-header", self.i)); + } + self.i += if is_array { 2 } else { 1 }; + self.end_of_line()?; + if is_array { + // Each [[item]] is a table of its own: its keys may repeat the last's. + let inside = format!("{name}\u{0}"); + let header = format!("[{name}\u{0}"); + seen.retain(|other| !other.starts_with(&inside) && !other.starts_with(&header)); + } else if !seen.insert(format!("[{name}]")) { + return Err(("toml-duplicate", start)); + } + table = name; + } else { + let name = self.key()?.join("\u{0}"); + if self.here() != Some(b'=') { + return Err(("toml-equals", self.i)); + } + self.i += 1; + self.blanks(); + self.value()?; + self.end_of_line()?; + let whole = if table.is_empty() { + name + } else { + format!("{table}\u{0}{name}") + }; + if !seen.insert(whole) { + return Err(("toml-duplicate", start)); + } + } + } + } +} + +fn check_toml(text: &str) -> Check { + let mut toml = Toml { + text, + b: text.as_bytes(), + i: 0, + }; + match toml.document() { + Ok(()) => Check::ok(Some(Checker::Toml), true), + Err((code, at)) => Check::broken( + Checker::Toml, + true, + code, + Some(js::line_of(text.as_bytes(), at)), + ), + } +} diff --git a/native/src/view.rs b/native/src/view.rs new file mode 100644 index 0000000..a0b1bce --- /dev/null +++ b/native/src/view.rs @@ -0,0 +1,896 @@ +//! Draws the controller's state with Hangar's widgets: view.js, ported. +//! Nothing a file or a caller said is read as markup, and a value shows only +//! in its own field, dotted until the person reveals it. + +use hangar_kit_sdk::Handler; +use hangar_kit_sdk::prelude::*; +use hangar_kit_sdk::ui::{Header, ListItem, LogLine}; + +use crate::diff::{Hunk, Kind}; +use crate::editor::{ + ConflictKind, ConflictRow, DIFF_WINDOW, Editor, Form, IgnoreStatus, KeyRow, Message, Screen, + Side, Stage, TellStatus, +}; +use crate::gitignore; +use crate::js; +use crate::logic; +use crate::validate::Check; + +/// What a value hidden in the conflict view shows. +pub const MASK: &str = "••••••••"; +const VALUE_LINES_MAX: usize = 8; +/// A line of a text area, and its padding, in logical pixels. +const AREA_LINE: f32 = 18.0; +const AREA_PAD: f32 = 16.0; + +type El = Element; + +pub fn view(editor: &Editor) -> El { + match editor.screen { + Screen::Loading => page![loading(editor.t().t("loading"))].into(), + Screen::Picker => picker_view(editor), + Screen::Error => error_view(editor), + _ if editor.conflict.is_some() => conflict_view(editor), + Screen::Dotenv => dotenv_view(editor), + Screen::Text => match editor.text.as_ref().map(|text| text.stage) { + Some(Stage::Review) => text_review_view(editor), + _ => text_edit_view(editor), + }, + } +} + +/* ── the parts every file shows ───────────────────────────────────── */ + +/// A page that does not scroll as a whole: its header, the part that +/// scrolls, and the foot with the one thing to do. +fn frame(header: impl Into, body: Vec, foot: Option) -> El { + let mut parts: Vec = vec![ + container(header) + .padding([0.0, 12.0]) + .width(Length::Fill) + .into(), + scroll(column(body).spacing(12.0).padding(12.0)).into(), + ]; + parts.extend(foot); + page(parts).fill().into() +} + +fn header_of(editor: &Editor, states: Vec) -> Header> { + let t = editor.t(); + let path = editor.path.as_deref().unwrap_or(""); + let mut head = header(js::base_name(path)); + for state in states { + head = head.state(state); + } + let dir = js::dir_name(path); + if !dir.is_empty() { + head = head.state(text(dir).mono().small().dim()); + } + if editor.from_picker { + head = head.action(button(t.t("back")).ghost().small().on_press(Message::Back)); + } + head +} + +fn request_banner(editor: &Editor) -> Option { + let why = editor.why.as_ref()?; + let t = editor.t(); + let asks = match &editor.caller { + Some(pane) => t.tv("askedBy", &[("pane", pane)]), + None => t.t("askedAnon"), + }; + Some(banner(Notice::Info, why.clone()).title(asks).into()) +} + +fn save_problem(editor: &Editor) -> Option { + let problem = editor.problem.as_ref()?; + Some( + banner( + Notice::Error, + editor.t().t(&format!("write.{}", problem.code)), + ) + .into(), + ) +} + +fn tell_problem(editor: &Editor) -> Option { + let told = editor + .told + .as_ref() + .filter(|told| told.status == TellStatus::Failed)?; + let t = editor.t(); + let key = format!("tell.{}", told.code.as_deref().unwrap_or("other")); + let reason = if logic::has(&key) { + t.t(&key) + } else { + t.t("tell.other") + }; + Some( + banner( + Notice::Warning, + t.tv("notTold", &[("pane", &told.pane), ("reason", &reason)]), + ) + .action( + button(t.tv("tellAgain", &[("pane", &told.pane)])) + .small() + .on_press_maybe((!editor.busy).then_some(Message::RetryTell)), + ) + .into(), + ) +} + +/// What is true right now, and the one thing to do: a line of its own at the +/// foot of the page. +fn foot(status: String, buttons: Vec) -> El { + let mut line: Vec = vec![container(text(status)).width(Length::Fill).into()]; + line.extend(buttons); + bar([row(line).spacing(6.0).align(Align::Center).into()]) + .foot() + .into() +} + +fn saved_status(editor: &Editor) -> String { + let t = editor.t(); + if editor.busy { + return t.t("saving"); + } + let saved = if editor.saved { + t.t("savedLocal") + } else { + String::new() + }; + match &editor.told { + None => saved, + Some(told) => match told.status { + TellStatus::Sent if editor.screen == Screen::Text => { + t.tv("toldText", &[("pane", &told.pane)]) + } + TellStatus::Sent => t.tv("told", &[("pane", &told.pane)]), + TellStatus::Checked => t.tv("toldNoChange", &[("pane", &told.pane)]), + TellStatus::Failed => saved, + }, + } +} + +fn can_tell_no_change(editor: &Editor) -> bool { + editor.caller.is_some() + && !editor.is_dirty() + && !editor.saved + && !editor + .told + .as_ref() + .is_some_and(|told| told.status != TellStatus::Failed) +} + +fn tell_button(editor: &Editor, pane: &str) -> ui::Button> { + button(editor.t().tv("tellNoChange", &[("pane", pane)])) + .small() + .on_press_maybe((!editor.busy).then_some(Message::TellNoChange)) +} + +use hangar_kit_sdk::ui; + +/* ── the form ─────────────────────────────────────────────────────── */ + +fn value_input(editor: &Editor, row: &KeyRow) -> El { + let t = editor.t(); + let id = format!("value:{}", row.key); + let key = row.key.clone(); + let edit = move |value| Message::EditRow(key.clone(), value); + let lines = row.value.split('\n').count(); + if lines > 1 && !row.revealed { + // A one-line field would drop the line breaks: there is nothing to + // edit until it shows. + return text_input(t.t("valueLines"), "") + .secure() + .mono() + .id(id) + .into(); + } + if lines > 1 { + let shown = lines.min(VALUE_LINES_MAX) as f32; + return text_area(id, row.value.clone()) + .mono() + .placeholder(t.t("valueEmpty")) + .height(shown * AREA_LINE + AREA_PAD) + .on_input(edit) + .into(); + } + let input = text_input(t.t("valueEmpty"), row.value.clone()) + .mono() + .id(id) + .on_input(edit); + if row.revealed { input } else { input.secure() }.into() +} + +fn row_mark(editor: &Editor, row: &KeyRow) -> Option { + let t = editor.t(); + if row.missing() { + return Some(state_label(Status::Waiting, t.t("keyMissing")).into()); + } + if row.changed() { + return Some(chip(t.t("keyChanged")).into()); + } + row.asked + .then(|| state_label(Status::Success, t.t("keySet")).into()) +} + +fn reveal_button(editor: &Editor, revealed: bool, message: Message) -> El { + let t = editor.t(); + button(if revealed { t.t("hide") } else { t.t("show") }) + .ghost() + .small() + .on_press(message) + .into() +} + +fn key_row(editor: &Editor, row: &KeyRow) -> ListItem> { + let t = editor.t(); + let mut entry = item(row.key.clone()).mono().wrap(); + if let Some(mark) = row_mark(editor, row) { + entry = entry.end(mark); + } + entry = entry.body( + row![ + value_input(editor, row), + reveal_button(editor, row.revealed, Message::ToggleReveal(row.key.clone())), + ] + .spacing(4.0) + .align(Align::Start), + ); + if !row.hint.is_empty() { + entry = entry.body(text(row.hint.clone()).small().dim()); + } + if row.count > 1 { + entry = entry.body(text(t.tn("keyTwice", row.count as i64, &[])).small().dim()); + } + entry +} + +fn ignore_banners(editor: &Editor) -> Vec { + let Some(ignore) = editor + .ignore + .as_ref() + .filter(|ignore| ignore.status != IgnoreStatus::Ignored) + else { + return Vec::new(); + }; + let t = editor.t(); + let path = editor.path.as_deref().unwrap_or(""); + let file = js::base_name(path); + if ignore.status == IgnoreStatus::Unknown { + return vec![banner(Notice::Info, t.tv("ignoreUnknown", &[("file", file)])).into()]; + } + let words = if ignore.status == IgnoreStatus::NoFile { + t.tv("ignoreNoFile", &[("file", file)]) + } else { + t.tv("ignoreWarning", &[("file", file)]) + }; + let label = if ignore.busy { + t.t("ignoreAdding") + } else { + t.tv("ignoreAdd", &[("pattern", &gitignore::pattern_for(path))]) + }; + let add = button(label) + .small() + .on_press_maybe((!ignore.busy).then_some(Message::AddToGitignore)); + let mut out: Vec = vec![banner(Notice::Warning, words).action(add).into()]; + if let Some(problem) = &ignore.problem { + let key = format!("write.{problem}"); + let reason = if logic::has(&key) { + t.t(&key) + } else { + t.t("write.other") + }; + out.push(banner(Notice::Error, t.tv("ignoreFailed", &[("reason", &reason)])).into()); + } + out +} + +fn offered_section(editor: &Editor, form: &Form) -> Option { + if form.offered.is_empty() { + return None; + } + let t = editor.t(); + let items = form.offered.iter().map(|offer| { + let mut entry = item(offer.key.clone()).mono().wrap().action( + button(t.t("add")) + .small() + .on_press(Message::AddOffered(offer.key.clone())), + ); + if !offer.hint.is_empty() { + entry = entry.sub(offer.hint.clone()); + } + entry + }); + let file = form.example_name.as_deref().unwrap_or(""); + let mut part = section( + t.tv("offeredTitle", &[("file", file)]), + [list(items).group().into()], + ) + .count(form.offered.len().to_string()); + if form.offered.len() > 1 { + part = part.action( + button(t.t("addAll")) + .ghost() + .small() + .on_press(Message::AddAllOffered), + ); + } + Some(part.into()) +} + +fn new_key_field(editor: &Editor, form: &Form) -> El { + let t = editor.t(); + let mut input = text_input(t.t("newKeyPlaceholder"), form.new_key.clone()) + .mono() + .id("new-key") + .on_input(Message::NewKey) + .on_submit(Message::AddNewKey); + if let Some(problem) = form.new_key_problem { + input = input.error(t.t(problem)); + } + row![ + input, + button(t.t("add")).small().on_press(Message::AddNewKey) + ] + .spacing(4.0) + .align(Align::Start) + .into() +} + +fn dotenv_view(editor: &Editor) -> El { + let t = editor.t(); + let Some(form) = &editor.form else { + return page![loading(t.t("loading"))].into(); + }; + let missing = editor.missing_count(); + let state: Vec = if missing > 0 { + vec![state_label(Status::Waiting, t.tn("stateMissing", missing as i64, &[])).into()] + } else if editor.saved { + vec![state_label(Status::Success, t.t("stateSaved")).into()] + } else if !editor.exists { + vec![state_label(Status::Neutral, t.t("stateNew")).into()] + } else { + Vec::new() + }; + let head = header_of(editor, state); + + let mut body: Vec = Vec::new(); + body.extend(request_banner(editor)); + body.extend(ignore_banners(editor)); + body.extend(save_problem(editor)); + body.extend(tell_problem(editor)); + if !editor.exists && editor.why.is_none() { + body.push(banner(Notice::Info, t.t("newFile")).into()); + } + let asked: Vec<&KeyRow> = form.rows.iter().filter(|row| row.asked).collect(); + let rest: Vec<&KeyRow> = form.rows.iter().filter(|row| !row.asked).collect(); + for (title, rows) in [("sectionAsked", &asked), ("sectionFile", &rest)] { + if rows.is_empty() { + continue; + } + let items = rows.iter().map(|row| key_row(editor, row)); + body.push( + section(t.t(title), [list(items).group().into()]) + .count(rows.len().to_string()) + .into(), + ); + } + if form.rows.is_empty() { + body.push(empty(t.t("noKeys")).into()); + } + body.extend(offered_section(editor, form)); + body.push(section(t.t("newKeyLabel"), [new_key_field(editor, form)]).into()); + if form.other_lines > 0 { + body.push( + text(t.tn("otherLines", form.other_lines as i64, &[])) + .small() + .muted() + .into(), + ); + } + + // With keys still to fill in, saying there is nothing to change is the + // lesser choice. + let mut buttons: Vec = Vec::new(); + let offer_tell = can_tell_no_change(editor); + if offer_tell && let Some(pane) = &editor.caller { + let tell = tell_button(editor, pane); + buttons.push(if missing > 0 { tell } else { tell.primary() }.into()); + } + if !offer_tell || missing > 0 { + let disabled = editor.busy || !editor.is_dirty(); + let mut save = button(t.t("save")) + .primary() + .small() + .on_press_maybe((!disabled).then_some(Message::SaveForm)); + if disabled && !editor.busy { + save = save.tooltip(t.t("nothingToSave")); + } + buttons.push(save.into()); + } + frame(head, body, Some(foot(saved_status(editor), buttons))) +} + +/* ── diffs ────────────────────────────────────────────────────────── */ + +fn diff_line(editor: &Editor, hunk: &Hunk) -> LogLine { + match hunk { + Hunk::Skip(count) => { + log_line(editor.t().tn("diffSkip", *count as i64, &[])).kind(LineKind::Head) + } + Hunk::Line(op) => { + let (sign, kind, number) = match op.kind { + Kind::Add => ("+ ", LineKind::Added, op.b), + Kind::Del => ("− ", LineKind::Removed, op.a), + Kind::Same => (" ", LineKind::Normal, op.a), + }; + let line = log_line(format!("{sign}{}", op.text)).kind(kind); + match number { + Some(number) => line.number(number as u32), + None => line, + } + } + } +} + +/// Signs as well as colours. Given in parts: a diff of a large file would +/// not fit in one view. +fn diff_block(editor: &Editor, hunks: &[Hunk]) -> El { + let total = hunks.len() as u32; + let (start, end) = editor.diff_range; + let start = start.min(total); + let end = end.max(start + DIFF_WINDOW).min(total); + let lines = hunks[start as usize..end as usize] + .iter() + .map(|hunk| diff_line(editor, hunk)); + log_lines(lines) + .id("diff") + .window(start, total) + .on_range(Message::DiffRange) + .height(480.0) + .into() +} + +/* ── the conflict ─────────────────────────────────────────────────── */ + +fn conflict_view(editor: &Editor) -> El { + let t = editor.t(); + let Some(conflict) = &editor.conflict else { + return page![loading(t.t("loading"))].into(); + }; + let head = header_of( + editor, + vec![state_label(Status::Failure, t.t("stateConflict")).into()], + ); + let intro = if conflict.gone() { + t.t("conflictGone") + } else { + format!("{}. {}", t.t("conflictTitle"), t.t("conflictHint")) + }; + let mut body: Vec = vec![banner(Notice::Error, intro).into()]; + match &conflict.kind { + ConflictKind::Text { hunks } => { + body.push(text(t.t("conflictDiff")).mono().small().dim().into()); + body.push(diff_block(editor, hunks)); + let mine = if conflict.gone() { + t.t("conflictWriteMine") + } else { + t.t("conflictKeepMine") + }; + let buttons = vec![ + button(mine) + .small() + .on_press(Message::ConflictKeepMine) + .into(), + button(t.t("conflictTakeTheirs")) + .small() + .on_press(Message::ConflictTakeTheirs) + .into(), + button(t.t("conflictEdit")) + .ghost() + .small() + .on_press(Message::ConflictBack) + .into(), + ]; + frame(head, body, Some(foot(String::new(), buttons))) + } + ConflictKind::Dotenv { + rows, + changed_on_disk, + .. + } => { + if rows.is_empty() { + body.push(banner(Notice::Info, t.t("conflictNone")).into()); + } else { + let items = rows.iter().map(|row| conflict_row(editor, row)); + body.push( + section(t.t("conflictRows"), [list(items).group().into()]) + .count(rows.len().to_string()) + .into(), + ); + } + if *changed_on_disk > 0 { + body.push( + text(t.tn("conflictTheirsChanged", *changed_on_disk as i64, &[])) + .small() + .dim() + .into(), + ); + } + let buttons = vec![ + button(t.t("conflictApply")) + .primary() + .small() + .on_press(Message::ConflictKeepMine) + .into(), + button(t.t("conflictTakeTheirs")) + .small() + .on_press(Message::ConflictTakeTheirs) + .into(), + ]; + frame(head, body, Some(foot(String::new(), buttons))) + } + } +} + +/// One side of a key that differs: absent, empty, or dotted until shown. +fn side_label(editor: &Editor, row: &ConflictRow, side: Side) -> String { + let t = editor.t(); + let (name, value) = match side { + Side::Mine => (t.t("mine"), Some(&row.mine)), + Side::Theirs => (t.t("theirs"), row.theirs.as_ref()), + }; + let shown = match value { + None => t.t("absent"), + Some(value) if value.is_empty() => t.t("valueEmpty"), + Some(value) if row.revealed => value.clone(), + Some(_) => MASK.to_owned(), + }; + format!("{name} {shown}") +} + +fn conflict_row(editor: &Editor, row: &ConflictRow) -> ListItem> { + let key = row.key.clone(); + let choice = radio( + [ + select_option("mine", side_label(editor, row, Side::Mine)), + select_option("theirs", side_label(editor, row, Side::Theirs)), + ], + Some(if row.choice == Side::Mine { + "mine" + } else { + "theirs" + }), + ) + .on_select(move |value| { + let side = if value == "theirs" { + Side::Theirs + } else { + Side::Mine + }; + Message::ConflictChoose(key.clone(), side) + }); + let choice = if row.revealed { + choice + } else { + choice.horizontal() + }; + item(row.key.clone()) + .mono() + .wrap() + .end(reveal_button( + editor, + row.revealed, + Message::ConflictReveal(row.key.clone()), + )) + .body(choice) +} + +/* ── the editor ───────────────────────────────────────────────────── */ + +fn check_word(editor: &Editor, check: &Check) -> Option { + let t = editor.t(); + let name = check.kind?.name(); + Some(if check.ok { + if check.partial { + state_label(Status::Neutral, t.tv("checkBasic", &[("kind", name)])).into() + } else { + state_label(Status::Success, t.tv("checkOk", &[("kind", name)])).into() + } + } else { + let words = match check.line { + Some(line) => t.tv( + "checkBrokenAt", + &[("kind", name), ("line", &line.to_string())], + ), + None => t.tv("checkBroken", &[("kind", name)]), + }; + state_label(Status::Failure, words).into() + }) +} + +fn text_header(editor: &Editor) -> Header> { + let t = editor.t(); + let check = editor.text.as_ref().map(|text| &text.check); + let state: Vec = if editor.saved { + vec![state_label(Status::Success, t.t("stateSaved")).into()] + } else if let Some(word) = check.and_then(|check| check_word(editor, check)) { + vec![word] + } else if !editor.exists { + vec![state_label(Status::Neutral, t.t("stateNew")).into()] + } else { + Vec::new() + }; + header_of(editor, state) +} + +pub fn check_reason(editor: &Editor, check: &Check) -> String { + let t = editor.t(); + let Some(kind) = check.kind else { + return String::new(); + }; + let name = kind.name(); + if check.ok { + return if check.partial { + t.tv("checkPartial", &[("kind", name)]) + } else { + String::new() + }; + } + let reason = t.t(&format!("check.{}", check.code.unwrap_or("json"))); + match check.line { + Some(line) => t.tv( + "checkBadAt", + &[ + ("kind", name), + ("line", &line.to_string()), + ("reason", &reason), + ], + ), + None => t.tv("checkBad", &[("kind", name), ("reason", &reason)]), + } +} + +fn capitalized(words: &str) -> String { + let mut chars = words.chars(); + match chars.next() { + Some(first) => first.to_uppercase().chain(chars).collect(), + None => String::new(), + } +} + +fn text_edit_view(editor: &Editor) -> El { + let t = editor.t(); + let Some(text_state) = &editor.text else { + return page![loading(t.t("loading"))].into(); + }; + let check = &text_state.check; + let mut notes: Vec = Vec::new(); + notes.extend(request_banner(editor)); + notes.extend(save_problem(editor)); + notes.extend(tell_problem(editor)); + if let Some((line, total)) = text_state.far { + notes.push( + banner( + Notice::Info, + t.tv( + "lineJumpFar", + &[("line", &line.to_string()), ("total", &total.to_string())], + ), + ) + .into(), + ); + } + if !editor.exists { + notes.push(banner(Notice::Info, t.t("newFile")).into()); + } + if check.kind.is_some() && !check.ok { + let bare = t.t(&format!("check.{}", check.code.unwrap_or("json"))); + notes.push(text(capitalized(&bare)).small().tone(Tone::Danger).into()); + } else { + let words = check_reason(editor, check); + if !words.is_empty() { + notes.push(text(words).small().dim().into()); + } + } + + let mut area = text_area("editor", text_state.value.clone()) + .line_numbers() + .fill() + .on_input(Message::EditText); + let broken_line = check.line.filter(|_| !check.ok).map(|line| line as u32); + if let Some(line) = broken_line { + area = area.mark(line_mark(line, Notice::Error).label(check_reason(editor, check))); + } + if let Some(target) = text_state + .target + .filter(|target| Some(*target) != broken_line) + { + area = area.mark(line_mark(target, Notice::Info)); + } + + let buttons: Vec = match &editor.caller { + Some(pane) if can_tell_no_change(editor) => { + vec![tell_button(editor, pane).primary().into()] + } + _ => { + let disabled = editor.busy || (!editor.is_dirty() && editor.exists); + let mut go = button(t.t("review")) + .primary() + .small() + .on_press_maybe((!disabled).then_some(Message::Review)); + if disabled && !editor.busy { + go = go.tooltip(t.t("nothingToSave")); + } + vec![go.into()] + } + }; + + let mut parts: Vec = vec![ + container(text_header(editor)) + .padding([0.0, 12.0]) + .width(Length::Fill) + .into(), + ]; + if !notes.is_empty() { + parts.push( + container(column(notes).spacing(6.0)) + .padding([8.0, 12.0]) + .width(Length::Fill) + .into(), + ); + } + parts.push(area.into()); + parts.push(foot(saved_status(editor), buttons)); + page(parts).fill().into() +} + +fn text_review_view(editor: &Editor) -> El { + let t = editor.t(); + let Some(text_state) = &editor.text else { + return page![loading(t.t("loading"))].into(); + }; + let check = &text_state.check; + let mut body: Vec = Vec::new(); + body.extend(save_problem(editor)); + let broken = check.kind.is_some() && !check.ok; + if broken { + body.push( + banner(Notice::Error, check_reason(editor, check)) + .action(switch(t.t("ackBroken"), text_state.ack).on_toggle(Message::Ack)) + .into(), + ); + } else if check.kind.is_some() && check.partial { + body.push(text(check_reason(editor, check)).small().dim().into()); + } + let hunks = text_state.hunks.as_deref().unwrap_or(&[]); + let changed = hunks.iter().any(Hunk::is_change); + let diff: El = if changed { + diff_block(editor, hunks) + } else { + text(t.t("diffNone")).small().dim().into() + }; + body.push(section(t.t("diffTitle"), [diff]).into()); + + let disabled = editor.busy || (broken && !text_state.ack) || (!changed && editor.exists); + let buttons = vec![ + button(t.t("backToEdit")) + .ghost() + .small() + .on_press(Message::BackToEdit) + .into(), + button(t.t("save")) + .primary() + .small() + .on_press_maybe((!disabled).then_some(Message::SaveText)) + .into(), + ]; + let status = if editor.busy { + t.t("saving") + } else { + String::new() + }; + frame(text_header(editor), body, Some(foot(status, buttons))) +} + +/* ── the picker ───────────────────────────────────────────────────── */ + +fn picker_view(editor: &Editor) -> El { + let t = editor.t(); + let Some(picker) = &editor.picker else { + return page![loading(t.t("loading"))].into(); + }; + let tools = container( + search(t.t("pickFilter"), picker.filter.clone()) + .id("filter") + .on_input(Message::Filter) + .on_clear(Message::Filter(String::new())), + ) + .padding([8.0, 12.0]) + .width(Length::Fill); + + let mut body: Vec = Vec::new(); + if picker.truncated { + body.push(banner(Notice::Warning, t.t("pickTruncated")).into()); + } + let groups: Vec = logic::filter_groups(&picker.groups, &picker.filter) + .into_iter() + .filter(|group| !group.files.is_empty()) + .collect(); + if groups.is_empty() { + body.push(empty(t.t("pickEmpty")).into()); + } + for group in groups { + let items = group.files.iter().map(|file| { + let mut entry = item(js::base_name(&file.path)) + .mono() + .tooltip(file.path.clone()) + .on_press(Message::Pick(file.path.clone())); + let dir = js::dir_name(&file.path); + if !dir.is_empty() { + entry = entry.sub(dir); + } + if file.is_new { + entry = entry.end(chip(t.t("pickNew"))); + } + entry + }); + let mut children: Vec = vec![list(items).into()]; + if group.more > 0 { + children.push( + text(t.tn("pickMore", group.more as i64, &[])) + .small() + .dim() + .into(), + ); + } + body.push( + section(t.t(group.group.title()), children) + .count((group.files.len() + group.more).to_string()) + .into(), + ); + } + let head = header(t.t("pickTitle")); + page![ + container(head).padding([0.0, 12.0]).width(Length::Fill), + tools, + scroll(column(body).spacing(12.0).padding(12.0)), + ] + .fill() + .into() +} + +/* ── the rest ─────────────────────────────────────────────────────── */ + +fn error_view(editor: &Editor) -> El { + let t = editor.t(); + let (kind, detail) = match &editor.error { + Some(error) => (error.kind.as_str(), error.detail.as_str()), + None => ("error", ""), + }; + let title = t.t(&format!("err.{kind}.title")); + let hint = t.t(&format!("err.{kind}.hint")); + let action = if kind == "bad-path" { + button(t.t("pickTitle")) + .primary() + .small() + .on_press(Message::Back) + } else { + button(t.t("retry")) + .primary() + .small() + .on_press(Message::Retry) + }; + let state = if kind == "denied" { + denied(title).text(hint) + } else { + let mut state = failed(title).text(hint); + if !detail.is_empty() { + state = state.child(text(detail).mono().small()); + } + state + }; + page![state.action(action)].into() +} diff --git a/native/tests/common/mod.rs b/native/tests/common/mod.rs new file mode 100644 index 0000000..846ce67 --- /dev/null +++ b/native/tests/common/mod.rs @@ -0,0 +1,623 @@ +//! Shared by the tests: test/helpers.js, ported. A fake Hangar over files held +//! in memory (no test touches a real file of anyone's) answers every call the +//! tab makes, in order, and keeps them all; the tab is driven as a person +//! would, through its page. +#![allow(dead_code)] + +use serde_json::{Value, json}; + +use hangar_kit_sdk::api::{self, KitError}; +use hangar_kit_sdk::testing::{self, Harness, StartExt}; +use hangar_kit_sdk::ui::abi::{Call, Operation}; +use hangar_kit_sdk::ui::{Element, EventValue, HandlerId, ListItem}; + +use kit_editor_tab::Editor; +use kit_editor_tab::editor::KeyRow; + +pub const CALLER: &str = "Asker"; +pub const IGNORED: (&str, &str) = (".gitignore", ".env\n"); + +/// Files in the order they were first written, as a JavaScript `Map` keeps them. +#[derive(Debug, Clone, Default)] +pub struct Store(pub Vec<(String, String)>); + +impl Store { + pub fn get(&self, path: &str) -> Option<&str> { + self.0 + .iter() + .find(|(other, _)| other == path) + .map(|(_, text)| text.as_str()) + } + + pub fn set(&mut self, path: &str, text: &str) { + match self.0.iter_mut().find(|(other, _)| other == path) { + Some(slot) => slot.1 = text.to_owned(), + None => self.0.push((path.to_owned(), text.to_owned())), + } + } + + pub fn delete(&mut self, path: &str) { + self.0.retain(|(other, _)| other != path); + } + + pub fn has(&self, path: &str) -> bool { + self.get(path).is_some() + } +} + +pub fn refusal(code: &str, message: &str) -> KitError { + KitError::new(code, if message.is_empty() { code } else { message }) +} + +/// A Hangar that answers as docs/kits.md says: `files.read` says not_found +/// for what is absent and drops a BOM, `files.write` with `expected` answers +/// conflict when the file holds anything else or is gone, and `deny` lists +/// the methods answered `denied`. +#[derive(Debug, Clone, Default)] +pub struct Fake { + pub store: Store, + pub deny: Vec, + pub send_error: Option, + pub write_error: Option, + pub truncated: bool, + /// How `ui.confirm` is answered. + pub confirm: bool, + /// Reads of these paths are refused: (path, code, message). + pub read_errors: Vec<(String, String, String)>, + /// Every call the tab made, answered, in order. + pub calls: Vec, +} + +fn strip_bom(text: &str) -> &str { + text.strip_prefix('\u{feff}').unwrap_or(text) +} + +/// The manifest's permissions: what the page held, and all the tab may use. +pub const GRANTED: [&str; 3] = ["files.read", "files.write", "panes.send"]; + +impl Fake { + fn answer(&mut self, call: &Call) -> Result { + let method = call.method.as_str(); + // Hangar's own gate: a method there is, under the manifest's permissions. + let granted: Vec = GRANTED + .iter() + .map(|permission| permission.to_string()) + .collect(); + assert!( + api::needs(method).is_some(), + "{method} is no method of Hangar's" + ); + assert!( + api::may_call(method, &call.params, &granted), + "{method} needs what the manifest does not ask for" + ); + if self.deny.iter().any(|denied| denied == method) { + return Err(refusal( + "denied", + &format!("this tab was not granted {method}"), + )); + } + let param = |name: &str| { + call.params + .get(name) + .and_then(Value::as_str) + .unwrap_or("") + .to_owned() + }; + match method { + "tab.setTitle" | "tab.setBadge" => Ok(json!({})), + "files.read" => { + let path = param("path"); + if let Some((_, code, message)) = + self.read_errors.iter().find(|(other, _, _)| *other == path) + { + return Err(refusal(code, message)); + } + match self.store.get(&path) { + Some(text) => Ok(json!(strip_bom(text))), + None => Err(refusal( + "not_found", + &format!("{path} was not found in the workspace folder"), + )), + } + } + "files.list" => Ok(json!({ + "files": self.store.0.iter().map(|(path, text)| json!({ "path": path, "size": text.len(), "modified": 0 })).collect::>(), + "truncated": self.truncated, + })), + "files.write" => { + if let Some(code) = &self.write_error { + return Err(refusal(code, "")); + } + let path = param("path"); + if let Some(expected) = call.params.get("expected") { + let now = self.store.get(&path).map(strip_bom); + if now != expected.as_str() { + return Err(refusal("conflict", "the file changed")); + } + } + self.store.set(&path, ¶m("text")); + Ok(json!({})) + } + "panes.send" => match &self.send_error { + Some(code) => Err(refusal(code, "")), + None => Ok(json!({ "queued": true, "pane": param("pane") })), + }, + "ui.confirm" => Ok(json!(self.confirm)), + _ => Err(refusal("unknown", &format!("unknown {method}"))), + } + } + + pub fn calls_to(&self, method: &str) -> Vec<&Call> { + self.calls + .iter() + .filter(|call| call.method == method) + .collect() + } + + pub fn writes(&self) -> Vec<&Call> { + self.calls_to("files.write") + } + + pub fn writes_to(&self, path: &str) -> Vec<&Call> { + self.writes() + .into_iter() + .filter(|call| call.params["path"] == path) + .collect() + } + + pub fn sent(&self) -> Vec<(String, String)> { + self.calls_to("panes.send") + .into_iter() + .map(|call| { + ( + call.params["pane"].as_str().unwrap_or("").to_owned(), + call.params["text"].as_str().unwrap_or("").to_owned(), + ) + }) + .collect() + } + + pub fn last_badge(&self) -> Value { + self.calls_to("tab.setBadge") + .last() + .map(|call| call.params.clone()) + .unwrap_or(Value::Null) + } +} + +/// What a test starts the tab with. +#[derive(Default)] +pub struct Setup { + pub fake: Fake, + params: Vec<(String, String)>, + caller: Option, + locale: Option, +} + +impl Setup { + pub fn new() -> Self { + Setup::default() + } + + pub fn param(mut self, name: &str, value: &str) -> Self { + self.params.push((name.to_owned(), value.to_owned())); + self + } + + pub fn path(self, path: &str) -> Self { + self.param("path", path) + } + + pub fn caller(mut self, pane: &str) -> Self { + self.caller = Some(pane.to_owned()); + self + } + + pub fn file(mut self, path: &str, text: &str) -> Self { + self.fake.store.set(path, text); + self + } + + pub fn files(mut self, files: &[(&str, &str)]) -> Self { + for (path, text) in files { + self.fake.store.set(path, text); + } + self + } + + pub fn ignored(self) -> Self { + self.file(IGNORED.0, IGNORED.1) + } + + pub fn deny(mut self, method: &str) -> Self { + self.fake.deny.push(method.to_owned()); + self + } + + pub fn send_error(mut self, code: &str) -> Self { + self.fake.send_error = Some(code.to_owned()); + self + } + + pub fn truncated(mut self) -> Self { + self.fake.truncated = true; + self + } + + pub fn confirm(mut self, answer: bool) -> Self { + self.fake.confirm = answer; + self + } + + pub fn read_error(mut self, path: &str, code: &str, message: &str) -> Self { + self.fake + .read_errors + .push((path.to_owned(), code.to_owned(), message.to_owned())); + self + } + + pub fn locale(mut self, locale: &str) -> Self { + self.locale = Some(locale.to_owned()); + self + } + + /// The tab started on these params, every call answered. + pub fn open(self) -> Tab { + let mut start = testing::start().grant(["files.read", "files.write", "panes.send"]); + for (name, value) in &self.params { + start = start.param(name.as_str(), value.as_str()); + } + if let Some(pane) = &self.caller { + start = start.caller(pane.as_str()); + } + if let Some(locale) = &self.locale { + start = start.locale(locale.as_str()); + } + let mut tab = Tab { + harness: Harness::::new(start), + fake: self.fake, + operations: Vec::new(), + }; + tab.settle(); + tab + } +} + +pub struct Tab { + pub harness: Harness, + pub fake: Fake, + /// What the tab asked done to its page, since it started. + pub operations: Vec, +} + +const REVEAL: [&str; 4] = ["Show", "Hide", "Afficher", "Masquer"]; + +impl Tab { + pub fn kit(&self) -> &Editor { + self.harness.kit() + } + + /// Every call answered, as the page's `settle` waited for them. + pub fn settle(&mut self) { + for _ in 0..10_000 { + let Some(call) = self.harness.calls().first().cloned() else { + break; + }; + let answer = self.fake.answer(&call); + self.fake.calls.push(call.clone()); + self.harness.reply(call.id, answer); + } + assert!( + self.harness.calls().is_empty(), + "the tab never stops calling" + ); + self.operations.extend(self.harness.take_operations()); + } + + pub fn store(&self) -> &Store { + &self.fake.store + } + + pub fn row(&self, key: &str) -> &KeyRow { + self.kit() + .form + .as_ref() + .and_then(|form| form.rows.iter().find(|row| row.key == key)) + .unwrap_or_else(|| panic!("no row {key}")) + } + + pub fn keys(&self) -> Vec { + self.kit() + .form + .as_ref() + .map(|form| form.rows.iter().map(|row| row.key.clone()).collect()) + .unwrap_or_default() + } + + pub fn shows(&self, needle: &str) -> bool { + self.harness.shows(needle) + } + + pub fn text(&self) -> String { + self.harness.texts().join("\n") + } + + pub fn press(&mut self, label: &str) { + self.harness.press(label); + self.settle(); + } + + pub fn type_into(&mut self, name: &str, text: &str) { + self.harness.type_into(name, text); + self.settle(); + } + + pub fn toggle(&mut self, label: &str, on: bool) { + self.harness.toggle(label, on); + self.settle(); + } + + pub fn shortcut(&mut self, keys: &str) { + self.harness.shortcut(keys); + self.settle(); + } + + pub fn event(&mut self, name: &str, data: Value) { + self.harness.event(name, data); + self.settle(); + } + + pub fn ui(&mut self, handler: HandlerId, value: Option) { + self.harness.ui(handler, value); + self.settle(); + } + + /// Every element of the page, depth first. + pub fn elements(&self) -> Vec { + let mut all = Vec::new(); + self.harness + .view() + .root + .for_each(&mut |element| all.push(element.clone())); + all + } + + /// The row of a list titled `title`. + pub fn item(&self, title: &str) -> Option { + self.elements() + .into_iter() + .find_map(|element| match element { + Element::List(list) => list.items.into_iter().find(|item| item.title == title), + _ => None, + }) + } + + /// Every element under a row: its end, actions and body. + pub fn inside(item: &ListItem) -> Vec { + let mut all = Vec::new(); + let mut parts: Vec<&Element> = Vec::new(); + parts.extend(item.end.as_deref()); + parts.extend(item.actions.iter()); + parts.extend(item.body.iter()); + for part in parts { + part.for_each(&mut |element| all.push(element.clone())); + } + all + } + + /// The field of a key's value: a text input or a text area, `value:KEY`. + pub fn value_field(&self, key: &str) -> Option { + let id = format!("value:{key}"); + self.elements().into_iter().find(|element| match element { + Element::TextInput(input) => input.id == id, + Element::TextArea(area) => area.id == id, + _ => false, + }) + } + + fn reveal_handler(&self, key: &str) -> Option { + let item = self.item(key)?; + Tab::inside(&item) + .into_iter() + .find_map(|element| match element { + Element::Button(button) + if button + .label + .as_deref() + .is_some_and(|label| REVEAL.contains(&label)) => + { + button.on_press + } + _ => None, + }) + } + + /// Shows or hides a key's value, by its row's button. + pub fn toggle_reveal(&mut self, key: &str) { + let handler = self + .reveal_handler(key) + .unwrap_or_else(|| panic!("no Show button for {key}")); + self.ui(handler, None); + } + + /// Types a value into a key's field, revealing it first when it is a + /// hidden one of several lines, which takes no typing. + pub fn edit_row(&mut self, key: &str, value: &str) { + let handler = |tab: &Tab| match tab.value_field(key) { + Some(Element::TextInput(input)) => input.on_input, + Some(Element::TextArea(area)) => area.on_input, + _ => None, + }; + let handler = match handler(self) { + Some(handler) => handler, + None => { + self.toggle_reveal(key); + handler(self).unwrap_or_else(|| panic!("no field for {key}")) + } + }; + self.ui(handler, Some(EventValue::Text(value.to_owned()))); + } + + /// Presses the Add button of an offered key. + pub fn add_offered(&mut self, key: &str) { + let item = self + .item(key) + .unwrap_or_else(|| panic!("{key} is not offered")); + let handler = item + .actions + .iter() + .find_map(|element| match element { + Element::Button(button) => button.on_press, + _ => None, + }) + .unwrap_or_else(|| panic!("{key} has no Add")); + self.ui(handler, None); + } + + /// Chooses a side of a key in the dotenv conflict: `mine` or `theirs`. + pub fn choose_side(&mut self, key: &str, side: &str) { + let item = self + .item(key) + .unwrap_or_else(|| panic!("no conflict row {key}")); + let handler = Tab::inside(&item) + .into_iter() + .find_map(|element| match element { + Element::Radio(radio) => radio.on_select, + _ => None, + }) + .unwrap_or_else(|| panic!("no choice for {key}")); + self.ui(handler, Some(EventValue::Text(side.to_owned()))); + } + + /// The radio buttons of a key in the dotenv conflict: (labels, chosen). + pub fn sides(&self, key: &str) -> (Vec, Option) { + let item = self + .item(key) + .unwrap_or_else(|| panic!("no conflict row {key}")); + Tab::inside(&item) + .into_iter() + .find_map(|element| match element { + Element::Radio(radio) => Some(( + radio + .options + .iter() + .map(|option| option.label.clone()) + .collect(), + radio.selected, + )), + _ => None, + }) + .unwrap_or_default() + } + + /// The button labelled `label`, if the page shows one. + pub fn button(&self, label: &str) -> Option { + self.elements() + .into_iter() + .find_map(|element| match element { + Element::Button(button) if button.label.as_deref() == Some(label) => Some(button), + _ => None, + }) + } + + /// Whether the button labelled `label` can be pressed. + pub fn enabled(&self, label: &str) -> bool { + self.button(label) + .unwrap_or_else(|| panic!("no button {label:?}")) + .on_press + .is_some() + } + + /// The labels of the primary buttons on the page. + pub fn primaries(&self) -> Vec { + self.elements() + .into_iter() + .filter_map(|element| match element { + Element::Button(button) + if button.kind == hangar_kit_sdk::ui::ButtonKind::Primary => + { + button.label + } + _ => None, + }) + .collect() + } + + /// The titles of the page's sections. + pub fn sections(&self) -> Vec { + self.elements() + .into_iter() + .filter_map(|element| match element { + Element::Section(section) => Some(section.title), + _ => None, + }) + .collect() + } + + /// The header's state line, as words. + pub fn header_state(&self) -> String { + self.elements() + .into_iter() + .find_map(|element| match element { + Element::Header(header) => Some(header), + _ => None, + }) + .map(|header| { + let mut words = Vec::new(); + for part in &header.state { + part.for_each(&mut |element| match element { + Element::State(state) => words.push(state.label.clone()), + Element::Text(text) => words.push(text.text.clone()), + _ => {} + }); + } + words.join(" ") + }) + .unwrap_or_default() + } + + /// The header's title. + pub fn title(&self) -> String { + self.elements() + .into_iter() + .find_map(|element| match element { + Element::Header(header) => Some(header.title), + _ => None, + }) + .unwrap_or_default() + } + + /// The page as JSON: every string it carries, to look for a value in. + pub fn view_json(&self) -> Value { + serde_json::to_value(self.harness.view()).expect("a view is JSON") + } + + /// Every string of the page with the key that holds it, depth first. + pub fn strings(&self) -> Vec<(String, String)> { + fn walk(value: &Value, key: &str, out: &mut Vec<(String, String)>) { + match value { + Value::String(text) => out.push((key.to_owned(), text.clone())), + Value::Array(items) => items.iter().for_each(|item| walk(item, key, out)), + Value::Object(map) => map.iter().for_each(|(name, item)| walk(item, name, out)), + _ => {} + } + } + let mut out = Vec::new(); + walk(&self.view_json(), "", &mut out); + out + } + + /// The cursor moves the tab asked for: (line, column). + pub fn cursor_moves(&self) -> Vec<(u32, u32)> { + self.operations + .iter() + .filter_map(|operation| match operation { + Operation::CursorTo { id, line, column } if id == "editor" => { + Some((*line, *column)) + } + _ => None, + }) + .collect() + } +} diff --git a/native/tests/controller.rs b/native/tests/controller.rs new file mode 100644 index 0000000..73c5b8e --- /dev/null +++ b/native/tests/controller.rs @@ -0,0 +1,1241 @@ +//! The tab's behaviour against a fake Hangar: what it reads, when it writes, +//! what it refuses to write, and what it says when Hangar answers no. +//! test/controller.test.js, ported: each case drives the tab through its page. + +mod common; + +use serde_json::{Value, json}; + +use common::{CALLER, Setup}; +use kit_editor_tab::diff::{Hunk, Kind}; +use kit_editor_tab::editor::{ConflictKind, IgnoreStatus, Screen, Side, Stage, TellStatus}; +use kit_editor_tab::logic; + +fn changes(hunks: &[Hunk]) -> Vec<(Kind, String)> { + hunks + .iter() + .filter_map(|hunk| match hunk { + Hunk::Line(op) if op.kind != Kind::Same => Some((op.kind, op.text.clone())), + _ => None, + }) + .collect() +} + +/* ── the dotenv form ──────────────────────────────────────────────── */ + +#[test] +fn a_dotenv_file_opens_as_a_form_one_row_per_key_hidden_its_comments_and_order_kept_on_save() { + let text = "# Database\nDB_URL=old\n\n# Payments\nexport STRIPE_KEY='x' # test mode\nLOG=debug\nDB_URL=later\n"; + let mut tab = Setup::new() + .path(".env") + .file(".env", text) + .ignored() + .open(); + assert_eq!(tab.kit().screen, Screen::Dotenv); + assert_eq!(tab.keys(), ["DB_URL", "STRIPE_KEY", "LOG"]); + assert!( + tab.kit() + .form + .as_ref() + .unwrap() + .rows + .iter() + .all(|row| !row.revealed), + "hidden until revealed" + ); + assert_eq!(tab.row("DB_URL").value, "later"); + assert_eq!(tab.row("DB_URL").count, 2); + assert_eq!(tab.row("STRIPE_KEY").hint, "Payments"); + + tab.edit_row("STRIPE_KEY", "sk_new"); + tab.press("Save"); + assert_eq!( + tab.store().get(".env"), + Some( + "# Database\nDB_URL=old\n\n# Payments\nexport STRIPE_KEY='sk_new' # test mode\nLOG=debug\nDB_URL=later\n" + ) + ); + assert_eq!( + tab.fake.writes()[0].params["expected"], + text, + "with what it read" + ); + assert!(tab.kit().saved); + assert_eq!(tab.fake.last_badge()["state"], "success"); +} + +#[test] +fn a_value_is_revealed_row_by_row_and_hidden_again_after_saving() { + let mut tab = Setup::new() + .path(".env") + .file(".env", "A=1\nB=2\n") + .ignored() + .open(); + tab.toggle_reveal("A"); + assert!(tab.row("A").revealed); + assert!(!tab.row("B").revealed); + tab.edit_row("A", "9"); + tab.press("Save"); + assert!(!tab.row("A").revealed); +} + +#[test] +fn the_keys_an_agent_asks_for_come_first_marked_missing_with_why_at_the_top() { + let mut tab = Setup::new() + .path(".env") + .param("keys", "NEW_ONE, PRESENT,EMPTY") + .param("why", "For the payment tests.") + .caller(CALLER) + .file(".env", "OTHER=1\nPRESENT=x\nEMPTY=\n") + .ignored() + .open(); + assert_eq!(tab.kit().why.as_deref(), Some("For the payment tests.")); + assert_eq!(tab.keys(), ["NEW_ONE", "PRESENT", "EMPTY", "OTHER"]); + let asked: Vec = tab + .kit() + .form + .as_ref() + .unwrap() + .rows + .iter() + .map(|row| row.asked) + .collect(); + assert_eq!(asked, [true, true, true, false]); + assert_eq!(tab.fake.last_badge()["text"], "2 missing"); + tab.edit_row("NEW_ONE", "v"); + assert_eq!(tab.fake.last_badge()["text"], "1 missing"); + tab.edit_row("EMPTY", "v"); + assert_eq!(tab.fake.last_badge()["state"], Value::Null); +} + +#[test] +fn a_key_asked_and_left_empty_is_not_written_one_filled_in_goes_at_the_end() { + let mut tab = Setup::new() + .path(".env") + .param("keys", "FILLED,LEFT") + .caller(CALLER) + .file(".env", "OTHER=1\n") + .ignored() + .open(); + tab.edit_row("FILLED", "v"); + tab.press("Save"); + assert_eq!(tab.store().get(".env"), Some("OTHER=1\nFILLED=v\n")); + assert_eq!( + tab.fake.sent(), + [( + "Asker".to_owned(), + "The person saved `.env`. Set: FILLED. Still empty: LEFT. The values stay in the file: do not read them back, use them through the program that loads it.".to_owned() + )] + ); + assert!(tab.row("LEFT").asked, "still asked for"); +} + +#[test] +fn a_file_that_does_not_exist_yet_opens_empty_and_saving_creates_it() { + let mut tab = Setup::new() + .path("config/.env") + .param("keys", "A") + .file(".gitignore", "*.env\n.env\n") + .open(); + assert_eq!(tab.kit().screen, Screen::Dotenv); + assert!(!tab.kit().exists); + tab.edit_row("A", "1"); + tab.press("Save"); + assert_eq!(tab.store().get("config/.env"), Some("A=1\n")); + assert_eq!( + tab.fake.writes()[0].params.get("expected"), + None, + "there was nothing to expect" + ); + assert!(tab.kit().exists); +} + +#[test] +fn keys_of_env_example_missing_here_are_offered_not_added() { + let mut tab = Setup::new() + .path(".env") + .param("keys", "FROM_EXAMPLE") + .file(".env", "HERE=1\n") + .file( + ".env.example", + "HERE=\n# Where to find it\nFROM_EXAMPLE=placeholder\n# Second\nEXTRA=placeholder\nANOTHER=\n", + ) + .ignored() + .open(); + let offered = |tab: &common::Tab| -> Vec { + tab.kit() + .form + .as_ref() + .unwrap() + .offered + .iter() + .map(|offer| offer.key.clone()) + .collect() + }; + assert_eq!(offered(&tab), ["EXTRA", "ANOTHER"]); + assert_eq!(tab.kit().form.as_ref().unwrap().offered[0].hint, "Second"); + assert_eq!( + tab.kit().form.as_ref().unwrap().example_name.as_deref(), + Some(".env.example") + ); + assert_eq!(tab.row("FROM_EXAMPLE").hint, "Where to find it"); + assert_eq!( + tab.row("FROM_EXAMPLE").value, + "", + "the example's value is not taken for a real one" + ); + assert!(!tab.kit().is_dirty(), "nothing is added until asked"); + + tab.add_offered("EXTRA"); + assert_eq!(tab.row("EXTRA").value, ""); + assert_eq!(offered(&tab), ["ANOTHER"]); + tab.edit_row("EXTRA", "mine"); + tab.press("Save"); + assert_eq!(tab.store().get(".env"), Some("HERE=1\nEXTRA=mine\n")); + assert_eq!( + offered(&tab), + ["ANOTHER"], + "what is still missing stays offered" + ); + assert_eq!( + tab.row("FROM_EXAMPLE").hint, + "Where to find it", + "and the template still explains what is asked" + ); + + tab.add_offered("ANOTHER"); + tab.press("Save"); + assert_eq!( + tab.store().get(".env"), + Some("HERE=1\nEXTRA=mine\nANOTHER=\n"), + "an explicit add is written, even empty" + ); + assert!(offered(&tab).is_empty()); +} + +#[test] +fn add_all_takes_every_offered_key() { + let mut tab = Setup::new() + .path(".env") + .file(".env", "") + .file(".env.example", "A=\nB=\n") + .ignored() + .open(); + tab.press("Add all"); + assert_eq!(tab.keys(), ["A", "B"]); + tab.press("Save"); + assert_eq!(tab.store().get(".env"), Some("A=\nB=\n")); +} + +#[test] +fn a_template_offers_nothing_and_needs_no_warning() { + let tab = Setup::new() + .path(".env.example") + .file(".env.example", "A=\n") + .open(); + assert!(tab.kit().form.as_ref().unwrap().offered.is_empty()); + assert_eq!( + tab.kit().ignore.as_ref().unwrap().status, + IgnoreStatus::Ignored + ); + let gitignores = tab + .fake + .calls_to("files.read") + .into_iter() + .filter(|call| { + call.params["path"] + .as_str() + .unwrap() + .ends_with(".gitignore") + }) + .count(); + assert_eq!(gitignores, 0); +} + +#[test] +fn a_key_the_person_adds_is_checked_and_a_bad_one_says_why() { + let mut tab = Setup::new() + .path(".env") + .file(".env", "A=1\n") + .ignored() + .open(); + tab.type_into("KEY_NAME", "not a key"); + tab.press("Add"); + assert_eq!( + tab.kit().form.as_ref().unwrap().new_key_problem, + Some("newKeyBad") + ); + assert!( + tab.shows("A key is letters") + || tab + .strings() + .iter() + .any(|(key, text)| key == "error" && text.starts_with("A key is letters")) + ); + tab.type_into("KEY_NAME", "A"); + tab.press("Add"); + assert_eq!( + tab.kit().form.as_ref().unwrap().new_key_problem, + Some("newKeyTaken") + ); + tab.type_into("KEY_NAME", " B_KEY "); + tab.press("Add"); + let form = tab.kit().form.as_ref().unwrap(); + assert_eq!(form.new_key_problem, None); + assert_eq!(form.new_key, ""); + assert!(tab.row("B_KEY").added); +} + +#[test] +fn enter_in_the_new_key_field_adds_it() { + let mut tab = Setup::new().path(".env").file(".env", "").ignored().open(); + tab.type_into("KEY_NAME", "FRESH"); + let submit = tab + .elements() + .into_iter() + .find_map(|element| match element { + hangar_kit_sdk::ui::Element::TextInput(input) if input.id == "new-key" => { + input.on_submit + } + _ => None, + }) + .expect("Enter adds"); + tab.ui(submit, None); + assert!(tab.row("FRESH").typed); +} + +/* ── git ──────────────────────────────────────────────────────────── */ + +#[test] +fn not_ignored_it_says_so_and_gitignore_changes_only_on_a_click() { + let mut tab = Setup::new() + .path(".env") + .file(".env", "A=1\n") + .file(".gitignore", "node_modules/\n") + .open(); + assert_eq!( + tab.kit().ignore.as_ref().unwrap().status, + IgnoreStatus::NotIgnored + ); + assert!(tab.fake.writes().is_empty(), "opening writes nothing"); + tab.edit_row("A", "2"); + tab.press("Save"); + assert!( + tab.fake.writes_to(".gitignore").is_empty(), + "saving the file does not touch it either" + ); + + tab.press("Add .env to .gitignore"); + assert_eq!(tab.store().get(".gitignore"), Some("node_modules/\n.env\n")); + assert_eq!( + tab.fake.writes_to(".gitignore")[0].params["expected"], + "node_modules/\n" + ); + assert_eq!( + tab.kit().ignore.as_ref().unwrap().status, + IgnoreStatus::Ignored + ); +} + +#[test] +fn no_gitignore_at_all_said_plainly_and_the_click_creates_one() { + let mut tab = Setup::new() + .path("sub/.env.local") + .file("sub/.env.local", "A=1\n") + .open(); + assert_eq!( + tab.kit().ignore.as_ref().unwrap().status, + IgnoreStatus::NoFile + ); + tab.press("Add sub/.env.local to .gitignore"); + assert_eq!(tab.store().get(".gitignore"), Some("sub/.env.local\n")); + assert_eq!( + tab.fake.writes_to(".gitignore")[0].params.get("expected"), + None + ); + assert_eq!( + tab.kit().ignore.as_ref().unwrap().status, + IgnoreStatus::Ignored + ); +} + +#[test] +fn a_gitignore_that_moved_under_the_click_is_not_overwritten_and_a_denied_one_says_so() { + let mut tab = Setup::new() + .path(".env") + .file(".env", "A=1\n") + .file(".gitignore", "old\n") + .open(); + tab.fake.write_error = Some("rate_limited".into()); + tab.press("Add .env to .gitignore"); + let ignore = tab.kit().ignore.clone().unwrap(); + assert_eq!(ignore.problem.as_deref(), Some("rate_limited")); + assert_eq!(ignore.status, IgnoreStatus::NotIgnored); + assert!(!ignore.busy); + assert_eq!(tab.store().get(".gitignore"), Some("old\n")); + assert!(tab.shows(".gitignore was not changed: at most 10 saves a minute.")); + tab.fake.write_error = None; + tab.press("Add .env to .gitignore"); + assert_eq!(tab.store().get(".gitignore"), Some("old\n.env\n")); +} + +#[test] +fn a_gitignore_that_cannot_be_read_leaves_the_question_open_and_the_form_works() { + let tab = Setup::new() + .path(".env") + .file(".env", "A=1\n") + .read_error(".gitignore", "denied", "no") + .open(); + assert_eq!( + tab.kit().ignore.as_ref().unwrap().status, + IgnoreStatus::Unknown + ); + assert_eq!(tab.kit().screen, Screen::Dotenv); + assert!(tab.shows("Could not read .gitignore")); +} + +/* ── any other text file ──────────────────────────────────────────── */ + +#[test] +fn a_text_file_opens_in_the_editor_at_the_line_asked_for() { + let lines: Vec = (1..=9).map(|i| format!("line {i}")).collect(); + let lines = lines.join("\n"); + let tab = Setup::new() + .path("notes.txt") + .param("line", "7") + .file("notes.txt", &lines) + .open(); + let text = tab.kit().text.as_ref().unwrap(); + assert_eq!(tab.kit().screen, Screen::Text); + assert_eq!(tab.cursor_moves(), [(7, 1)], "the cursor goes there once"); + assert_eq!(text.target, Some(7)); + assert_eq!(text.check.kind, None); + let far = Setup::new() + .path("notes.txt") + .param("line", "70") + .file("notes.txt", &lines) + .open(); + assert_eq!(far.cursor_moves(), [(9, 1)], "as far as the file goes"); + assert_eq!(far.kit().text.as_ref().unwrap().far, Some((70, 9))); + assert!(far.shows("Line 70 was asked for; the file has 9.")); +} + +#[test] +fn a_diff_comes_before_saving_and_saving_sends_what_was_reviewed() { + let mut tab = Setup::new() + .path("a.txt") + .file("a.txt", "one\ntwo\nthree\n") + .open(); + tab.type_into("editor", "one\nTWO\nthree\n"); + assert!(tab.fake.writes().is_empty(), "typing writes nothing"); + tab.press("Review changes"); + let text = tab.kit().text.as_ref().unwrap(); + assert_eq!(text.stage, Stage::Review); + assert_eq!( + changes(text.hunks.as_ref().unwrap()), + [(Kind::Del, "two".to_owned()), (Kind::Add, "TWO".to_owned())] + ); + assert!(tab.fake.writes().is_empty(), "reviewing writes nothing"); + tab.press("Save"); + assert_eq!(tab.store().get("a.txt"), Some("one\nTWO\nthree\n")); + assert_eq!(tab.fake.writes()[0].params["expected"], "one\ntwo\nthree\n"); + assert_eq!(tab.kit().text.as_ref().unwrap().stage, Stage::Edit); + assert!(tab.kit().saved); +} + +#[test] +fn line_endings_survive_the_editor() { + let mut crlf = Setup::new() + .path("a.txt") + .file("a.txt", "one\r\ntwo\r\n") + .open(); + assert_eq!( + crlf.kit().text.as_ref().unwrap().value, + "one\ntwo\n", + "as an editor would hold it" + ); + crlf.type_into("editor", "one\ntwo\nthree\n"); + crlf.press("Review changes"); + let texts: Vec = changes(crlf.kit().text.as_ref().unwrap().hunks.as_ref().unwrap()) + .into_iter() + .map(|(_, text)| text) + .collect(); + assert_eq!(texts, ["three"], "the line endings are no change"); + crlf.press("Save"); + assert_eq!(crlf.store().get("a.txt"), Some("one\r\ntwo\r\nthree\r\n")); + + let mut mixed = Setup::new() + .path("a.txt") + .file("a.txt", "a\r\nb\nc\r\nd\r\n") + .open(); + mixed.type_into("editor", "a\nB\nc\nd\n"); + mixed.press("Review changes"); + mixed.press("Save"); + assert_eq!( + mixed.store().get("a.txt"), + Some("a\r\nB\r\nc\r\nd\r\n"), + "only the changed line takes the common one" + ); +} + +#[test] +fn a_broken_file_is_saved_only_after_saying_so() { + let mut tab = Setup::new() + .path("a.json") + .file("a.json", "{\"a\": 1}\n") + .open(); + assert!(tab.kit().text.as_ref().unwrap().check.ok); + tab.type_into("editor", "{\"a\": 1,}\n"); + assert!(!tab.kit().text.as_ref().unwrap().check.ok); + tab.press("Review changes"); + assert!(!tab.enabled("Save"), "not without saying so"); + // Ctrl+S reviews in the editor; in the review it is nothing, as in the page. + assert!(tab.harness.subscriptions().shortcuts.is_empty()); + assert!(tab.fake.writes().is_empty()); + assert_eq!(tab.store().get("a.json"), Some("{\"a\": 1}\n")); + + tab.toggle("I know this file is broken: save it anyway.", true); + assert!(tab.enabled("Save")); + tab.press("← Back to editing"); + tab.type_into("editor", "{\"a\": 1,,}\n"); + assert!( + !tab.kit().text.as_ref().unwrap().ack, + "changing the text takes back what was said" + ); + tab.press("Review changes"); + assert!(!tab.kit().text.as_ref().unwrap().ack); + assert!(!tab.enabled("Save")); + assert!(tab.fake.writes().is_empty()); + + tab.toggle("I know this file is broken: save it anyway.", true); + tab.press("Save"); + assert_eq!(tab.store().get("a.json"), Some("{\"a\": 1,,}\n")); +} + +#[test] +fn a_save_from_an_older_view_still_needs_the_person_to_say_so() { + // The SDK keeps eight views' handlers: a click drawn before the text broke + // must not write it. + let mut tab = Setup::new() + .path("a.json") + .file("a.json", "{\"a\": 1}\n") + .open(); + tab.type_into("editor", "{\"a\": 2}\n"); + tab.press("Review changes"); + let seq = tab.harness.view().seq; + let save = tab.button("Save").unwrap().on_press.unwrap(); + tab.press("← Back to editing"); + tab.type_into("editor", "{\"a\": 2,}\n"); + tab.harness.ui_from(seq, save, None); + tab.settle(); + assert!(tab.fake.writes().is_empty()); +} + +#[test] +fn a_file_already_broken_when_opened_follows_the_same_rule() { + let mut tab = Setup::new().path("a.toml").file("a.toml", "a = \n").open(); + assert!(!tab.kit().text.as_ref().unwrap().check.ok); + tab.type_into("editor", "a = \nb = 2\n"); + tab.press("Review changes"); + assert!(!tab.enabled("Save")); + assert!(tab.fake.writes().is_empty()); +} + +#[test] +fn a_new_text_file_the_whole_of_it_is_the_diff_and_it_is_created() { + let mut tab = Setup::new().path("conf/new.yaml").open(); + assert_eq!(tab.kit().screen, Screen::Text); + assert!(!tab.kit().exists); + tab.type_into("editor", "a: 1\n"); + tab.press("Review changes"); + tab.press("Save"); + assert_eq!(tab.store().get("conf/new.yaml"), Some("a: 1\n")); + assert_eq!(tab.fake.writes()[0].params.get("expected"), None); +} + +#[test] +fn ctrl_s_saves_the_form_and_reviews_the_text() { + let mut form = Setup::new() + .path(".env") + .file(".env", "A=1\n") + .ignored() + .open(); + form.edit_row("A", "2"); + form.shortcut("mod+s"); + assert_eq!(form.store().get(".env"), Some("A=2\n")); + + let mut text = Setup::new().path("a.txt").file("a.txt", "x\n").open(); + text.type_into("editor", "y\n"); + text.shortcut("mod+s"); + assert_eq!(text.kit().text.as_ref().unwrap().stage, Stage::Review); + assert!(text.fake.writes().is_empty(), "reviewing is not saving"); + assert!( + text.harness.subscriptions().shortcuts.is_empty(), + "nothing to do with it in the review" + ); +} + +/* ── conflicts ────────────────────────────────────────────────────── */ + +fn edited_then_moved(caller: bool) -> common::Tab { + let mut setup = Setup::new().path("a.txt").file("a.txt", "base\n"); + if caller { + setup = setup.caller(CALLER); + } + let mut tab = setup.open(); + tab.type_into("editor", "mine\n"); + tab.press("Review changes"); + tab.fake.store.set("a.txt", "theirs\n"); + tab.press("Save"); + tab +} + +#[test] +fn text_conflict_nothing_is_written_until_the_person_chooses_and_both_sides_show() { + let mut tab = edited_then_moved(true); + assert_eq!( + tab.store().get("a.txt"), + Some("theirs\n"), + "never overwritten silently" + ); + let conflict = tab.kit().conflict.clone().unwrap(); + assert_eq!(conflict.theirs.as_deref(), Some("theirs\n")); + let ConflictKind::Text { hunks } = &conflict.kind else { + panic!("a text conflict"); + }; + assert_eq!( + changes(hunks), + [ + (Kind::Del, "theirs".to_owned()), + (Kind::Add, "mine".to_owned()) + ] + ); + assert!( + tab.fake.sent().is_empty(), + "no answer for what was not written" + ); + + tab.press("Replace it with mine"); + assert_eq!(tab.store().get("a.txt"), Some("mine\n")); + assert_eq!( + tab.fake.writes().last().unwrap().params["expected"], + "theirs\n", + "measured against what the person just saw" + ); + assert!(tab.kit().conflict.is_none()); + assert_eq!(tab.fake.sent().len(), 1); +} + +#[test] +fn text_conflict_taking_theirs_drops_mine_and_writes_nothing() { + let mut tab = edited_then_moved(false); + let before = tab.fake.writes().len(); + tab.press("Keep what is on disk, lose mine"); + assert_eq!(tab.kit().text.as_ref().unwrap().value, "theirs\n"); + assert!(!tab.kit().is_dirty()); + assert_eq!(tab.fake.writes().len(), before); + assert_eq!(tab.store().get("a.txt"), Some("theirs\n")); +} + +#[test] +fn text_conflict_back_to_editing_keeps_mine_against_what_the_disk_holds_now() { + let mut tab = edited_then_moved(false); + tab.press("Back to editing, with mine"); + let text = tab.kit().text.as_ref().unwrap(); + assert_eq!(text.value, "mine\n"); + assert_eq!(text.original, "theirs\n"); + assert_eq!(text.stage, Stage::Edit); + tab.press("Review changes"); + tab.press("Save"); + assert_eq!(tab.store().get("a.txt"), Some("mine\n")); +} + +#[test] +fn the_file_moved_twice_a_second_conflict_is_a_conflict_again() { + let mut tab = edited_then_moved(false); + tab.fake.store.set("a.txt", "theirs again\n"); + tab.press("Replace it with mine"); + assert_eq!(tab.store().get("a.txt"), Some("theirs again\n")); + assert_eq!( + tab.kit().conflict.as_ref().unwrap().theirs.as_deref(), + Some("theirs again\n") + ); +} + +#[test] +fn a_file_deleted_meanwhile_is_a_conflict_and_writing_it_back_is_a_choice() { + let mut tab = Setup::new().path("a.txt").file("a.txt", "base\n").open(); + tab.type_into("editor", "mine\n"); + tab.press("Review changes"); + tab.fake.store.delete("a.txt"); + tab.press("Save"); + assert!(!tab.store().has("a.txt")); + assert!(tab.kit().conflict.as_ref().unwrap().gone()); + assert!(tab.shows("The file was deleted while you were editing it. Nothing was written.")); + tab.press("Write mine"); + assert_eq!(tab.store().get("a.txt"), Some("mine\n")); +} + +#[test] +fn a_new_file_that_appeared_meanwhile_is_a_conflict_too() { + let mut tab = Setup::new() + .path(".env") + .param("keys", "A") + .ignored() + .open(); + tab.edit_row("A", "mine"); + tab.fake.store.set(".env", "A=theirs\n"); + tab.press("Save"); + assert_eq!( + tab.store().get(".env"), + Some("A=theirs\n"), + "not overwritten though nothing was expected" + ); + assert!(matches!( + tab.kit().conflict.as_ref().unwrap().kind, + ConflictKind::Dotenv { .. } + )); +} + +#[test] +fn dotenv_conflict_key_by_key_hidden_and_my_keys_go_on_top_of_what_the_disk_holds() { + let mut tab = Setup::new() + .path(".env") + .caller(CALLER) + .file(".env", "# base\nA=1\nB=2\nC=3\n") + .ignored() + .open(); + tab.edit_row("A", "mine-a"); + tab.edit_row("B", "mine-b"); + tab.fake + .store + .set(".env", "# moved\nA=theirs-a\nB=2\nC=3\nD=new\n"); + tab.press("Save"); + + assert_eq!( + tab.store().get(".env"), + Some("# moved\nA=theirs-a\nB=2\nC=3\nD=new\n") + ); + let conflict = tab.kit().conflict.clone().unwrap(); + let ConflictKind::Dotenv { + rows, + changed_on_disk, + .. + } = &conflict.kind + else { + panic!("a dotenv conflict"); + }; + let shown: Vec<(&str, &str, Option<&str>, Side, bool)> = rows + .iter() + .map(|row| { + ( + row.key.as_str(), + row.mine.as_str(), + row.theirs.as_deref(), + row.choice, + row.revealed, + ) + }) + .collect(); + assert_eq!( + shown, + [ + ("A", "mine-a", Some("theirs-a"), Side::Mine, false), + ("B", "mine-b", Some("2"), Side::Mine, false), + ] + ); + assert_eq!(*changed_on_disk, 1, "D"); + assert!(tab.fake.sent().is_empty()); + + tab.toggle_reveal("A"); + let ConflictKind::Dotenv { rows, .. } = &tab.kit().conflict.as_ref().unwrap().kind else { + panic!("still a conflict"); + }; + assert!(rows[0].revealed); + tab.choose_side("A", "theirs"); + tab.press("Save with these choices"); + assert_eq!( + tab.store().get(".env"), + Some("# moved\nA=theirs-a\nB=mine-b\nC=3\nD=new\n"), + "their comment and their key stay" + ); + assert_eq!( + tab.fake.writes().last().unwrap().params["expected"], + "# moved\nA=theirs-a\nB=2\nC=3\nD=new\n" + ); + assert!(tab.fake.sent()[0].1.contains("Set: B.")); + assert!(tab.kit().conflict.is_none()); + assert_eq!(tab.row("D").value, "new", "the form now reads the new file"); +} + +#[test] +fn dotenv_conflict_when_nothing_collides_it_still_asks() { + let mut tab = Setup::new() + .path(".env") + .file(".env", "A=1\nB=2\n") + .ignored() + .open(); + tab.edit_row("A", "mine"); + tab.fake.store.set(".env", "A=1\nB=theirs\n"); + tab.press("Save"); + let ConflictKind::Dotenv { rows, .. } = &tab.kit().conflict.as_ref().unwrap().kind else { + panic!("a dotenv conflict"); + }; + assert_eq!(rows.len(), 1, "A: mine is not what the disk holds"); + assert_eq!(tab.store().get(".env"), Some("A=1\nB=theirs\n")); + tab.press("Keep what is on disk, lose mine"); + assert_eq!(tab.row("B").value, "theirs"); + assert_eq!(tab.row("A").value, "1"); + assert!(!tab.kit().is_dirty()); +} + +/* ── who asked ────────────────────────────────────────────────────── */ + +#[test] +fn the_agent_is_answered_on_save_and_only_when_one_asked() { + let mut text = Setup::new() + .path("a.txt") + .caller(CALLER) + .file("a.txt", "x\n") + .open(); + text.type_into("editor", "y\n"); + text.press("Review changes"); + text.press("Save"); + assert_eq!( + text.fake.sent(), + [( + "Asker".to_owned(), + "The person saved `a.txt`: the file changed.".to_owned() + )] + ); + assert_eq!(text.kit().told.as_ref().unwrap().status, TellStatus::Sent); + + let mut nobody = Setup::new().path("a.txt").file("a.txt", "x\n").open(); + nobody.type_into("editor", "y\n"); + nobody.press("Review changes"); + nobody.press("Save"); + assert!(nobody.fake.sent().is_empty()); + assert!(nobody.kit().told.is_none()); +} + +#[test] +fn nothing_to_change_the_waiting_agent_can_still_be_told_with_names_only() { + let mut tab = Setup::new() + .path(".env") + .param("keys", "SET_KEY,EMPTY_KEY") + .caller(CALLER) + .file(".env", "SET_KEY=abc\nEMPTY_KEY=\n") + .ignored() + .open(); + tab.press("Tell Asker: nothing to change"); + assert_eq!( + tab.fake.sent()[0].1, + "The person checked `.env` and changed nothing. Already set: SET_KEY. Still empty: EMPTY_KEY. The values stay in the file: do not read them back, use them through the program that loads it." + ); + assert_eq!(tab.kit().told.as_ref().unwrap().status, TellStatus::Checked); + assert!(tab.fake.writes().is_empty()); + + let mut text = Setup::new() + .path("a.txt") + .caller(CALLER) + .file("a.txt", "x\n") + .open(); + text.press("Tell Asker: nothing to change"); + assert_eq!( + text.fake.sent()[0].1, + "The person checked `a.txt` and changed nothing." + ); + text.type_into("editor", "y\n"); + assert!( + text.button("Tell Asker: nothing to change").is_none(), + "not while something is unsaved" + ); + assert_eq!(text.fake.sent().len(), 1); +} + +#[test] +fn an_agent_that_cannot_be_told_saved_all_the_same_it_says_so_and_it_can_try_again() { + let mut tab = Setup::new() + .path(".env") + .caller(CALLER) + .file(".env", "A=1\n") + .ignored() + .send_error("not_found") + .open(); + tab.edit_row("A", "2"); + tab.press("Save"); + assert_eq!(tab.store().get(".env"), Some("A=2\n")); + assert!(tab.kit().saved); + let told = tab.kit().told.clone().unwrap(); + assert_eq!( + (told.status, told.pane.as_str(), told.code.as_deref()), + (TellStatus::Failed, "Asker", Some("not_found")) + ); + tab.fake.send_error = None; + tab.press("Tell Asker again"); + assert_eq!(tab.kit().told.as_ref().unwrap().status, TellStatus::Sent); +} + +#[test] +fn asked_again_the_latest_to_ask_is_answered_and_what_was_typed_stays() { + let mut tab = Setup::new() + .path(".env") + .param("keys", "A") + .caller(CALLER) + .file(".env", "A=\nB=2\n") + .ignored() + .open(); + tab.edit_row("A", "typing"); + tab.event( + "tab.params", + json!({ "params": { "path": ".env", "keys": "A,NEW", "why": "Now this too." }, "caller": { "pane": "Other" } }), + ); + assert_eq!(tab.kit().caller.as_deref(), Some("Other")); + assert_eq!(tab.row("A").value, "typing"); + assert_eq!(tab.kit().why.as_deref(), Some("Now this too.")); + let rows: Vec<(String, bool)> = tab + .kit() + .form + .as_ref() + .unwrap() + .rows + .iter() + .map(|row| (row.key.clone(), row.asked)) + .collect(); + assert_eq!( + rows, + [ + ("A".to_owned(), true), + ("NEW".to_owned(), true), + ("B".to_owned(), false) + ] + ); + let reads = tab + .fake + .calls_to("files.read") + .into_iter() + .filter(|call| call.params["path"] == ".env") + .count(); + assert_eq!(reads, 1, "not read again"); + tab.press("Save"); + assert_eq!(tab.fake.sent()[0].0, "Other"); +} + +#[test] +fn asked_again_after_a_save_the_new_asker_can_be_told_there_is_nothing_more_to_change() { + let mut tab = Setup::new() + .path("a.txt") + .caller(CALLER) + .file("a.txt", "x\n") + .open(); + tab.type_into("editor", "y\n"); + tab.press("Review changes"); + tab.press("Save"); + assert!(tab.kit().saved); + tab.event( + "tab.params", + json!({ "params": { "path": "a.txt" }, "caller": { "pane": "Other" } }), + ); + assert!(!tab.kit().saved); + assert!(tab.kit().told.is_none()); + tab.press("Tell Other: nothing to change"); + assert_eq!( + tab.fake.sent().last().unwrap(), + &( + "Other".to_owned(), + "The person checked `a.txt` and changed nothing.".to_owned() + ) + ); +} + +#[test] +fn the_person_opening_it_again_takes_the_caller_away_and_nobody_is_told() { + let mut tab = Setup::new() + .path("a.txt") + .caller(CALLER) + .file("a.txt", "x\n") + .open(); + tab.event( + "tab.params", + json!({ "params": { "path": "a.txt" }, "caller": null }), + ); + assert!(tab.kit().caller.is_none()); + tab.type_into("editor", "y\n"); + tab.press("Review changes"); + tab.press("Save"); + assert!(tab.fake.sent().is_empty()); +} + +#[test] +fn asked_for_another_file_it_opens_that_one() { + let mut tab = Setup::new() + .path("a.txt") + .file("a.txt", "x\n") + .file("b.txt", "y\n") + .open(); + tab.event( + "tab.params", + json!({ "params": { "path": "b.txt" }, "caller": null }), + ); + assert_eq!(tab.kit().path.as_deref(), Some("b.txt")); + assert_eq!(tab.kit().text.as_ref().unwrap().value, "y\n"); +} + +/* ── what Hangar refuses ──────────────────────────────────────────── */ + +#[test] +fn reading_denied_a_page_that_says_what_to_do_with_nothing_written() { + let tab = Setup::new() + .path(".env") + .file(".env", "A=1\n") + .deny("files.read") + .open(); + assert_eq!(tab.kit().screen, Screen::Error); + assert_eq!(tab.kit().error.as_ref().unwrap().kind, "denied"); + assert!(tab.fake.writes().is_empty()); +} + +#[test] +fn listing_denied_the_picker_says_so_too() { + let tab = Setup::new().deny("files.list").open(); + assert_eq!(tab.kit().screen, Screen::Error); + assert_eq!(tab.kit().error.as_ref().unwrap().kind, "denied"); +} + +#[test] +fn writing_denied_or_over_the_limit_the_edits_stay_and_it_says_so() { + for code in ["denied", "rate_limited", "invalid", "failed"] { + let mut tab = Setup::new() + .path(".env") + .file(".env", "A=1\n") + .ignored() + .open(); + tab.fake.write_error = Some(code.into()); + tab.edit_row("A", "typed"); + tab.press("Save"); + let expected = if code == "failed" { "other" } else { code }; + assert_eq!(tab.kit().problem.as_ref().unwrap().code, expected); + assert!( + tab.shows(&logic::strings("en").t(&format!("write.{expected}"))), + "{code}" + ); + assert_eq!(tab.row("A").value, "typed", "{code}"); + assert!(tab.kit().is_dirty()); + assert!(!tab.kit().saved); + assert!(!tab.kit().busy); + tab.fake.write_error = None; + tab.press("Save"); + assert_eq!(tab.store().get(".env"), Some("A=typed\n")); + assert!(tab.kit().problem.is_none()); + } +} + +#[test] +fn panes_send_denied_saved_and_it_says_the_agent_was_not_told() { + let mut tab = Setup::new() + .path("a.txt") + .caller(CALLER) + .file("a.txt", "x\n") + .deny("panes.send") + .open(); + tab.type_into("editor", "y\n"); + tab.press("Review changes"); + tab.press("Save"); + assert_eq!(tab.store().get("a.txt"), Some("y\n")); + assert_eq!( + tab.kit().told.as_ref().unwrap().code.as_deref(), + Some("denied") + ); +} + +#[test] +fn a_title_or_a_badge_refused_changes_nothing() { + let tab = Setup::new() + .path(".env") + .param("keys", "A") + .file(".env", "") + .ignored() + .deny("tab.setTitle") + .deny("tab.setBadge") + .open(); + assert_eq!(tab.kit().screen, Screen::Dotenv); +} + +#[test] +fn a_path_that_can_never_open_said_as_such_and_hangar_is_not_asked() { + for path in [ + "../outside", + "/etc/passwd", + "C:/x", + ".git/config", + "a/../b", + "sub\\.GIT\\hooks", + "a. ", + ] { + let tab = Setup::new().path(path).open(); + assert_eq!(tab.kit().screen, Screen::Error, "{path}"); + assert_eq!(tab.kit().error.as_ref().unwrap().kind, "bad-path", "{path}"); + assert!(tab.fake.calls_to("files.read").is_empty(), "{path}"); + } +} + +#[test] +fn a_file_hangar_cannot_read_shows_why() { + let tab = Setup::new() + .path("big.txt") + .read_error("big.txt", "failed", "big.txt is larger than 1 MB") + .open(); + let error = tab.kit().error.as_ref().unwrap(); + assert_eq!(error.kind, "failed"); + assert_eq!(error.detail, "big.txt is larger than 1 MB"); +} + +#[test] +fn try_again_reads_the_file_again() { + let mut tab = Setup::new() + .path("a.txt") + .read_error("a.txt", "unavailable", "gone") + .open(); + assert_eq!(tab.kit().error.as_ref().unwrap().kind, "unavailable"); + tab.fake.read_errors.clear(); + tab.fake.store.set("a.txt", "back\n"); + tab.press("Try again"); + assert_eq!(tab.kit().text.as_ref().unwrap().value, "back\n"); +} + +/* ── the picker ───────────────────────────────────────────────────── */ + +#[test] +fn no_params_a_picker_env_files_first_then_config_what_is_not_text_left_out() { + let mut tab = Setup::new() + .files(&[ + ("README.md", ""), + ("src/app.ts", ""), + ("logo.png", ""), + ("package.json", "{}"), + ("pnpm-lock.yaml", ""), + ("config/app.yaml", ""), + (".env.local", "A=1"), + ("sub/.env", ""), + (".npmrc", ""), + ("tsconfig.json", "{}"), + ]) + .open(); + assert_eq!(tab.kit().screen, Screen::Picker); + assert_eq!(tab.fake.calls_to("files.list").len(), 1); + let groups = &tab.kit().picker.as_ref().unwrap().groups; + let env: Vec<(&str, bool)> = groups + .env + .iter() + .map(|file| (file.path.as_str(), file.is_new)) + .collect(); + assert_eq!( + env, + [(".env", true), (".env.local", false), ("sub/.env", false)] + ); + let config: Vec<&str> = groups + .config + .iter() + .map(|file| file.path.as_str()) + .collect(); + assert_eq!( + config, + ["package.json", "config/app.yaml", ".npmrc", "tsconfig.json"] + ); + let other: Vec<&str> = groups.other.iter().map(|file| file.path.as_str()).collect(); + assert_eq!(other, ["README.md", "src/app.ts", "pnpm-lock.yaml"]); + + tab.press(".env.local"); + assert_eq!(tab.kit().screen, Screen::Dotenv); + assert!(tab.kit().from_picker); + assert_eq!(tab.kit().path.as_deref(), Some(".env.local")); + assert_eq!( + tab.fake.calls_to("tab.setTitle").last().unwrap().params["title"], + ".env.local" + ); + + tab.press("← Files"); + assert_eq!(tab.kit().screen, Screen::Picker); + assert!(tab.kit().path.is_none()); +} + +#[test] +fn the_pickers_filter_and_a_listing_that_was_cut() { + let mut paths = vec!["a.yaml".to_owned(), "b/.env".to_owned()]; + paths.extend((0..450).map(|i| format!("src/f{i}.ts"))); + let groups = logic::rank_files(paths.iter().map(String::as_str)); + let counts: Vec = logic::filter_groups(&groups, "YAML") + .iter() + .map(|group| group.files.len()) + .collect(); + assert_eq!(counts, [0, 1, 0], "any case"); + let all = logic::filter_groups(&groups, ""); + assert_eq!(all[2].files.len(), 200); + assert_eq!(all[2].more, 250); + let tab = Setup::new().file("a.txt", "").truncated().open(); + assert!(tab.kit().picker.as_ref().unwrap().truncated); + assert!(tab.shows("This folder holds more files than Hangar lists")); +} + +/* ── params, read like form input ─────────────────────────────────── */ + +#[test] +fn params() { + assert_eq!( + logic::parse_keys(Some("A, B ,A,not a key,1BAD,C.D")), + ["A", "B", "C.D"] + ); + assert!(logic::parse_keys(None).is_empty()); + assert_eq!(logic::parse_line(Some("12")), Some(12)); + for bad in ["0", "-1", "1e3", "abc", ""] { + assert_eq!(logic::parse_line(Some(bad)), None, "{bad}"); + } + assert_eq!(logic::parse_line(None), None); + assert_eq!( + logic::check_path("a\\b/./c.txt").as_deref(), + Some("a/b/c.txt") + ); + assert_eq!(logic::check_path(".env").as_deref(), Some(".env")); + assert_eq!( + logic::check_path(".github/x.yml").as_deref(), + Some(".github/x.yml") + ); + let params = [("path", ".env"), ("why", " why "), ("keys", "A")] + .into_iter() + .map(|(name, value)| (name.to_owned(), value.to_owned())) + .collect(); + let read = logic::read_params(¶ms, Some("P")); + assert_eq!( + read, + logic::Params { + path: Some(".env".into()), + bad_path: false, + keys: vec!["A".into()], + why: Some("why".into()), + line: None, + caller: Some("P".into()), + } + ); + assert_eq!( + logic::read_params(&Default::default(), Some("")).caller, + None + ); + assert_eq!( + logic::tab_title(&format!("a/{}", "x".repeat(60))) + .chars() + .count(), + 40 + ); +} + +#[test] +fn the_language_follows_hangars() { + let mut tab = Setup::new() + .path(".env") + .file(".env", "A=1\n") + .ignored() + .open(); + assert!(tab.shows("In this file")); + tab.event("theme", json!({ "scheme": "dark", "locale": "fr" })); + assert!(tab.shows("Dans ce fichier")); +} diff --git a/native/tests/diff.rs b/native/tests/diff.rs new file mode 100644 index 0000000..b3bdbf3 --- /dev/null +++ b/native/tests/diff.rs @@ -0,0 +1,140 @@ +//! the HTML tab's Node test of the same name, ported before the page was deleted. + +use std::time::Instant; + +use kit_editor_tab::diff::{self, Hunk, Kind}; + +fn changes(before: &str, after: &str) -> Vec<(Kind, String)> { + diff::diff_lines(before, after) + .into_iter() + .filter(|op| op.kind != Kind::Same) + .map(|op| (op.kind, op.text)) + .collect() +} + +fn ch(kind: Kind, text: &str) -> (Kind, String) { + (kind, text.to_owned()) +} + +#[test] +fn what_changed_line_by_line_with_both_numberings() { + assert!(changes("a\nb\nc", "a\nb\nc").is_empty()); + assert_eq!( + changes("a\nb\nc", "a\nX\nc"), + [ch(Kind::Del, "b"), ch(Kind::Add, "X")] + ); + assert_eq!(changes("a\nc", "a\nb\nc"), [ch(Kind::Add, "b")]); + assert_eq!(changes("a\nb\nc", "a\nc"), [ch(Kind::Del, "b")]); + assert_eq!(changes("", "a\n"), [ch(Kind::Add, "a")]); + let ops: Vec<(Kind, Option, Option)> = diff::diff_lines("a\nb\nc", "a\nX\nY\nc") + .into_iter() + .map(|op| (op.kind, op.a, op.b)) + .collect(); + assert_eq!( + ops, + [ + (Kind::Same, Some(1), Some(1)), + (Kind::Del, Some(2), None), + (Kind::Add, None, Some(2)), + (Kind::Add, None, Some(3)), + (Kind::Same, Some(3), Some(4)), + ] + ); +} + +#[test] +fn lines_moved_in_the_middle_of_a_block_are_found() { + assert_eq!( + changes("1\n2\n3\n4\n5\n6", "1\n3\n4\nnew\n5\n6"), + [ch(Kind::Del, "2"), ch(Kind::Add, "new")] + ); +} + +#[test] +fn a_change_too_large_to_compare_is_shown_replaced_not_lost() { + let big = |prefix: &str| { + (0..3000) + .map(|i| format!("{prefix}{i}")) + .collect::>() + .join("\n") + }; + let ops = diff::diff_lines(&big("a"), &big("b")); + assert_eq!(ops.iter().filter(|op| op.kind == Kind::Del).count(), 3000); + assert_eq!(ops.iter().filter(|op| op.kind == Kind::Add).count(), 3000); +} + +#[test] +fn a_small_change_in_a_large_file_is_cheap() { + let lines: Vec = (0..50000).map(|i| format!("line {i}")).collect(); + let mut changed = lines.clone(); + changed[25000] = "changed".into(); + let started = Instant::now(); + let ops = diff::diff_lines(&lines.join("\n"), &changed.join("\n")); + assert!(started.elapsed().as_millis() < 1000); + let texts: Vec = ops + .into_iter() + .filter(|op| op.kind != Kind::Same) + .map(|op| op.text) + .collect(); + assert_eq!(texts, ["line 25000", "changed"]); +} + +#[test] +fn unchanged_stretches_fold_around_the_changes() { + let lines = (0..20) + .map(|i| i.to_string()) + .collect::>() + .join("\n"); + let changed = lines.replace("\n10\n", "\nten\n"); + let hunks = diff::hunks(diff::diff_lines(&lines, &changed)); + let shown: Vec = hunks + .iter() + .map(|hunk| match hunk { + Hunk::Skip(count) => format!("skip {count}"), + Hunk::Line(op) => op.text.clone(), + }) + .collect(); + assert_eq!( + shown, + [ + "skip 7", "7", "8", "9", "10", "ten", "11", "12", "13", "skip 6" + ] + ); + assert!(!diff::has_changes(&diff::diff_lines("a", "a"))); + assert!(diff::has_changes(&diff::diff_lines("a", "b"))); + assert_eq!( + diff::hunks(diff::diff_lines("a\nb", "a\nb")), + [Hunk::Skip(2)] + ); +} + +#[test] +fn what_an_editor_takes_away_comes_back() { + assert_eq!(diff::normalize("a\r\nb\rc\n"), "a\nb\nc\n"); + assert_eq!(diff::restore_eols("a\nb\n", "a\nc\n"), "a\nc\n"); + assert_eq!( + diff::restore_eols("a\r\nb\r\n", "a\nc\nd\n"), + "a\r\nc\r\nd\r\n" + ); + assert_eq!( + diff::restore_eols("no end of line", "no end\nof line"), + "no end\nof line" + ); + assert_eq!(diff::restore_eols("", "new\n"), "new\n"); + assert_eq!( + diff::restore_eols("a\r\nb\nc\r\n", "a\nb\nc\n"), + "a\r\nb\nc\r\n", + "mixed, untouched" + ); + assert_eq!( + diff::restore_eols("a\r\nb\nc\r\n", "a\nb\nnew\nc\n"), + "a\r\nb\nnew\r\nc\r\n", + "a new line takes the common one" + ); + assert_eq!(diff::restore_eols("a\rb\r", "a\nb\nc\n"), "a\rb\rc\r"); + assert_eq!( + diff::restore_eols("a\r\nb", "a\nb\nc"), + "a\r\nb\r\nc", + "the old last line had none of its own" + ); +} diff --git a/native/tests/dotenv.rs b/native/tests/dotenv.rs new file mode 100644 index 0000000..655371a --- /dev/null +++ b/native/tests/dotenv.rs @@ -0,0 +1,350 @@ +//! Comments, order and every untouched byte survive a save; a value is a +//! value, even over several lines, and is never read as a key. +//! the HTML tab's Node test of the same name, ported before the page was deleted. + +use kit_editor_tab::dotenv; + +fn value(doc: &dotenv::Doc, key: &str) -> Option { + dotenv::rows(doc) + .into_iter() + .find(|row| row.key == key) + .map(|row| row.value) +} + +fn keys(doc: &dotenv::Doc) -> Vec { + dotenv::rows(doc).into_iter().map(|row| row.key).collect() +} + +fn edit(text: &str, edits: &[(&str, &str)]) -> String { + let edits: Vec<(String, String)> = edits + .iter() + .map(|(key, value)| (key.to_string(), value.to_string())) + .collect(); + dotenv::serialize(&dotenv::with_values(&dotenv::parse(text), &edits)) +} + +const SHAPES: &[(&str, &str)] = &[ + ("empty", ""), + ("one line, no end of line", "A=1"), + ("plain", "# head\n\nA=1\nB=2\n"), + ("crlf", "# head\r\n\r\nA=1\r\nB=2\r\n"), + ("mixed endings", "A=1\r\nB=2\nC=3\r\n"), + ("lone CR", "A=1\rB=2\r"), + ("exported", "export A=1\n export B = 2\n"), + ("spaced", "A = 1\nB= 2\nC =3\n\tD=4\n"), + ("quotes", "A=\"1\"\nB='2'\nC=`3`\nD=\"\"\nE=''\n"), + ( + "inline comments", + "A=1 # one\nB=\"2\" # two\nC= # three\nD=a#b\n", + ), + ( + "several lines", + "A=\"one\ntwo\nB=inside\"\nC='x\ny=z'\nD=1\n", + ), + ("CRLF inside a value", "A='one\r\ntwo'\r\nB=2\r\n"), + ("unclosed quotes", "A=\"open\nB=2\nC='open\nD=4\n"), + ( + "escaped quotes", + "A=\"say \\\"hi\\\"\"\nB='it\\'s'\nC=\"back\\\\\"\n", + ), + ( + "not understood", + "just-a-token\nA=1\n1BAD=2\nKEY: value\n=lonely\n", + ), + ("duplicates", "A=1\n# again\nA=2\nB=3\nA=4\n"), + ("blank lines at the end", "A=1\n\n\n"), + ("trailing blanks", "A=1 \nB=2\t\n"), + ("unicode", "NOM=Éléonore\nÉTÉ=chaud\nA=✓\n"), + ("equals in a value", "A=b=c==\nURL=https://x.y/?a=1&b=2\n"), +]; + +fn shape(name: &str) -> &'static str { + SHAPES.iter().find(|(other, _)| *other == name).unwrap().1 +} + +#[test] +fn read_and_written_back_unchanged() { + for (name, text) in SHAPES { + assert_eq!(dotenv::serialize(&dotenv::parse(text)), *text, "{name}"); + assert_eq!(edit(text, &[]), *text, "{name}"); + } +} + +#[test] +fn values_are_read_as_parsers_read_them() { + let inline = shape("inline comments") + .replace("A=", "F=") + .replace("B=", "G=") + .replace("C=", "H=") + .replace("D=", "I="); + let doc = dotenv::parse(&format!("{}{inline}", shape("quotes"))); + assert_eq!(value(&doc, "A").as_deref(), Some("1")); + assert_eq!(value(&doc, "B").as_deref(), Some("2")); + assert_eq!(value(&doc, "C").as_deref(), Some("3")); + assert_eq!(value(&doc, "D").as_deref(), Some("")); + assert_eq!(value(&doc, "E").as_deref(), Some("")); + assert_eq!( + value(&doc, "F").as_deref(), + Some("1"), + "a comment after a blank is no part of the value" + ); + assert_eq!(value(&doc, "G").as_deref(), Some("2")); + assert_eq!( + value(&doc, "H").as_deref(), + Some(""), + "nothing but a comment" + ); + assert_eq!( + value(&doc, "I").as_deref(), + Some("a#b"), + "a # inside a word is part of it" + ); + assert_eq!( + value(&dotenv::parse(shape("exported")), "B").as_deref(), + Some("2") + ); + assert_eq!( + value(&dotenv::parse(shape("spaced")), "D").as_deref(), + Some("4") + ); + assert_eq!( + value(&dotenv::parse(shape("equals in a value")), "A").as_deref(), + Some("b=c==") + ); + let escaped = dotenv::parse(shape("escaped quotes")); + assert_eq!(value(&escaped, "A").as_deref(), Some("say \"hi\"")); + assert_eq!(value(&escaped, "B").as_deref(), Some("it's")); + assert_eq!(value(&escaped, "C").as_deref(), Some("back\\")); +} + +#[test] +fn what_is_inside_a_multi_line_value_is_no_key_and_an_unclosed_quote_swallows_nothing() { + let several = dotenv::parse(shape("several lines")); + assert_eq!( + keys(&several), + ["A", "C", "D"], + "B=inside and y=z belong to values" + ); + assert_eq!(value(&several, "A").as_deref(), Some("one\ntwo\nB=inside")); + assert_eq!(value(&several, "C").as_deref(), Some("x\ny=z")); + let unclosed = dotenv::parse(shape("unclosed quotes")); + assert_eq!(keys(&unclosed), ["A", "B", "C", "D"]); + assert_eq!(value(&unclosed, "A").as_deref(), Some("\"open")); +} + +#[test] +fn a_private_key_over_several_lines_none_of_its_lines_is_a_key() { + let pem = "-----BEGIN KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQ=\nabcDEF123=\n-----END KEY-----"; + let doc = dotenv::parse(&format!("A=1\nPRIVATE_KEY=\"{pem}\"\nB=2\n")); + assert_eq!(keys(&doc), ["A", "PRIVATE_KEY", "B"]); + assert_eq!(value(&doc, "PRIVATE_KEY").as_deref(), Some(pem)); +} + +#[test] +fn a_line_that_is_no_pair_is_no_key_and_is_counted_to_say_so() { + let doc = dotenv::parse(shape("not understood")); + assert_eq!(keys(&doc), ["A"]); + assert_eq!(dotenv::other_lines(&doc), 4); + assert_eq!(dotenv::other_lines(&dotenv::parse("# comment\n\nA=1\n")), 0); +} + +#[test] +fn setting_a_value_changes_that_line_and_no_other() { + assert_eq!( + edit( + "# head\n\nA=1\n\n# about b\nB=2 # inline\n# tail\n", + &[("B", "new")] + ), + "# head\n\nA=1\n\n# about b\nB=new # inline\n# tail\n" + ); + assert_eq!(edit("export A=1\n", &[("A", "2")]), "export A=2\n"); + assert_eq!(edit(" A = 1\n", &[("A", "2")]), " A = 2\n"); + assert_eq!( + edit("A=\"1\"\n", &[("A", "2")]), + "A=\"2\"\n", + "its quotes are kept when nothing needs them changed" + ); + assert_eq!(edit("A='1'\r\nB=2\r\n", &[("A", "x")]), "A='x'\r\nB=2\r\n"); + assert_eq!(edit("A= # empty\n", &[("A", "x")]), "A= x # empty\n"); + assert_eq!( + edit("A=\"one\ntwo\" # c\nB=1\n", &[("A", "x")]), + "A=\"x\" # c\nB=1\n" + ); + assert_eq!(edit("A=1\n", &[("A", "1")]), "A=1\n"); +} + +#[test] +fn a_new_key_goes_at_the_end_in_the_files_line_endings_and_nothing_moves() { + assert_eq!(edit("A=1\n", &[("Z", "9")]), "A=1\nZ=9\n"); + assert_eq!( + edit("A=1", &[("Z", "9")]), + "A=1\nZ=9\n", + "the last line gets its end of line first" + ); + assert_eq!( + edit("A=1\r\nB=2\r\n", &[("Z", "9")]), + "A=1\r\nB=2\r\nZ=9\r\n" + ); + assert_eq!(edit("", &[("Z", "9")]), "Z=9\n"); + assert_eq!( + edit("# only a comment\n", &[("Z", "9"), ("Y", "8")]), + "# only a comment\nZ=9\nY=8\n" + ); +} + +#[test] +fn a_key_defined_twice_shows_once_and_the_last_line_is_the_one_read_and_edited() { + let doc = dotenv::parse(shape("duplicates")); + let a = dotenv::rows(&doc) + .into_iter() + .find(|row| row.key == "A") + .unwrap(); + assert_eq!(a.value, "4"); + assert_eq!(a.count, 3); + assert_eq!( + edit(shape("duplicates"), &[("A", "x")]), + "A=1\n# again\nA=2\nB=3\nA=x\n" + ); +} + +#[test] +fn any_value_is_read_back_the_same_once_written() { + let values = [ + "plain", + "with space", + " leading", + "trailing ", + "#hash", + "a #b", + "it's", + "say \"hi\"", + "both ' and \"", + "back\\slash", + "ends\\", + "$HOME", + "${HOME}", + "`tick`", + "two\nlines", + "two\r\nlines", + "it's\ntwo", + "a=b", + "é✓", + "=", + "'", + "\"", + "\\", + "\\n", + "'\\n'", + "tab\there", + ]; + for original in ["A=1\n", "A=\"1\"\n", "A='1'\n", "export A = 1 # c\n"] { + for wanted in values { + let text = edit(original, &[("A", wanted), ("B", wanted)]); + let doc = dotenv::parse(&text); + assert_eq!( + value(&doc, "A").as_deref(), + Some(wanted), + "{wanted:?} over {original:?}: {text:?}" + ); + assert_eq!( + value(&doc, "B").as_deref(), + Some(wanted), + "{wanted:?} as a new key: {text:?}" + ); + assert_eq!(keys(&doc), ["A", "B"], "{text:?}"); + } + } +} + +#[test] +fn the_comment_above_a_key_is_its_hint_but_a_value_put_aside_in_a_comment_is_not() { + let rows = dotenv::rows(&dotenv::parse( + "# Get one at the dashboard\n# (free)\nA=1\n\n# unrelated\n\nB=2\n# OLD_TOKEN=abc123\n#export C=1\nC=3\n", + )); + assert_eq!(rows[0].hint, "Get one at the dashboard (free)"); + assert_eq!(rows[1].hint, "", "a blank line cuts the link"); + assert_eq!(rows[2].hint, ""); +} + +#[test] +fn which_keys_changed_names_only() { + let changed = dotenv::changed_keys( + &dotenv::parse("A=1\nB=2\nC=\nD=4\n"), + &dotenv::parse("A=1\nB=x\nC=y\nD=\nE=z\nF=\n"), + ); + assert_eq!(changed.set, ["B", "C", "E"]); + assert_eq!(changed.emptied, ["D"]); +} + +#[test] +fn what_counts_as_a_dotenv_file_and_what_as_a_template() { + for path in [ + ".env", + ".env.local", + "config/.env.production", + "app.env", + "a/b/prod.ENV", + ".env.example", + ] { + assert!(dotenv::is_dotenv_path(path), "{path}"); + } + for path in [ + ".envrc", + "env", + "env.json", + "dotenv", + ".environment", + "config.yaml", + ".env/file", + ] { + assert!(!dotenv::is_dotenv_path(path), "{path}"); + } + assert!(dotenv::is_example_path("sub/.env.example")); + assert!(dotenv::is_example_path(".env.sample")); + assert!(!dotenv::is_example_path(".env")); + assert!(!dotenv::is_example_path(".env.local")); + assert_eq!( + dotenv::example_candidates("sub/.env.local")[..3], + [ + "sub/.env.local.example", + "sub/.env.local.sample", + "sub/.env.example" + ] + ); + assert!(!dotenv::example_candidates(".env.example").contains(&".env.example".to_owned())); +} + +#[test] +fn no_text_makes_the_parser_panic() { + // A panic's message is logged, and Rust's for a cut inside a character + // quotes the text: none may happen whatever a file holds. + let pieces = [ + "A", "=", "\"", "'", "`", "\\", "#", " ", "\t", "\n", "\r", "é", "😀", "export ", "x", + ]; + let mut seed: u32 = 7; + for _ in 0..3000 { + let mut text = String::new(); + for _ in 0..(seed % 24) { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + text.push_str(pieces[(seed as usize) % pieces.len()]); + } + let doc = dotenv::parse(&text); + assert_eq!(dotenv::serialize(&doc), text); + let rows = dotenv::rows(&doc); + let edits: Vec<(String, String)> = rows + .iter() + .map(|row| (row.key.clone(), format!("{}é\n'\"", row.value))) + .collect(); + let written = dotenv::serialize(&dotenv::with_values(&doc, &edits)); + let back = dotenv::parse(&written); + for (key, wanted) in &edits { + assert_eq!( + value(&back, key).as_ref(), + Some(wanted), + "{text:?} → {written:?}" + ); + } + } +} diff --git a/native/tests/gitignore.rs b/native/tests/gitignore.rs new file mode 100644 index 0000000..f67abd1 --- /dev/null +++ b/native/tests/gitignore.rs @@ -0,0 +1,208 @@ +//! Git's rules, and git itself as the judge: the table below is run through +//! `git check-ignore` in a temporary repository when git is on the machine. +//! the HTML tab's Node test of the same name, ported before the page was deleted. + +use std::path::PathBuf; +use std::process::Command; + +use kit_editor_tab::gitignore::{self, Source}; + +fn root(text: &str) -> Vec { + vec![Source { + dir: String::new(), + text: text.to_owned(), + }] +} + +// (.gitignore, path, ignored?) +const TABLE: &[(&str, &str, bool)] = &[ + ("", ".env", false), + (".env\n", ".env", true), + (".env\n", "sub/.env", true), + ("/.env\n", ".env", true), + ("/.env\n", "sub/.env", false), + ("sub/.env\n", "sub/.env", true), + ("sub/.env\n", "other/sub/.env", false), + (".env*\n", ".env.local", true), + (".env*\n", "sub/.env", true), + ("*.env\n", "app.env", true), + ("*.env\n", ".env", true), + ("*.env\n", "sub/app.env", true), + (".env\n!.env\n", ".env", false), + (".env*\n!.env.example\n", ".env.example", false), + (".env*\n!.env.example\n", ".env.local", true), + ("!.env\n.env\n", ".env", true), + ("# .env\n", ".env", false), + ("\\#x\n", "#x", true), + ("\\!x\n", "!x", true), + ("config/\n", "config/.env", true), + ("config/\n", "a/config/.env", true), + ("config/\n", "config", false), + ("/config/\n", "a/config/.env", false), + ("config\n", "config", true), + ("config\n", "config/.env", true), + ("config/*\n!config/.env\n", "config/.env", false), + ("config/\n!config/.env\n", "config/.env", true), + ("**/.env\n", "a/b/.env", true), + ("**/.env\n", ".env", true), + ("a/**/.env\n", "a/.env", true), + ("a/**/.env\n", "a/b/c/.env", true), + ("a/**\n", "a/b/.env", true), + ("a/**\n", "a", false), + ("*\n", "a/b", true), + ("*\n!a/\n!a/b\n", "a/b", false), + (".en?\n", ".env", true), + (".en?\n", ".env/x", true), + (".e[nm]v\n", ".env", true), + (".e[!n]v\n", ".env", false), + (".e[a-z]v\n", ".env", true), + (" .env\n", ".env", false), + (".env \n", ".env", true), + (".env\r\n", ".env", true), + ("a b\n", "a b", true), + ("foo*bar\n", "foo/bar", false), + ("a/*/b\n", "a/x/b", true), + ("a/*/b\n", "a/x/y/b", false), + ("[\n", "[", false), +]; + +#[test] +fn gits_rules() { + for (text, file, expected) in TABLE { + assert_eq!( + gitignore::is_ignored(&root(text), file), + *expected, + "{text:?} on {file}" + ); + } +} + +#[test] +fn deeper_gitignore_files_have_the_last_word() { + let sources = vec![ + Source { + dir: String::new(), + text: ".env\n".into(), + }, + Source { + dir: "sub".into(), + text: "!.env\n".into(), + }, + ]; + assert!(!gitignore::is_ignored(&sources, "sub/.env")); + assert!(gitignore::is_ignored(&sources, ".env")); + assert!(gitignore::is_ignored(&sources, "other/.env")); + let sub = |text: &str| { + vec![Source { + dir: "sub".into(), + text: text.into(), + }] + }; + assert!(gitignore::is_ignored(&sub("/x\n"), "sub/x")); + assert!(!gitignore::is_ignored(&sub("/x\n"), "x")); + assert!(!gitignore::is_ignored(&sub("/x\n"), "sub/y/x")); +} + +#[test] +fn the_gitignore_files_that_have_a_say() { + assert_eq!( + gitignore::sources_for(".env"), + [(String::new(), ".gitignore".to_owned())] + ); + let paths: Vec = gitignore::sources_for("a/b/.env") + .into_iter() + .map(|(_, path)| path) + .collect(); + assert_eq!(paths, [".gitignore", "a/.gitignore", "a/b/.gitignore"]); +} + +#[test] +fn the_line_a_click_adds_ignores_that_very_file_whatever_its_name() { + for file in [ + ".env", + "sub/.env", + "a b/.env", + "we[ird]/.env", + "st*r/.env", + "#x/.env", + "!x/.env", + "back\\slash.env", + ] { + let pattern = gitignore::pattern_for(file); + assert!( + gitignore::is_ignored(&root(&format!("{pattern}\n")), file), + "{file} by {pattern}" + ); + } + assert_eq!(gitignore::pattern_for(".env"), ".env"); + assert_eq!(gitignore::with_pattern("", ".env"), ".env\n"); + assert_eq!(gitignore::with_pattern("a\n", ".env"), "a\n.env\n"); + assert_eq!(gitignore::with_pattern("a", ".env"), "a\n.env\n"); + assert_eq!( + gitignore::with_pattern("a\r\nb\r\n", ".env"), + "a\r\nb\r\n.env\r\n" + ); +} + +#[test] +fn ranges_out_of_order_and_odd_classes_match_nothing_as_the_page_did() { + assert!( + !gitignore::is_ignored(&root(".e[z-a]v\n"), ".env"), + "the page's RegExp threw: no rule" + ); + assert!( + gitignore::is_ignored(&root(".e[]n]v\n"), ".env"), + "a ] first is a character" + ); + assert!( + gitignore::is_ignored(&root(".e[a-]v\n"), ".e-v"), + "a - last is a character" + ); +} + +fn git(dir: &PathBuf, args: &[&str]) -> Option { + Command::new("git") + .args(args) + .current_dir(dir) + .output() + .ok() +} + +#[test] +fn git_agrees_with_the_table() { + let temp = std::env::temp_dir(); + if git(&temp, &["--version"]).is_none_or(|out| !out.status.success()) { + eprintln!("git is not installed: skipped"); + return; + } + for (index, (text, file, expected)) in TABLE.iter().enumerate() { + // Names Windows cannot create are for the logic above, not for git here. + if cfg!(windows) && file.contains(['*', '?', '[', ']']) { + continue; + } + let dir = temp.join(format!("editor-kit-{}-{index}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + git(&dir, &["init", "-q"]).unwrap(); + std::fs::write(dir.join(".gitignore"), text).unwrap(); + let answer = git( + &dir, + &[ + "-c", + "core.excludesFile=", + "-c", + "core.ignorecase=false", + "check-ignore", + "--no-index", + "-q", + file, + ], + ) + .unwrap(); + let _ = std::fs::remove_dir_all(&dir); + assert_eq!( + answer.status.success(), + *expected, + "git says otherwise of {text:?} on {file}" + ); + } +} diff --git a/native/tests/manifest.rs b/native/tests/manifest.rs new file mode 100644 index 0000000..f9dc689 --- /dev/null +++ b/native/tests/manifest.rs @@ -0,0 +1,154 @@ +//! The manifest names the module, and the module is one Hangar loads: the +//! native cases of test/manifest.test.js, and what docs/native/kits-native.md +//! asks of a module (its imports and exports). + +mod common; + +use std::path::{Path, PathBuf}; + +use serde_json::Value; + +fn kit() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("..") +} + +fn manifest() -> Value { + serde_json::from_str(&std::fs::read_to_string(kit().join("hangar-kit.json")).unwrap()).unwrap() +} + +#[test] +fn the_tab_is_native_under_schema_2() { + let manifest = manifest(); + assert_eq!( + manifest["schema"], 2, + "an entry that is a module needs schema 2" + ); + assert_eq!(manifest["hangar"], ">=2.0.0"); + let tab = &manifest["tabs"][0]; + assert_eq!(tab["entry"], "tabs/editor.wasm"); + assert!(tab.get("native").is_none(), "the entry is the module itself"); + assert!( + !kit().join("tabs/editor").exists(), + "no HTML page is left" + ); + let mut permissions: Vec<&str> = tab["permissions"] + .as_array() + .unwrap() + .iter() + .map(|p| p.as_str().unwrap()) + .collect(); + permissions.sort(); + assert_eq!( + permissions, + common::GRANTED, + "the tab's three, which the tests' Hangar holds the tab to" + ); +} + +fn leb(bytes: &[u8], at: &mut usize) -> u64 { + let (mut value, mut shift) = (0u64, 0); + loop { + let byte = bytes[*at]; + *at += 1; + value |= u64::from(byte & 0x7f) << shift; + if byte & 0x80 == 0 { + return value; + } + shift += 7; + } +} + +fn name(bytes: &[u8], at: &mut usize) -> String { + let len = leb(bytes, at) as usize; + let text = String::from_utf8(bytes[*at..*at + len].to_vec()).unwrap(); + *at += len; + text +} + +/// The module's imports (`module.field`) and exports. +fn imports_and_exports(bytes: &[u8]) -> (Vec, Vec) { + assert_eq!( + &bytes[..8], + b"\0asm\x01\0\0\0", + "a WebAssembly module, version 1" + ); + let (mut imports, mut exports) = (Vec::new(), Vec::new()); + let mut at = 8; + while at < bytes.len() { + let id = bytes[at]; + at += 1; + let size = leb(bytes, &mut at) as usize; + let end = at + size; + let mut i = at; + match id { + 2 => { + for _ in 0..leb(bytes, &mut i) { + let module = name(bytes, &mut i); + let field = name(bytes, &mut i); + imports.push(format!("{module}.{field}")); + match bytes[i] { + 0 => { + i += 1; + leb(bytes, &mut i); + } + kind => panic!("an import of kind {kind}: {module}.{field}"), + } + } + } + 7 => { + for _ in 0..leb(bytes, &mut i) { + exports.push(name(bytes, &mut i)); + i += 1; + leb(bytes, &mut i); + } + } + _ => {} + } + at = end; + } + (imports, exports) +} + +#[test] +fn the_module_imports_only_what_hangar_gives_and_exports_the_abi() { + let path = kit().join("tabs/editor.wasm"); + let bytes = std::fs::read(&path).expect("tabs/editor.wasm: run scripts/build-native.sh"); + assert!( + bytes.len() < 4 * 1024 * 1024, + "a small module: {} bytes", + bytes.len() + ); + let (mut imports, exports) = imports_and_exports(&bytes); + imports.sort(); + for import in &imports { + assert!( + ["hangar.log", "hangar.now"].contains(&import.as_str()), + "no WASI, no glue: {import}" + ); + } + for export in [ + "memory", + "hangar_abi_version", + "hangar_alloc", + "hangar_init", + "hangar_update", + "hangar_view", + ] { + assert!( + exports.iter().any(|other| other == export), + "{export} in {exports:?}" + ); + } +} + +#[test] +fn the_module_names_no_path_of_the_machine_that_built_it() { + let bytes = std::fs::read(kit().join("tabs/editor.wasm")).unwrap(); + let text = String::from_utf8_lossy(&bytes); + for personal in ["/home/", "/Users/", "C:\\Users"] { + assert!( + !text.contains(personal), + "{personal} is in the module: build it with scripts/build-native.sh" + ); + } +} diff --git a/native/tests/no_value_reaches_an_agent.rs b/native/tests/no_value_reaches_an_agent.rs new file mode 100644 index 0000000..575b615 --- /dev/null +++ b/native/tests/no_value_reaches_an_agent.rs @@ -0,0 +1,637 @@ +//! The proof the kit stands on: whatever the file holds, whatever the person +//! types, however the save goes, no value reaches `panes.send`, any other call +//! but the file's own, or the tab's log. Every test drives the tab through its +//! page against a fake Hangar, marks every value with a sentinel, and looks at +//! what left the tab. the HTML tab's Node test of the same name, ported before the page was deleted. + +mod common; + +use std::collections::HashSet; +use std::path::Path; +use std::sync::LazyLock; + +use regex::Regex; + +use common::{CALLER, Fake, Setup, Tab}; +use hangar_kit_sdk::testing; +use hangar_kit_sdk::ui::Element; +use hangar_kit_sdk::ui::abi::Call; +use kit_editor_tab::answer; +use kit_editor_tab::editor::Screen; + +/// A deterministic generator: a failure here can be run again as it is. +struct Random(u32); + +impl Random { + fn next(&mut self) -> u32 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 17; + self.0 ^= self.0 << 5; + self.0 + } + + fn int(&mut self, max: u32) -> u32 { + self.next() % max + } + + fn pick<'a, T>(&mut self, list: &'a [T]) -> &'a T { + &list[self.next() as usize % list.len()] + } +} + +fn base36(mut n: u32) -> String { + let digits = b"0123456789abcdefghijklmnopqrstuvwxyz"; + let mut out = Vec::new(); + loop { + out.push(digits[(n % 36) as usize]); + n /= 36; + if n == 0 { + break; + } + } + out.reverse(); + String::from_utf8(out).unwrap() +} + +/// What every message must look like: fixed sentences, a path, names, +/// counts. Nothing else fits. +static SHAPE: LazyLock = LazyLock::new(|| { + Regex::new(concat!( + r"^The person (?:saved|checked) `[^`\n]+`(?:", + r": the file changed\.|", + r" and changed nothing\.(?: (?:Already set|Still empty): [A-Za-z_][\w.-]*(?:, [A-Za-z_][\w.-]*)*\.)*(?: \d+ other keys? set or empty\.)?(?: The values stay in the file: do not read them back, use them through the program that loads it\.)?|", + r"\.(?: (?:Set|Emptied|Still empty): [A-Za-z_][\w.-]*(?:, [A-Za-z_][\w.-]*)*\.)*(?: \d+ other keys? changed or empty\.)? The values stay in the file: do not read them back, use them through the program that loads it\.", + r")$", + )) + .unwrap() +}); + +/// What left the tab: every call answered, and what it logged. +fn assert_clean(calls: &[Call], logs: &[String], secrets: &[String], label: &str) -> Vec { + let sent: Vec = calls + .iter() + .filter(|call| call.method == "panes.send") + .map(|call| call.params["text"].as_str().unwrap_or("").to_owned()) + .collect(); + for text in &sent { + assert!( + SHAPE.is_match(text), + "{label}: not one of the fixed sentences: {text}" + ); + for secret in secrets { + assert!( + !text.contains(secret.as_str()), + "{label}: a value reached panes.send: {secret} in {text}" + ); + } + } + // Only the file calls may carry a value, and only to the file itself. + for call in calls { + if call.method == "files.write" || call.method == "files.read" { + continue; + } + let seen = call.params.to_string(); + for secret in secrets { + assert!( + !seen.contains(secret.as_str()), + "{label}: {secret} left in {}: {seen}", + call.method + ); + } + } + for line in logs { + for secret in secrets { + assert!( + !line.contains(secret.as_str()), + "{label}: {secret} reached the log: {line}" + ); + } + } + sent +} + +fn clean(tab: &Tab, secrets: &[String], label: &str) -> Vec { + let logs: Vec = testing::take_logs() + .into_iter() + .map(|(_, line)| line) + .collect(); + assert_clean(&tab.fake.calls, &logs, secrets, label) +} + +fn s(n: impl std::fmt::Display) -> String { + format!("s3cr3t-{n}-XqZ9") +} + +/// Every way a value can sit in a dotenv file. +fn hostile(index: usize, v: &str) -> String { + let u = v.replace('-', "_"); + match index { + 0 => format!("PLAIN={v}"), + 1 => format!("export EXPORTED={v}"), + 2 => format!("SPACED = {v}"), + 3 => format!("DOUBLE=\"{v}\""), + 4 => format!("SINGLE='{v}'"), + 5 => format!("TICK=`{v}`"), + 6 => format!("INLINE={v} # also {v}"), + 7 => format!("# COMMENTED={v}"), + 8 => format!("#{v}"), + 9 => v.to_owned(), // a token alone on its line + 10 => format!("MULTI=\"first {v}\nINNER_KEY={v}\nlast\""), + 11 => format!("MULTISINGLE='{v}\nOTHER={v}'"), + 12 => format!("UNCLOSED=\"{v}"), + 13 => format!("DUP={v}"), + 14 => format!("DUP={v}x"), + 15 => format!("COLON: {v}"), + 16 => format!("EQUALS={v}={v}=="), + 17 => format!("A{u}={u}"), // the value is also in the key's name + 18 => format!("{u}={u}"), // a key that is its own value + _ => format!("NOTE=see {u}"), + } +} +const HOSTILE: usize = 20; + +fn rows(tab: &Tab) -> Vec<(String, String)> { + tab.kit() + .form + .as_ref() + .map(|form| { + form.rows + .iter() + .map(|row| (row.key.clone(), row.value.clone())) + .collect() + }) + .unwrap_or_default() +} + +/// Adds a key the person typed, by Enter in its field. +fn add_new_key(tab: &mut Tab, name: &str) { + tab.type_into("KEY_NAME", name); + let submit = tab + .elements() + .into_iter() + .find_map(|element| match element { + Element::TextInput(input) if input.id == "new-key" => input.on_submit, + _ => None, + }) + .unwrap(); + tab.ui(submit, None); +} + +fn offered(tab: &Tab) -> Vec { + tab.kit() + .form + .as_ref() + .map(|form| form.offered.iter().map(|offer| offer.key.clone()).collect()) + .unwrap_or_default() +} + +fn add_all_offered(tab: &mut Tab) { + let keys = offered(tab); + match keys.len() { + 0 => {} + 1 => tab.add_offered(&keys[0]), + _ => tab.press("Add all"), + } +} + +/// Saves when there is something to save, or tells the agent there is not. +fn save_or_tell(tab: &mut Tab) { + if tab.kit().is_dirty() { + tab.press("Save"); + } else if tab + .button("Tell Asker: nothing to change") + .is_some_and(|button| button.on_press.is_some()) + { + tab.press("Tell Asker: nothing to change"); + } +} + +#[test] +fn every_hostile_line_one_by_one_the_answer_holds_no_value() { + for index in 0..HOSTILE { + let secret = s(index); + let text = format!("# head\n{}\nTARGET=old\n", hostile(index, &secret)); + let mut tab = Setup::new() + .path(".env") + .param("keys", "TARGET,NEW_KEY") + .caller(CALLER) + .file(".env", &text) + .ignored() + .open(); + tab.edit_row("TARGET", &format!("{secret}-typed")); + tab.edit_row("NEW_KEY", &format!("{secret}-new")); + for (key, value) in rows(&tab) { + tab.edit_row(&key, &format!("{value}-{secret}")); + } + tab.press("Save"); + let sent = clean( + &tab, + &[secret.clone(), secret.replace('-', "_")], + &format!("line {index}"), + ); + assert_eq!(sent.len(), 1, "line {index}: it answered once"); + } +} + +#[test] +fn random_files_random_edits_400_of_them_the_answer_holds_no_value() { + let mut random = Random(20261031); + let eols = ["\n", "\r\n"]; + let keys = [ + "API_KEY", "DB_URL", "TOKEN", "PORT", "A.B", "x-y", "_z", "DEBUG", + ]; + let mut conflicts = 0; + let mut answers = 0; + for run in 0..400 { + let mut secrets: Vec = Vec::new(); + let secret = |random: &mut Random, secrets: &mut Vec| { + let value = format!( + "v{run}-{}-{}Q", + secrets.len(), + base36(random.int(1_000_000_000)) + ); + secrets.push(value.clone()); + value + }; + let eol = *random.pick(&eols); + let mut lines: Vec = Vec::new(); + for _ in 0..=random.int(12) { + let index = random.int(HOSTILE as u32) as usize; + let value = secret(&mut random, &mut secrets); + lines.push(hostile(index, &value)); + } + for key in keys { + if random.int(2) == 1 { + let at = random.int(lines.len() as u32 + 1) as usize; + let value = secret(&mut random, &mut secrets); + lines.insert(at, format!("{key}={value}")); + } + } + let mut text = lines.join(eol); + if random.int(2) == 1 { + text.push_str(eol); + } + let mut setup = Setup::new() + .path(".env") + .param("why", "for the test") + .caller(CALLER) + .file(".env", &text); + if random.int(2) == 1 { + let (a, b) = ( + secret(&mut random, &mut secrets), + secret(&mut random, &mut secrets), + ); + setup = setup.file( + ".env.example", + &format!("# say what\nFROM_EXAMPLE={a}\nAPI_KEY={b}\n"), + ); + } + if random.int(2) == 1 { + setup = setup.ignored(); + } + let asked: Vec<&str> = keys + .iter() + .copied() + .filter(|_| random.int(3) == 0) + .collect(); + if !asked.is_empty() { + setup = setup.param("keys", &asked.join(",")); + } + let mut tab = setup.open(); + assert_eq!(tab.kit().screen, Screen::Dotenv, "run {run}"); + + for (key, _) in rows(&tab) { + match random.int(4) { + 0 => { + let value = secret(&mut random, &mut secrets); + tab.edit_row(&key, &value); + } + 1 => tab.edit_row(&key, ""), + 2 => { + let (a, b) = ( + secret(&mut random, &mut secrets), + secret(&mut random, &mut secrets), + ); + tab.edit_row(&key, &format!("{a}\n{b}=x")); + } + _ => {} + } + } + if !offered(&tab).is_empty() && random.int(2) == 1 { + add_all_offered(&mut tab); + } + if random.int(4) == 0 { + // The person pastes a secret where the name of a new key goes. + let pasted = format!( + "Pasted_{}", + secret(&mut random, &mut secrets).replace('-', "_") + ); + secrets.push(pasted.clone()); + add_new_key(&mut tab, &pasted); + let value = secret(&mut random, &mut secrets); + tab.edit_row(&pasted, &value); + } + // The file may have moved in the meantime, and the person chooses. + if random.int(4) == 0 { + let moved = secret(&mut random, &mut secrets); + tab.fake + .store + .set(".env", &format!("# moved\nMOVED={moved}\n{text}")); + } + save_or_tell(&mut tab); + if tab.kit().conflict.is_some() { + conflicts += 1; + if random.int(2) == 1 { + tab.press("Save with these choices"); + } else { + tab.press("Keep what is on disk, lose mine"); + } + save_or_tell(&mut tab); + } + answers += clean(&tab, &secrets, &format!("run {run} of {text:?}")).len(); + } + assert!(conflicts > 20, "the fuzz reaches the conflict: {conflicts}"); + assert!(answers > 300, "and answers the agent: {answers}"); +} + +#[test] +fn a_text_file_only_that_it_changed_whatever_it_holds() { + let secret = s("text"); + let files = [ + ("config.json", format!("{{ \"password\": \"{secret}\" }}\n")), + ("values.yaml", format!("password: {secret}\n")), + ("app.toml", format!("password = \"{secret}\"\n")), + ("notes.txt", format!("{secret}\n")), + ]; + for (file, _) in &files { + let mut setup = Setup::new().path(file).caller(CALLER); + for (path, text) in &files { + setup = setup.file(path, text); + } + let mut tab = setup.open(); + let value = tab.kit().text.as_ref().unwrap().value.clone(); + tab.type_into("editor", &format!("{value}# {secret}-typed\n")); + tab.press("Review changes"); + if tab.shows("I know this file is broken: save it anyway.") { + tab.toggle("I know this file is broken: save it anyway.", true); + } + tab.press("Save"); + let sent = clean(&tab, std::slice::from_ref(&secret), file); + assert_eq!( + sent, + [format!("The person saved `{file}`: the file changed.")] + ); + } +} + +#[test] +fn failures_and_retries_carry_no_value_either() { + let secret = s("retry"); + for code in ["not_found", "denied", "unavailable", "rate_limited"] { + let mut tab = Setup::new() + .path(".env") + .param("keys", "A") + .caller(CALLER) + .file(".env", &format!("A={secret}\n")) + .ignored() + .send_error(code) + .open(); + tab.edit_row("A", &format!("{secret}2")); + tab.press("Save"); + assert_eq!( + tab.kit().told.as_ref().unwrap().status, + kit_editor_tab::editor::TellStatus::Failed + ); + tab.fake.send_error = None; + tab.press("Tell Asker again"); + assert_eq!( + tab.kit().told.as_ref().unwrap().status, + kit_editor_tab::editor::TellStatus::Sent + ); + let sent = clean(&tab, std::slice::from_ref(&secret), code); + assert_eq!(sent.len(), 2); + assert_eq!(sent[0], sent[1], "the same message, sent again"); + } +} + +#[test] +fn with_nobody_to_answer_nothing_is_sent() { + let mut tab = Setup::new() + .path(".env") + .file(".env", "A=1\n") + .ignored() + .open(); + tab.edit_row("A", "2"); + tab.press("Save"); + assert!(tab.fake.sent().is_empty()); + assert_eq!(tab.store().get(".env"), Some("A=2\n")); +} + +#[test] +fn the_message_is_made_of_names_what_is_not_a_name_or_is_a_value_stays_unsaid() { + let known: HashSet = [ + "API_KEY", + "hunter2hunter2", + "HAS_hunter2hunter2_IN", + "SHORT", + "Bad Name", + "a=b", + ] + .into_iter() + .map(String::from) + .collect(); + let names = + |list: &[&str]| -> Vec { list.iter().map(|name| name.to_string()).collect() }; + let values = names(&["hunter2hunter2", "x"]); + let text = answer::dotenv_saved( + &answer::Facts { + path: ".env", + known: &known, + values: &values, + }, + &names(&[ + "API_KEY", + "hunter2hunter2", + "HAS_hunter2hunter2_IN", + "NEVER_SEEN", + "Bad Name", + "a=b", + "line\nbreak", + "42", + ]), + &[], + &names(&["SHORT"]), + ); + assert_eq!( + text, + "The person saved `.env`. Set: API_KEY. Still empty: SHORT. 7 other keys changed or empty. The values stay in the file: do not read them back, use them through the program that loads it." + ); + let one = |name: &str| -> HashSet { [name.to_owned()].into_iter().collect() }; + assert!( + answer::may_name("A1", &one("A1"), &names(&["1"])), + "a short value does not silence a name by chance" + ); + assert!( + !answer::may_name("A1", &one("A1"), &names(&["A1"])), + "but a name that is a value does" + ); + let long = "x".repeat(65); + assert!( + !answer::may_name(&long, &one(&long), &[]), + "a name this long reads as a token" + ); +} + +#[test] +fn a_key_the_person_typed_is_counted_never_named() { + let mut tab = Setup::new() + .path(".env") + .param("keys", "A") + .caller(CALLER) + .file(".env", "A=\n") + .ignored() + .open(); + add_new_key(&mut tab, "sk_live_PASTED_BY_MISTAKE"); + tab.edit_row("sk_live_PASTED_BY_MISTAKE", "whatever"); + tab.edit_row("A", "filled"); + tab.press("Save"); + let sent = tab.fake.sent(); + assert!( + sent[0].1.contains("Set: A. 1 other key changed or empty."), + "{}", + sent[0].1 + ); + assert!(!sent[0].1.contains("sk_live")); +} + +#[test] +fn a_long_list_of_keys_stays_a_list_of_names_and_within_what_panes_send_carries() { + let lines: Vec = (0..300).map(|i| format!("KEY_{i}=old{i}")).collect(); + let mut tab = Setup::new() + .path(".env") + .caller(CALLER) + .file(".env", &lines.join("\n")) + .ignored() + .open(); + for (key, _) in rows(&tab) { + tab.edit_row(&key, &format!("new-{key}")); + } + tab.press("Save"); + let sent = clean(&tab, &["new-KEY".to_owned(), "old1".to_owned()], "long"); + assert!(sent[0].contains("260 other keys changed or empty.")); + assert!(sent[0].chars().count() < 20_000); +} + +fn source(name: &str) -> String { + std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("src").join(name)).unwrap() +} + +#[test] +fn in_the_sources_one_panes_send_fed_by_answer_alone_and_no_log() { + let names = [ + "answer.rs", + "diff.rs", + "dotenv.rs", + "editor.rs", + "gitignore.rs", + "js.rs", + "lib.rs", + "logic.rs", + "validate.rs", + "view.rs", + ]; + let mut uses = Vec::new(); + for name in names { + let text = source(name); + uses.extend(text.matches("PanesSend").map(|_| name)); + uses.extend(text.matches("\"panes.send\"").map(|_| name)); + // Nothing is logged: a log line is kept beside a failure. + for logging in [ + "console::", + "sys::log", + "eprintln!", + "println!", + "dbg!", + "call_raw", + ] { + assert!(!text.contains(logging), "{name} uses {logging}"); + } + } + assert_eq!(uses, ["editor.rs"], "panes.send is called from one place"); + let editor = source("editor.rs"); + assert!(editor.contains("api::PanesSend {\n pane: pane.clone(),\n text: message,\n }")); + // Each `send(` is given what answer made, or the message already made for it. + let senders = Regex::new(r"self\.send\(([^,]+),").unwrap(); + let mut count = 0; + for found in senders.captures_iter(&editor) { + let first = found[1].trim(); + assert!( + first == "message" || first.starts_with("answer::"), + "send({first}, …)" + ); + count += 1; + } + assert_eq!(count, 4); + for made in [ + "let message = answer::dotenv_saved(", + "answer::dotenv_checked(", + "let Some((message, status)) = self.unsent.clone()", + ] { + assert!(editor.contains(made), "{made}"); + } + // And answer takes no field that could carry a value but `values`, used only to stay silent. + let speech = source("answer.rs"); + assert!( + !speech.contains("{values"), + "a value formatted into a sentence" + ); + assert!( + !Regex::new(r"\.value\b").unwrap().is_match(&speech), + "a value read in answer" + ); +} + +#[test] +fn the_fuzz_would_catch_a_leak_a_value_in_the_message_fails_the_checks() { + // Guards the checks themselves: a broken answer must not slip past `assert_clean`. + let leak = s("leak"); + let call = |method: &str, params: serde_json::Value| Call { + id: 1, + method: method.to_owned(), + params, + }; + let planted = |calls: Vec, logs: Vec, secret: String| { + std::panic::catch_unwind(move || assert_clean(&calls, &logs, &[secret], "planted")).is_err() + }; + let stay = "The values stay in the file: do not read them back, use them through the program that loads it."; + assert!(planted( + vec![call( + "panes.send", + serde_json::json!({ "pane": "Asker", "text": format!("The person saved `.env`. Set: API_KEY={leak}. {stay}") }) + )], + vec![], + leak.clone() + )); + let named = leak.replace('-', "_"); + assert!(planted( + vec![call( + "panes.send", + serde_json::json!({ "pane": "Asker", "text": format!("The person saved `.env`. Set: {named}. {stay}") }) + )], + vec![], + named.clone() + )); + assert!(planted( + vec![call( + "tab.setBadge", + serde_json::json!({ "state": "neutral", "text": leak }) + )], + vec![], + leak.clone() + )); + assert!( + planted(vec![], vec![format!("files.write: {leak}")], leak.clone()), + "a log line too" + ); + let _ = Fake::default(); +} diff --git a/native/tests/validate.rs b/native/tests/validate.rs new file mode 100644 index 0000000..760b1ae --- /dev/null +++ b/native/tests/validate.rs @@ -0,0 +1,452 @@ +//! JSON's answer is the grammar's. YAML is scanned and TOML parsed for what is +//! certainly wrong, so the first thing checked is that valid files, full of +//! traps, pass. the HTML tab's Node test of the same name, ported before the page was deleted. + +use std::path::Path; + +use kit_editor_tab::validate::{self, Check, Checker}; + +fn valid(kind: Checker, partial: bool) -> Check { + Check { + kind: Some(kind), + ok: true, + partial, + code: None, + line: None, + column: None, + } +} + +#[test] +fn which_check_applies() { + let table: &[(&str, Option)] = &[ + ("a.json", Some(Checker::Json)), + ("pkg/package.json", Some(Checker::Json)), + ("b.JSON", Some(Checker::Json)), + ("tsconfig.json", Some(Checker::Jsonc)), + ("tsconfig.app.json", Some(Checker::Jsonc)), + (".vscode/settings.json", Some(Checker::Jsonc)), + ("c.jsonc", Some(Checker::Jsonc)), + ("w.code-workspace", Some(Checker::Jsonc)), + ("a.yaml", Some(Checker::Yaml)), + ("a.yml", Some(Checker::Yaml)), + ("a.toml", Some(Checker::Toml)), + ("Cargo.toml", Some(Checker::Toml)), + ("a.txt", None), + ("a.ini", None), + ("a.json5", None), + ("Dockerfile", None), + ]; + for (path, kind) in table { + assert_eq!(validate::checker_for(path), *kind, "{path}"); + } +} + +#[test] +fn json_what_the_grammar_says_with_a_line() { + assert_eq!( + validate::validate("a.json", "{\"a\": [1, 2]}"), + valid(Checker::Json, false) + ); + let bad = validate::validate("a.json", "{\n \"a\": 1,\n \"b\": \n}\n"); + assert!(!bad.ok); + assert!(!bad.partial); + assert_eq!(bad.code, Some("json")); + assert_eq!(bad.line, Some(4)); + assert!( + !validate::validate("a.json", "").ok, + "an empty file is no JSON" + ); + assert!(!validate::validate("a.json", "{\"a\": 1} // no").ok); + assert!(!validate::validate("a.json", "{\"a\": 1,}").ok); +} + +#[test] +fn json_where_it_goes_wrong_is_found_and_agrees_with_json_parse_on_what_is_wrong() { + let cases: &[(&str, usize, usize)] = &[ + ("{\"a\": 1,}", 1, 9), + ("[1, 2\n", 2, 1), + ("{\n\"a\" 1}", 2, 5), + ("{\"a\": tru}", 1, 7), + ("\"\\q\"", 1, 2), + ("\"new\nline\"", 1, 5), + ("1 2", 1, 3), + ("{\"a\":01}", 1, 7), + ("[1,\n2,\n,3]", 3, 1), + ("nul", 1, 1), + ]; + for (text, line, column) in cases { + assert!( + serde_json::from_str::(text).is_err(), + "{text}" + ); + let result = validate::validate("a.json", text); + assert!(!result.ok, "{text}"); + assert_eq!( + (result.line, result.column), + (Some(*line), Some(*column)), + "{text}" + ); + } + for text in [ + "\"\\u00e9 \\\" \\n\"", + "[[], {}, [{\"a\": [null, true, false, -1.5e+3, 0]}]]", + " \n 1 \n", + ] { + assert!(validate::validate("a.json", text).ok, "{text}"); + } + assert!( + !validate::validate("a.json", &"[".repeat(200_000)).ok, + "too deep is still not valid" + ); + let deep = format!("{}{}", "[".repeat(200_000), "]".repeat(200_000)); + assert!( + validate::validate("a.json", &deep).ok, + "and as deep as it goes, valid is valid" + ); +} + +#[test] +fn json_agrees_with_a_parser_on_many_texts() { + let pieces = [ + "{", + "}", + "[", + "]", + ",", + ":", + "\"a\"", + "1", + "-0.5e3", + "true", + "null", + " ", + "\n", + "\"\\u12\"", + "01", + "é", + ]; + let mut seed: u32 = 99; + for _ in 0..5000 { + let mut text = String::new(); + for _ in 0..(seed % 12) { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + text.push_str(pieces[(seed as usize) % pieces.len()]); + } + let parsed = serde_json::from_str::(&text).is_ok(); + assert_eq!(validate::validate("a.json", &text).ok, parsed, "{text:?}"); + } +} + +#[test] +fn jsonc_comments_and_trailing_commas_are_fine_and_strings_are_left_alone() { + let good = "// head\n{\n /* block\n over lines */\n \"url\": \"http://x.y/*z*/\", // tail\n \"list\": [1, 2,],\n \"o\": { \"a\": \"// not, a comment\", },\n}\n"; + assert!(validate::validate("tsconfig.json", good).ok); + assert!(validate::validate(".vscode/settings.json", good).ok); + assert!( + !validate::validate("a.json", good).ok, + "plain JSON has neither" + ); + let bad = validate::validate("c.jsonc", "{\n // fine\n \"a\": 1\n \"b\": 2\n}\n"); + assert!(!bad.ok); + assert_eq!(bad.line, Some(4), "the lines are still the file's"); + assert!(validate::validate("c.jsonc", "{\"a\": \",\", }").ok); + assert!( + !validate::validate("c.jsonc", "[1,,]").ok, + "only the last comma goes" + ); +} + +const GOOD_YAML: &[(&str, &str)] = &[ + ( + "workflow", + "name: CI +on: + push: + branches: [main, \"release/**\"] +env: { A: 1, B: \"x,y\" } +jobs: + build: + runs-on: ${{ matrix.os }} + if: github.event_name == 'push' && contains(x, 'y') + steps: + - uses: actions/checkout@v4 + - name: Say \"hi\" # a comment with a ' quote and a [ bracket + run: | + echo \"unterminated + it's [fine { here + \ttab inside a block scalar + - run: >- + folded 'text + env: + X: 'it''s' + Y: \"a \\\" b\" +", + ), + ( + "plain", + "key: it's fine +other: a \"quoted\" word +url: http://x.y:80/a#b +time: 12:30:00 +list: +- a +- b: c + d: [e, {f: g}] +- 'single' +- \"double\" +- - nested + - more +empty: +tilde: ~ +glob: \"*.js\" +star: *anchor +amp: &anchor value +tagged: !!str \"text\" +tagged2: !custom [a, b] +? complex key +: complex value +", + ), + ( + "documents", + "%YAML 1.2 +--- +a: 1 +... +--- # second +b: 2 +--- | + text with 'a quote +--- \"quoted\" +", + ), + ( + "multiline", + "a: \"first line + second 'line\" +b: 'first + second \"line' +c: [1, + 2, +\t3] +d: { + e: f +} +plain: this goes on + 'over several lines + and \"another +next: 1 +", + ), + ( + "jsonish", + "{\"a\": 1, \"b\": [true, null], \"c\": {\"d\": \"e\"}}\n", + ), + ("tabs", "a: 1\n\t\n \t# a comment after a tab\nb: 2 \t\n"), + ("empty", ""), + ("crlf", "a: 1\r\nb:\r\n - c\r\n"), +]; + +#[test] +fn valid_yaml_passes() { + for (name, text) in GOOD_YAML { + assert_eq!( + validate::validate("a.yaml", text), + valid(Checker::Yaml, true), + "{name}" + ); + } +} + +#[test] +fn broken_yaml_what_is_certainly_wrong_with_its_line() { + let cases: &[(&str, &str, usize)] = &[ + ("a: 1\n\tb: 2\n", "yaml-tab", 2), + ("a:\n - b\n \t- c\n", "yaml-tab", 3), + ("a: \"never closed\nb: 2\n", "yaml-quote", 1), + ("a: 1\nb: 'never closed\n", "yaml-quote", 2), + ("a: [1, 2\nb: 3\n", "yaml-bracket", 1), + ("a: {b: 1]\n", "yaml-bracket", 1), + ("a: ]\n", "yaml-bracket", 1), + ("a: @scope/pkg\n", "yaml-reserved", 1), + ("a: `tick`\n", "yaml-reserved", 1), + ]; + for (text, code, line) in cases { + let result = validate::validate("a.yml", text); + assert!(!result.ok, "{text:?}"); + assert_eq!(result.code, Some(*code), "{text:?}"); + assert_eq!(result.line, Some(*line), "{text:?}"); + assert!(result.partial); + } +} + +const GOOD_TOML: &[(&str, &str)] = &[ + ( + "everything", + "# comment +title = \"TOML\" # trailing +\"quoted key\" = 1 +'lit key' = 2 +a.b.c = 3 +d . e = 4 +bare-key_1 = true +no = false +int = +1_000 +hex = 0xDEAD_beef +oct = 0o755 +bin = 0b1010 +float = 6.626e-34 +inf = -inf +nan = nan +date = 1979-05-27 +dt = 1979-05-27T07:32:00Z +dt2 = 1979-05-27 07:32:00.5-07:00 +time = 07:32:00 +str = \"esc \\\" \\\\ \\t \\u00E9 \\U0001F600\" +lit = 'C:\\no\\escape' +multi = \"\"\" +line \\ + joined \"quotes\" \"\" +\"\"\" +multi2 = ''' +raw 'x' '' +''' +arr = [1, 2, 3,] +arr2 = [ + \"a\", # comment + [1, 2], + + { x = 1, y = \"z\" }, +] +empty = [] +inline = { a = 1, b.c = 2 } +none = {} + +[table] +x = 1 + +[table.sub] +x = 2 + +[ spaced . \"name\" ] +x = 3 + +[[items]] +name = \"one\" + +[[items]] +name = \"two\" + +[other] +x = 4 +", + ), + ("crlf", "a = 1\r\n# c\r\n[b]\r\nc = \"d\"\r\n"), + ("empty", ""), + ("no final newline", "a = 1"), +]; + +#[test] +fn valid_toml_passes() { + for (name, text) in GOOD_TOML { + assert_eq!( + validate::validate("a.toml", text), + valid(Checker::Toml, true), + "{name}" + ); + } +} + +#[test] +fn broken_toml_with_its_line() { + let cases: &[(&str, &str, usize)] = &[ + ("a = \n", "toml-value", 1), + ("ok = 1\nb\n", "toml-equals", 2), + ("a = 1 2\n", "toml-trailing", 1), + ("a = \"open\n", "toml-string", 1), + ("ok = 1\nb = \"bad \\q\"\n", "toml-escape", 2), + ("= 1\n", "toml-key", 1), + ("[table\nb = 1\n", "toml-header", 1), + ("[[table]\n", "toml-header", 1), + ("a = 1\na = 2\n", "toml-duplicate", 2), + ("[t]\nx = 1\n[t]\ny = 2\n", "toml-duplicate", 3), + ("[t]\nx = 1\nx = 2\n", "toml-duplicate", 3), + ("a = [1, 2\n", "toml-value", 1), + ("a = { b = 1,\n}\n", "toml-key", 1), + ("a = nope\n", "toml-value", 1), + ("a = 01\n", "toml-value", 1), + ("a = 1_\n", "toml-value", 1), + ("a = truex\n", "toml-value", 1), + ("a = '''open\n", "toml-string", 1), + ]; + for (text, code, line) in cases { + let result = validate::validate("a.toml", text); + assert!(!result.ok, "{text:?}"); + assert_eq!(result.code, Some(*code), "{text:?}"); + assert_eq!(result.line, Some(*line), "{text:?}"); + } +} + +#[test] +fn the_same_key_in_two_tables_or_two_items_is_no_duplicate() { + assert!(validate::validate("a.toml", "[a]\nx = 1\n[b]\nx = 2\n").ok); + assert!(validate::validate("a.toml", "[[a]]\nx = 1\n[[a]]\nx = 2\n").ok); +} + +#[test] +fn the_repositorys_own_files_pass_when_they_are_around() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join(".."); + for sample in [ + ".github/workflows/ci.yml", + ".github/repo.json", + "hangar-kit.json", + "package.json", + "native/Cargo.toml", + ] { + let file = root.join(sample); + let Ok(text) = std::fs::read_to_string(&file) else { + continue; + }; + let result = validate::validate(sample, &text); + assert!(result.ok, "{sample}: {result:?}"); + } +} + +#[test] +fn no_check_for_other_files_nothing_can_be_said_so_nothing_is_claimed() { + assert_eq!( + validate::validate("a.txt", "whatever {{{"), + Check { + kind: None, + ok: true, + partial: false, + code: None, + line: None, + column: None, + } + ); +} + +#[test] +fn no_text_makes_a_check_panic() { + let pieces = [ + "\"", "'", "\\", "[", "]", "{", "}", "=", ":", "#", " ", "\t", "\n", "\r", "é", "😀", "a", + "1", "-", ".", "'''", "\"\"\"", + ]; + let mut seed: u32 = 3; + for _ in 0..4000 { + let mut text = String::new(); + for _ in 0..(seed % 20) { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + text.push_str(pieces[(seed as usize) % pieces.len()]); + } + for path in ["a.json", "a.jsonc", "a.yaml", "a.toml"] { + let _ = validate::validate(path, &text); + } + } +} diff --git a/native/tests/view.rs b/native/tests/view.rs new file mode 100644 index 0000000..6fde4a1 --- /dev/null +++ b/native/tests/view.rs @@ -0,0 +1,682 @@ +//! What the page draws for each state: values dotted until revealed, text +//! never read as markup, both languages, one primary action. +//! the HTML tab's Node test of the same name, ported before the page was deleted. + +mod common; + +use std::path::Path; + +use common::{CALLER, Setup, Tab}; +use hangar_kit_sdk::ui::{Element, EmptyKind, LineKind, Notice}; +use kit_editor_tab::editor::{ConflictKind, Screen, Side, Stage}; +use kit_editor_tab::logic::{EN, FR}; +use kit_editor_tab::view::MASK; + +const SECRET: &str = "s3cr3t-value-XqZ9"; + +fn holding(tab: &Tab, needle: &str) -> Vec<(String, String)> { + tab.strings() + .into_iter() + .filter(|(_, text)| text.contains(needle)) + .collect() +} + +#[test] +fn a_value_is_masked_until_its_row_is_revealed_and_shows_nowhere_else() { + let mut tab = Setup::new() + .path(".env") + .file( + ".env", + &format!("# about it\nAPI_KEY={SECRET}\n# OLD={SECRET}\n"), + ) + .ignored() + .open(); + let Some(Element::TextInput(input)) = tab.value_field("API_KEY") else { + panic!("a one-line field"); + }; + assert!(input.secure, "dotted"); + assert_eq!( + input.value, SECRET, + "the field holds it, and Hangar dots it" + ); + assert!(!tab.text().contains(SECRET), "no text of the page holds it"); + assert_eq!( + holding(&tab, SECRET), + [("value".to_owned(), SECRET.to_owned())], + "only that field's value, not a title, a hint or a comment" + ); + + tab.toggle_reveal("API_KEY"); + let Some(Element::TextInput(input)) = tab.value_field("API_KEY") else { + panic!("a one-line field"); + }; + assert!(!input.secure); + assert!(tab.row("API_KEY").revealed); +} + +#[test] +fn a_value_over_several_lines_stays_hidden_and_is_edited_whole_once_shown() { + let mut tab = Setup::new() + .path(".env") + .file(".env", &format!("KEY='first\n{SECRET}'\n")) + .ignored() + .open(); + let Some(Element::TextInput(hidden)) = tab.value_field("KEY") else { + panic!("a one-line field stands in"); + }; + assert!(hidden.on_input.is_none(), "nothing to type in"); + assert!(hidden.secure); + assert_eq!( + hidden.value, "", + "a one-line field would drop its line breaks" + ); + assert_eq!(hidden.placeholder, "Several lines"); + assert!(holding(&tab, SECRET).is_empty()); + + tab.toggle_reveal("KEY"); + let Some(Element::TextArea(area)) = tab.value_field("KEY") else { + panic!("a text area once shown"); + }; + assert_eq!(area.value, format!("first\n{SECRET}")); + assert!(area.on_input.is_some()); +} + +#[test] +fn asked_keys_come_first_with_their_state_then_the_files_and_why_at_the_top() { + let tab = Setup::new() + .path("sub/.env") + .param("keys", "MISSING,DONE") + .param("why", "For the tests.") + .caller(CALLER) + .file("sub/.env", "OTHER=1\nDONE=x\n") + .file("sub/.env.example", "# Offer hint\nOFFERED=y\n") + .ignored() + .open(); + let banner = tab + .elements() + .into_iter() + .find_map(|element| match element { + Element::Banner(banner) if banner.title.is_some() => Some(banner), + _ => None, + }) + .expect("the request"); + assert_eq!(banner.title.as_deref(), Some("Asker asks:")); + assert_eq!( + banner.text, "For the tests.", + "shown as written, not as markup" + ); + assert_eq!(tab.title(), ".env"); + let state = tab.header_state(); + assert!( + state.contains("1 missing") && state.contains("sub/"), + "{state}" + ); + assert_eq!( + tab.sections(), + [ + "Asked for", + "In this file", + "In .env.example, missing here", + "Add a key" + ] + ); + let titles: Vec = tab + .elements() + .into_iter() + .filter_map(|element| match element { + Element::List(list) => Some(list.items.into_iter().map(|item| item.title)), + _ => None, + }) + .flatten() + .collect(); + assert_eq!(titles, ["MISSING", "DONE", "OTHER", "OFFERED"]); + assert!(tab.shows("Offer hint")); + let states: Vec = tab + .elements() + .into_iter() + .filter_map(|element| match element { + Element::State(state) => Some(state.label), + _ => None, + }) + .collect(); + assert_eq!(states.iter().filter(|label| *label == "missing").count(), 1); + assert_eq!(states.iter().filter(|label| *label == "set").count(), 1); +} + +#[test] +fn the_warning_says_it_plainly_and_the_button_is_what_writes() { + let mut tab = Setup::new() + .path(".env") + .file(".env", "A=1\n") + .file(".gitignore", "x\n") + .open(); + assert!(tab.shows(".env is not ignored by git: git would commit it, secrets included.")); + let warnings = |tab: &Tab| { + tab.elements() + .into_iter() + .filter(|element| matches!(element, Element::Banner(banner) if banner.kind == Notice::Warning)) + .count() + }; + assert_eq!(warnings(&tab), 1); + assert!(tab.fake.writes().is_empty()); + tab.press("Add .env to .gitignore"); + assert_eq!(tab.store().get(".gitignore"), Some("x\n.env\n")); + assert_eq!(warnings(&tab), 0); +} + +#[test] +fn typing_refreshes_what_depends_on_it_and_leaves_the_field_alone() { + let mut tab = Setup::new() + .path(".env") + .param("keys", "A") + .file(".env", "A=\n") + .ignored() + .open(); + assert!(!tab.enabled("Save"), "nothing to save"); + assert_eq!( + tab.button("Save").unwrap().tooltip.as_deref(), + Some("Nothing to save yet.") + ); + assert!(tab.header_state().contains("1 missing")); + tab.edit_row("A", "typed"); + assert!( + matches!(tab.value_field("A"), Some(Element::TextInput(input)) if input.id == "value:A"), + "the same field: its caret stays" + ); + assert!(tab.enabled("Save")); + assert!(!tab.header_state().contains("missing")); + assert!( + tab.elements() + .iter() + .any(|element| matches!(element, Element::Chip(chip) if chip.label == "changed")) + ); + tab.press("Save"); + assert!(tab.kit().saved); + assert!(tab.header_state().contains("Saved")); +} + +#[test] +fn one_primary_action_at_a_time_save_or_tell_the_agent_there_is_nothing_to_change() { + let mut tab = Setup::new() + .path(".env") + .caller(CALLER) + .file(".env", "A=1\n") + .ignored() + .open(); + assert_eq!(tab.primaries(), ["Tell Asker: nothing to change"]); + tab.edit_row("A", "2"); + assert_eq!(tab.primaries(), ["Save"]); + tab.press("Save"); + assert!(tab.shows("Asker was told, without any value.")); + assert!(!tab.shows("nothing to change")); +} + +#[test] +fn with_keys_still_missing_save_stays_the_primary_action() { + let tab = Setup::new() + .path(".env") + .param("keys", "A") + .caller(CALLER) + .file(".env", "") + .ignored() + .open(); + assert_eq!(tab.primaries(), ["Save"]); + assert!( + tab.button("Tell Asker: nothing to change").is_some(), + "the lesser choice is there too" + ); +} + +#[test] +fn an_agent_that_could_not_be_told_is_said_with_a_way_to_try_again() { + let mut tab = Setup::new() + .path(".env") + .caller(CALLER) + .file(".env", "A=1\n") + .ignored() + .send_error("not_found") + .open(); + tab.edit_row("A", "2"); + tab.press("Save"); + assert!(tab.shows("Saved, but Asker could not be told: that pane is gone. No value was sent.")); + tab.fake.send_error = None; + tab.press("Tell Asker again"); + assert!(tab.shows("Asker was told")); +} + +#[test] +fn the_editor_line_numbers_the_line_asked_for_marked_and_the_check_above_it() { + let body: Vec = (0..12).map(|i| format!("\"k{i}\": {i},")).collect(); + let mut tab = Setup::new() + .path("conf.json") + .param("line", "5") + .param("why", "Check the timeout.") + .file("conf.json", &format!("{{\n{}\n}}\n", body.join("\n"))) + .open(); + let area = |tab: &Tab| { + tab.elements() + .into_iter() + .find_map(|element| match element { + Element::TextArea(area) if area.id == "editor" => Some(area), + _ => None, + }) + .expect("the editor") + }; + let editor = area(&tab); + assert!(editor.line_numbers); + assert!(editor.fill); + let marks: Vec<(u32, Notice)> = editor + .marks + .iter() + .map(|mark| (mark.line, mark.kind)) + .collect(); + assert!(marks.contains(&(5, Notice::Info)), "{marks:?}"); + assert!( + marks.iter().any(|(_, kind)| *kind == Notice::Error), + "the broken line too: {marks:?}" + ); + assert_eq!( + tab.cursor_moves(), + [(5, 1)], + "scrolled to it, the keyboard left where it was" + ); + assert!( + tab.header_state().starts_with("Broken JSON, line "), + "{}", + tab.header_state() + ); + assert!(tab.shows("Check the timeout.")); + assert!(tab.shows("JSON cannot be read past this point.")); + + tab.type_into("editor", "{\"a\": 1}\n"); + assert!(tab.header_state().contains("Valid JSON")); + assert_eq!( + area(&tab) + .marks + .iter() + .map(|mark| mark.line) + .collect::>(), + [5], + "the error is gone" + ); + assert!(tab.kit().is_dirty()); +} + +#[test] +fn the_review_signs_as_well_as_colours_then_a_broken_file_asks() { + let mut tab = Setup::new() + .path("a.json") + .file("a.json", "{\"a\": 1}\n") + .open(); + tab.type_into("editor", "{\"a\": 2,}\n"); + tab.press("Review changes"); + let lines: Vec<(String, LineKind)> = tab + .elements() + .into_iter() + .find_map(|element| match element { + Element::Log(log) if log.id == "diff" => Some( + log.lines + .into_iter() + .map(|line| (line.text, line.kind)) + .collect(), + ), + _ => None, + }) + .expect("the diff"); + assert!( + lines.contains(&("− {\"a\": 1}".to_owned(), LineKind::Removed)), + "{lines:?}" + ); + assert!( + lines.contains(&("+ {\"a\": 2,}".to_owned(), LineKind::Added)), + "{lines:?}" + ); + assert!(!tab.enabled("Save"), "broken, and not said so"); + assert!(tab.shows("I know this file is broken: save it anyway.")); + tab.toggle("I know this file is broken: save it anyway.", true); + assert!(tab.enabled("Save")); + tab.press("Save"); + assert_eq!(tab.store().get("a.json"), Some("{\"a\": 2,}\n")); + assert_eq!(tab.kit().text.as_ref().unwrap().stage, Stage::Edit); +} + +#[test] +fn a_long_diff_is_given_in_parts() { + let before: Vec = (0..3000).map(|i| format!("a{i}")).collect(); + let mut tab = Setup::new() + .path("big.txt") + .file("big.txt", &before.join("\n")) + .open(); + let after: Vec = (0..3000).map(|i| format!("b{i}")).collect(); + tab.type_into("editor", &after.join("\n")); + tab.press("Review changes"); + let log = |tab: &Tab| { + tab.elements() + .into_iter() + .find_map(|element| match element { + Element::Log(log) if log.id == "diff" => Some(log), + _ => None, + }) + .unwrap() + }; + let first = log(&tab); + assert_eq!(first.total, Some(6000)); + assert_eq!((first.first, first.lines.len()), (0, 400)); + tab.harness.range("diff", 5000, 5100); + tab.settle(); + let later = log(&tab); + assert_eq!(later.first, 5000); + assert!( + later.lines[0].text.starts_with("+ b"), + "{}", + later.lines[0].text + ); +} + +#[test] +fn the_text_conflict_shows_both_sides_and_three_ways_out() { + let mut tab = Setup::new().path("a.txt").file("a.txt", "base\n").open(); + tab.type_into("editor", "mine\n"); + tab.press("Review changes"); + tab.fake.store.set("a.txt", "theirs\n"); + tab.press("Save"); + assert!(tab.shows("This file changed while you were editing it. Nothing was written.")); + assert!(tab.shows("− theirs")); + assert!(tab.shows("+ mine")); + assert!(tab.header_state().contains("Changed on disk")); + for way in [ + "Replace it with mine", + "Keep what is on disk, lose mine", + "Back to editing, with mine", + ] { + assert!(tab.enabled(way), "{way}"); + } + tab.press("Keep what is on disk, lose mine"); + assert_eq!(tab.kit().text.as_ref().unwrap().value, "theirs\n"); + assert!(tab.button("Replace it with mine").is_none()); +} + +#[test] +fn the_dotenv_conflict_keeps_values_hidden_until_asked_on_both_sides() { + let mut tab = Setup::new() + .path(".env") + .file(".env", "A=1\n") + .ignored() + .open(); + tab.edit_row("A", &format!("{SECRET}-mine")); + tab.fake + .store + .set(".env", &format!("A={SECRET}-theirs\nB=2\n")); + tab.press("Save"); + assert!(holding(&tab, SECRET).is_empty(), "both dotted"); + let (labels, chosen) = tab.sides("A"); + assert_eq!( + labels, + [format!("Yours {MASK}"), format!("On disk {MASK}")] + ); + assert_eq!(chosen.as_deref(), Some("mine")); + assert!(tab.shows("1 other key changed on disk")); + + tab.toggle_reveal("A"); + let (labels, _) = tab.sides("A"); + assert_eq!( + labels, + [ + format!("Yours {SECRET}-mine"), + format!("On disk {SECRET}-theirs") + ] + ); + tab.choose_side("A", "theirs"); + let ConflictKind::Dotenv { rows, .. } = &tab.kit().conflict.as_ref().unwrap().kind else { + panic!("a dotenv conflict"); + }; + assert_eq!(rows[0].choice, Side::Theirs); + tab.press("Save with these choices"); + assert_eq!( + tab.store().get(".env"), + Some(format!("A={SECRET}-theirs\nB=2\n").as_str()) + ); +} + +#[test] +fn the_picker_groups_filters_as_you_type_and_opens_what_is_clicked() { + let mut tab = Setup::new() + .files(&[ + (".env.local", "A=1\n"), + ("app.yaml", "a: 1\n"), + ("src/x.ts", ""), + (".gitignore", ".env.local\n"), + ]) + .open(); + assert_eq!( + tab.sections(), + ["Environment files", "Configuration files", "Other files"] + ); + assert!(tab.shows("new"), ".env is offered though it is not there"); + tab.type_into("Filter by name", "app"); + assert_eq!(tab.sections(), ["Configuration files"]); + tab.type_into("Filter by name", "nothing like it"); + assert!(tab.shows("No file matches.")); + tab.type_into("Filter by name", ""); + tab.press(".env.local"); + assert_eq!(tab.kit().screen, Screen::Dotenv); + assert!(tab.button("← Files").is_some()); +} + +#[test] +fn back_with_edits_asks_in_place_without_one_it_just_goes() { + let opened = |answer: bool| { + let mut tab = Setup::new().file("a.txt", "x\n").confirm(answer).open(); + tab.press("a.txt"); + tab + }; + let mut stay = opened(false); + stay.type_into("editor", "changed\n"); + stay.press("← Files"); + let asked = stay.fake.calls_to("ui.confirm"); + assert_eq!(asked.len(), 1); + assert_eq!(asked[0].params["message"], "Your changes are not saved."); + assert_eq!(asked[0].params["confirm"], "Lose them"); + assert_eq!(asked[0].params["cancel"], "Keep editing"); + assert_eq!(stay.kit().screen, Screen::Text); + assert_eq!(stay.kit().text.as_ref().unwrap().value, "changed\n"); + + let mut leave = opened(true); + leave.type_into("editor", "changed\n"); + leave.press("← Files"); + assert_eq!(leave.kit().screen, Screen::Picker); + + let mut clean = opened(false); + clean.press("← Files"); + assert_eq!(clean.kit().screen, Screen::Picker); + assert!(clean.fake.calls_to("ui.confirm").is_empty()); +} + +#[test] +fn denied_and_failed_are_designed_states_each_saying_what_to_do() { + let denied = Setup::new().path(".env").deny("files.read").open(); + assert!(denied.shows("This tab may not read or write here")); + assert!(denied.shows("Accept files.read and files.write")); + let kinds: Vec = denied + .elements() + .into_iter() + .filter_map(|element| match element { + Element::Empty(empty) => Some(empty.kind), + _ => None, + }) + .collect(); + assert_eq!(kinds, [EmptyKind::Denied], "drawn with its lock"); + assert!(denied.button("Try again").is_some()); + + let mut bad = Setup::new().path("../x").open(); + assert!(bad.shows("This path cannot be opened")); + assert!( + bad.button("Try again").is_none(), + "trying again would change nothing" + ); + bad.press("Choose a file"); + assert_eq!(bad.kit().screen, Screen::Picker, "the picker is the way on"); + + let failed = Setup::new() + .path("big.txt") + .read_error("big.txt", "failed", "big.txt is larger than 1 MB") + .open(); + assert!(failed.shows("This file cannot be opened")); + assert!( + failed.shows("big.txt is larger than 1 MB"), + "what Hangar said" + ); +} + +#[test] +fn loading_is_a_state_too() { + let tab = hangar_kit_sdk::testing::Harness::::new( + hangar_kit_sdk::testing::start(), + ); + assert!(tab.shows("Loading…")); +} + +#[test] +fn in_french_with_accents() { + let mut tab = Setup::new() + .locale("fr") + .path(".env") + .param("keys", "A,B") + .caller(CALLER) + .file(".env", "C=1\n") + .file(".gitignore", "x\n") + .open(); + let text = tab.text(); + assert!(text.contains("Dans ce fichier")); + assert!(text.contains("Demandées")); + assert!(text.contains("manquante")); + assert!(text.contains("n'est pas ignoré par git")); + tab.edit_row("A", "x"); + assert!(tab.shows("Enregistrer")); + assert!( + tab.elements() + .iter() + .any(|element| matches!(element, Element::Chip(chip) if chip.label == "modifiée")) + ); + assert_eq!(tab.fake.last_badge()["text"], "1 à remplir"); +} + +fn sources() -> Vec<(String, String)> { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + let mut files: Vec<(String, String)> = std::fs::read_dir(&dir) + .unwrap() + .map(|entry| entry.unwrap().path()) + .filter(|path| path.extension().is_some_and(|ext| ext == "rs")) + .map(|path| { + ( + path.file_name().unwrap().to_string_lossy().into_owned(), + std::fs::read_to_string(&path).unwrap(), + ) + }) + .collect(); + files.sort(); + files +} + +#[test] +fn every_word_the_page_says_exists_in_both_languages() { + let mut en: Vec<&str> = EN.iter().map(|(key, _)| *key).collect(); + let mut fr: Vec<&str> = FR.iter().map(|(key, _)| *key).collect(); + en.sort(); + fr.sort(); + assert_eq!(en, fr); + let accents = |text: &str| { + text.chars() + .any(|c| "àâçéèêëîïôûùüœÀÂÇÉÈÊËÎÏÔÛÙÜŒ".contains(c)) + }; + assert!( + FR.iter().filter(|(_, text)| accents(text)).count() > 60, + "written with its accents" + ); + let known = |key: &str| { + EN.iter() + .any(|(other, _)| *other == key || *other == format!("{key}_one")) + }; + let mut used = 0; + for (file, source) in sources() { + for call in [".t(\"", ".tv(\"", ".tn(\""] { + for (at, _) in source.match_indices(call) { + let rest = &source[at + call.len()..]; + let key: String = rest.chars().take_while(|c| *c != '"').collect(); + assert!(known(&key), "{file}: {key}"); + used += 1; + } + } + } + assert!(used > 80, "the scan finds the words: {used}"); + for code in [ + "json", + "yaml-tab", + "yaml-quote", + "yaml-bracket", + "yaml-reserved", + "toml-trailing", + "toml-string", + "toml-escape", + "toml-key", + "toml-equals", + "toml-value", + "toml-header", + "toml-duplicate", + ] { + assert!(known(&format!("check.{code}")), "{code}"); + } + let validate = sources() + .into_iter() + .find(|(file, _)| file == "validate.rs") + .unwrap() + .1; + for prefix in ["\"yaml-", "\"toml-"] { + for (at, _) in validate.match_indices(prefix) { + let code: String = validate[at + 1..] + .chars() + .take_while(|c| *c != '"') + .collect(); + assert!(known(&format!("check.{code}")), "{code}"); + } + } + for kind in [ + "denied", + "invalid", + "bad-path", + "failed", + "unavailable", + "timeout", + "error", + ] { + assert!( + known(&format!("err.{kind}.title")) && known(&format!("err.{kind}.hint")), + "{kind}" + ); + } + for code in ["denied", "rate_limited", "invalid", "other", "conflict"] { + assert!(known(&format!("write.{code}")), "{code}"); + } +} + +#[test] +fn no_colour_of_its_own() { + // Hangar draws every widget in the person's theme: a tab names what + // something is, never a colour. + for (file, source) in sources() { + assert!(!source.contains("Ink::"), "{file} names an ink"); + assert!(!source.contains("Surface::"), "{file} picks a surface"); + let hex = source.match_indices('#').any(|(at, _)| { + let digits: String = source[at + 1..] + .chars() + .take_while(char::is_ascii_hexdigit) + .collect(); + digits.len() == 6 + && source[at + 1..] + .chars() + .nth(6) + .is_none_or(|c| !c.is_ascii_alphanumeric()) + }); + assert!(!hex, "{file} holds a colour"); + } +} diff --git a/scripts/build-native.sh b/scripts/build-native.sh new file mode 100755 index 0000000..4d390ad --- /dev/null +++ b/scripts/build-native.sh @@ -0,0 +1,31 @@ +#!/bin/sh +# Builds the tab's native module, tabs/editor.wasm, from native/: what the +# manifest's tab `entry` names and Hangar runs. Hangar never builds a +# kit, so the module is committed with the source that made it: run this in the +# commit that changes native/. +# +# Needs Rust; native/rust-toolchain.toml names the version and the +# wasm32-unknown-unknown target, which rustup installs the first time. The +# paths of this machine are taken out of the module, so that it is the same +# byte for byte wherever it is built: CI builds it again and compares. +# +# scripts/build-native.sh build it, and write tabs/editor.wasm +# scripts/build-native.sh --check build it, and fail if tabs/editor.wasm is not what the source builds +set -eu +kit="$(cd "$(dirname "$0")/.." && pwd)" +cargo_home="${CARGO_HOME:-$HOME/.cargo}" +cd "$kit/native" +RUSTFLAGS="--remap-path-prefix=$kit=/kit --remap-path-prefix=$cargo_home=/cargo" \ + cargo build --release --locked --target wasm32-unknown-unknown +built=target/wasm32-unknown-unknown/release/kit_editor_tab.wasm +if [ "${1:-}" = "--check" ]; then + if cmp -s "$built" "$kit/tabs/editor.wasm"; then + echo "tabs/editor.wasm is what native/ builds." + else + echo "tabs/editor.wasm is stale: run scripts/build-native.sh and commit it." >&2 + exit 1 + fi +else + cp "$built" "$kit/tabs/editor.wasm" + echo "tabs/editor.wasm" +fi diff --git a/tabs/editor.wasm b/tabs/editor.wasm new file mode 100755 index 0000000..f7d94b8 Binary files /dev/null and b/tabs/editor.wasm differ diff --git a/tabs/editor/answer.js b/tabs/editor/answer.js deleted file mode 100644 index 9944ec9..0000000 --- a/tabs/editor/answer.js +++ /dev/null @@ -1,77 +0,0 @@ -"use strict"; -// The only text this tab ever sends to an agent. Every sentence is fixed here; what -// varies is the file's path, key names and counts. It is handed names, never a -// value: `values` is only there so that a name that is also a value stays unsaid. -(function (root, factory) { - const api = factory(); - if (typeof module === "object" && module.exports) module.exports = api; - else root.EditorAnswer = api; -})(typeof globalThis !== "undefined" ? globalThis : this, function () { - const NAME = /^[A-Za-z_][A-Za-z0-9_.-]{0,63}$/; - const NAMED_MAX = 40; - const SHORTEST_INSIDE = 4; // shorter values match names by chance: `1` in KEY1 - const STAY = "The values stay in the file: do not read them back, use them through the program that loads it."; - - /** - * A value pasted where a key goes (`sk_live_abc=`, or a value that repeats as - * another line's key) is still a key to any parser. So a name is said only if it - * looks like one, is one this file or the agent already knew, and holds no value. - */ - function mayName(name, known, values) { - if (typeof name !== "string" || !NAME.test(name) || !known.has(name)) return false; - return !values.some((raw) => { - const value = String(raw).trim(); - return value !== "" && (value === name || (value.length >= SHORTEST_INSIDE && name.includes(value))); - }); - } - - /** The names that may be said, and how many may not. */ - function sayable(names, known, values) { - const named = []; - let others = 0; - for (const name of names) { - if (named.length < NAMED_MAX && mayName(name, known, values)) named.push(name); - else others++; - } - return { named, others }; - } - - function sentence(label, names) { - return names.length ? ` ${label}: ${names.join(", ")}.` : ""; - } - - const others = (count, verb) => (count ? ` ${count} other ${count === 1 ? "key" : "keys"} ${verb}.` : ""); - - /** The person saved a dotenv file. */ - function dotenvSaved({ path, set, emptied, stillEmpty, known, values }) { - const setSaid = sayable(set, known, values); - const emptiedSaid = sayable(emptied, known, values); - const emptySaid = sayable(stillEmpty, known, values); - return ( - `The person saved \`${path}\`.` + - sentence("Set", setSaid.named) + - sentence("Emptied", emptiedSaid.named) + - sentence("Still empty", emptySaid.named) + - others(setSaid.others + emptiedSaid.others + emptySaid.others, "changed or empty") + - ` ${STAY}` - ); - } - - /** The person looked at a dotenv file and had nothing to change. */ - function dotenvChecked({ path, alreadySet, stillEmpty, known, values }) { - const setSaid = sayable(alreadySet, known, values); - const emptySaid = sayable(stillEmpty, known, values); - return ( - `The person checked \`${path}\` and changed nothing.` + - sentence("Already set", setSaid.named) + - sentence("Still empty", emptySaid.named) + - others(setSaid.others + emptySaid.others, "set or empty") + - ` ${STAY}` - ); - } - - const textSaved = ({ path }) => `The person saved \`${path}\`: the file changed.`; - const textChecked = ({ path }) => `The person checked \`${path}\` and changed nothing.`; - - return { dotenvSaved, dotenvChecked, textSaved, textChecked, mayName }; -}); diff --git a/tabs/editor/app.js b/tabs/editor/app.js deleted file mode 100644 index 6c7a854..0000000 --- a/tabs/editor/app.js +++ /dev/null @@ -1,53 +0,0 @@ -"use strict"; -// Starts the tab in the page: wires the controller to the view, in Hangar's language. -(function () { - const logic = window.EditorLogic; - const ui = window.hangar.ui; - const t = ui - ? ui.i18n(logic.STRINGS) - : (key, vars) => logic.t(logic.pickLang(navigator.language), key, vars); - const language = () => (ui ? ui.locale() : logic.pickLang(navigator.language)); - const container = document.getElementById("app"); - - let refresh = () => undefined; - const controller = window.EditorController.createController({ - hangar: window.hangar, - t, - lib: { - logic, - dotenv: window.EditorDotenv, - validate: window.EditorValidate, - diff: window.EditorDiff, - gitignore: window.EditorGitignore, - answer: window.EditorAnswer, - }, - onChange: draw, - onTyping: () => refresh(), - }); - - const ctx = { - doc: document, - t, - logic, - gitignore: window.EditorGitignore, - actions: controller, - confirm: (anchor, options) => (ui ? ui.confirm(anchor, options) : Promise.resolve(false)), - }; - - function draw(state) { - document.documentElement.lang = language(); - document.title = t("tab"); - refresh = window.EditorView.render(container, state, ctx); - } - - // The first `theme` event may bring Hangar's language; a later one may change it. - let lastLanguage = language(); - window.hangar.on("theme", () => { - if (language() === lastLanguage) return; - lastLanguage = language(); - draw(controller.state); - }); - - draw(controller.state); - controller.start(); -})(); diff --git a/tabs/editor/controller.js b/tabs/editor/controller.js deleted file mode 100644 index c69829a..0000000 --- a/tabs/editor/controller.js +++ /dev/null @@ -1,725 +0,0 @@ -"use strict"; -// The tab's behaviour, apart from any DOM. `hangar` is `window.hangar`, or a fake of -// it. It reports a change of what is on screen through `onChange(state)`, and a -// keystroke's consequences through `onTyping(state)`, so that typing never redraws -// the field being typed in. Values go to `files.write` and nowhere else. -(function (root, factory) { - const api = factory(); - if (typeof module === "object" && module.exports) module.exports = api; - else root.EditorController = api; -})(typeof globalThis !== "undefined" ? globalThis : this, function () { - const VALIDATE_WHILE_TYPING_MAX = 100000; // larger files are checked when reviewing - - /** - * @param {object} options - * @param {{call(method: string, params?: object): Promise, on?(event: string, fn: Function): Function}} options.hangar - * @param {{logic, dotenv, validate, diff, gitignore, answer}} options.lib - * @param {string} [options.lang] Used only when no `t` is given. - * @param {(key: string, vars?: object) => string} [options.t] The page's words. - * @param {(state: object) => void} [options.onChange] - * @param {(state: object) => void} [options.onTyping] - */ - function createController(options) { - const { hangar, lib } = options; - const { logic, dotenv, validate, diff, gitignore, answer } = lib; - const t = options.t || ((key, vars) => logic.t(options.lang || "en", key, vars)); - const onChange = options.onChange || (() => undefined); - const onTyping = options.onTyping || (() => undefined); - - const state = { - view: "loading", // loading | picker | dotenv | text | error - path: null, - caller: null, - why: null, - asked: [], - fromPicker: false, - exists: false, - busy: false, - problem: null, // what a write said: { code, detail } - saved: false, - told: null, // { status: "sent" | "failed" | "checked", pane, code? } - error: null, // { kind, detail }: the whole page - picker: null, // { groups, filter, truncated } - form: null, // { rows, offered, exampleName, otherLines } - ignore: null, // { status, busy, problem } - text: null, // { value, original, stage, check, ack, hunks, jump, far } - conflict: null, - }; - - let generation = 0; // a later file makes the earlier answers stale - let disposed = false; - let offParams = null; - let lastTitle = null; - let lastBadge = null; - let doc = null; // the dotenv file as last read or written - let lastRead = null; // the exact text the file held when last read, null when absent - let exampleRows = []; - let exampleName = null; - let exampleValues = []; - let unsent = null; // an answer that could not be sent, to try again as it is - - const emit = () => { - if (!disposed) onChange(state); - }; - const typed = () => { - if (!disposed) onTyping(state); - }; - - async function setTitle(title) { - if (title === lastTitle) return; - lastTitle = title; - try { - await hangar.call("tab.setTitle", { title }); - } catch { - /* a refused title leaves the tab's own */ - } - } - - function missingCount() { - if (state.view !== "dotenv" || !state.form) return 0; - return state.form.rows.filter((row) => row.asked && row.value === "").length; - } - - async function setBadge() { - const missing = missingCount(); - let badge = null; - if (missing) badge = { state: "neutral", text: t("badgeMissing", { n: missing }).slice(0, 12) }; - else if (state.saved) badge = { state: "success", text: t("badgeSaved").slice(0, 12) }; - const key = badge ? `${badge.state}|${badge.text}` : "none"; - if (key === lastBadge) return; - lastBadge = key; - try { - await hangar.call("tab.setBadge", badge || { state: null }); - } catch { - /* idem */ - } - } - - async function readOrNull(path) { - try { - return await hangar.call("files.read", { path }); - } catch (error) { - if (error && error.code === "not_found") return null; - throw error; - } - } - - const KNOWN_ERRORS = new Set(["denied", "invalid", "failed", "unavailable", "timeout"]); - - function showError(error, kind) { - state.view = "error"; - const code = error && error.code; - state.error = { kind: kind || (KNOWN_ERRORS.has(code) ? code : "error"), detail: String((error && error.message) || "") }; - state.busy = false; - setBadge(); - emit(); - } - - /* ── the agent's answer ───────────────────────────────────────── */ - - /** The one place that speaks to an agent. `message` comes from answer.js, which is handed no value. */ - async function send(message, status) { - if (!state.caller) { - state.told = null; - unsent = null; - return; - } - const { pane } = state.caller; - unsent = { message, status }; - try { - await hangar.call("panes.send", { pane, text: message }); - state.told = { status, pane }; - unsent = null; - } catch (error) { - state.told = { status: "failed", pane, code: (error && error.code) || "other" }; - } - } - - async function retryTell() { - if (!unsent || state.busy) return; - state.busy = true; - emit(); - await send(unsent.message, unsent.status); - state.busy = false; - emit(); - } - - /* ── dotenv: the form ─────────────────────────────────────────── */ - - function buildForm(fileDoc) { - const present = dotenv.rows(fileDoc); - const byKey = new Map(present.map((row) => [row.key, row])); - const hints = new Map(exampleRows.map((row) => [row.key, row.hint])); - const makeRow = (key, asked) => { - const found = byKey.get(key); - return { - key, - asked, - present: Boolean(found), - original: found ? found.value : null, - value: found ? found.value : "", - hint: (found && found.hint) || hints.get(key) || "", - count: found ? found.count : 0, - revealed: false, - added: false, - typed: false, - }; - }; - const rows = state.asked.map((key) => makeRow(key, true)); - for (const row of present) if (!state.asked.includes(row.key)) rows.push(makeRow(row.key, false)); - const shown = new Set(rows.map((row) => row.key)); - const offered = exampleRows.filter((row) => !shown.has(row.key)).map((row) => ({ key: row.key, hint: row.hint })); - return { rows, offered, exampleName, otherLines: dotenv.otherLines(fileDoc), newKey: "", newKeyProblem: null }; - } - - /** What the form changes: key → value. */ - function formEdits() { - const edits = new Map(); - for (const row of state.form.rows) { - if (row.present ? row.value !== row.original : row.added || row.value !== "") edits.set(row.key, row.value); - } - return edits; - } - - async function readExample(path) { - if (dotenv.isExamplePath(path)) return null; - for (const candidate of dotenv.exampleCandidates(path)) { - let text = null; - try { - text = await readOrNull(candidate); - } catch { - return null; // no template to offer: the form works without - } - if (text !== null) return { name: logic.baseName(candidate), doc: dotenv.parse(text) }; - } - return null; - } - - async function checkIgnore(path) { - if (dotenv.isExamplePath(path)) return { status: "ignored" }; // a template is meant to be committed - const sources = []; - for (const source of gitignore.sourcesFor(path)) { - try { - const text = await readOrNull(source.path); - if (text !== null) sources.push({ dir: source.dir, text }); - } catch { - return { status: "unknown" }; - } - } - if (!sources.length) return { status: "no-file" }; - return { status: gitignore.isIgnored(sources, path) ? "ignored" : "not-ignored" }; - } - - async function openDotenv(path, text, token) { - const example = await readExample(path); - const ignore = await checkIgnore(path); - if (token !== generation || disposed) return; - doc = dotenv.parse(text === null ? "" : text); - exampleRows = example ? dotenv.rows(example.doc) : []; - exampleName = example ? example.name : null; - exampleValues = example ? dotenv.allValues(example.doc) : []; - Object.assign(state, { - view: "dotenv", - form: buildForm(doc), - ignore, - text: null, - busy: false, - }); - setBadge(); - emit(); - } - - function editRow(key, value) { - const row = state.form && state.form.rows.find((other) => other.key === key); - if (!row) return; - row.value = value; - state.saved = false; - setBadge(); - typed(); - } - - function toggleReveal(key) { - const row = state.form && state.form.rows.find((other) => other.key === key); - if (!row) return; - row.revealed = !row.revealed; - emit(); - } - - function addOffered(key) { - const form = state.form; - const offer = form && form.offered.find((other) => other.key === key); - if (!offer) return; - form.offered = form.offered.filter((other) => other !== offer); - form.rows.push({ - key: offer.key, asked: false, present: false, original: null, value: "", hint: offer.hint, - count: 0, revealed: false, added: true, typed: false, - }); - emit(); - } - - function addAllOffered() { - if (!state.form) return; - for (const offer of [...state.form.offered]) addOffered(offer.key); - } - - function setNewKey(name) { - if (!state.form) return; - state.form.newKey = name; - state.form.newKeyProblem = null; - typed(); - } - - /** A key the person types. It may be a secret pasted in the wrong field, so it is never named to the agent. */ - function addNewKey() { - const form = state.form; - if (!form) return; - const name = form.newKey.trim(); - if (!dotenv.isKey(name)) form.newKeyProblem = "newKeyBad"; - else if (form.rows.some((row) => row.key === name)) form.newKeyProblem = "newKeyTaken"; - else { - form.offered = form.offered.filter((other) => other.key !== name); - form.rows.push({ - key: name, asked: false, present: false, original: null, value: "", hint: "", - count: 0, revealed: false, added: true, typed: true, - }); - form.newKey = ""; - form.newKeyProblem = null; - } - emit(); - } - - /** Names and counts for the agent, read from what the file holds now. */ - function dotenvFacts(before, after) { - const rows = dotenv.rows(after); - const value = new Map(rows.map((row) => [row.key, row.value])); - const typedNames = new Set(state.form.rows.filter((row) => row.typed).map((row) => row.key)); - const known = new Set([...state.asked, ...exampleRows.map((row) => row.key), ...dotenv.rows(before).map((row) => row.key)]); - for (const name of typedNames) known.delete(name); - return { - path: state.path, - known, - values: [...dotenv.allValues(before), ...dotenv.allValues(after), ...exampleValues], - stillEmpty: state.asked.filter((key) => !value.get(key)), - alreadySet: state.asked.filter((key) => value.get(key)), - }; - } - - async function afterFormSave(written) { - const before = doc; - const after = dotenv.parse(written); - const changed = dotenv.changedKeys(before, after); - const facts = dotenvFacts(before, after); - const message = answer.dotenvSaved({ ...facts, set: changed.set, emptied: changed.emptied }); - doc = after; - state.exists = true; - state.form = buildForm(after); - state.saved = true; - await send(message, "sent"); - } - - function saveForm() { - if (state.view !== "dotenv" || state.busy || state.conflict) return undefined; - const edits = formEdits(); - if (!edits.size) return undefined; - return persist(dotenv.serialize(dotenv.withValues(doc, edits)), afterFormSave); - } - - async function addToGitignore() { - if (!state.ignore || state.ignore.busy || !state.path) return; - const path = state.path; - state.ignore = { ...state.ignore, busy: true, problem: null }; - emit(); - try { - const current = await readOrNull(".gitignore"); - const text = gitignore.withPattern(current === null ? "" : current, gitignore.patternFor(path)); - await hangar.call("files.write", current === null ? { path: ".gitignore", text } : { path: ".gitignore", text, expected: current }); - state.ignore = await checkIgnore(path); - } catch (error) { - state.ignore = { ...state.ignore, busy: false, problem: (error && error.code) || "other" }; - } - emit(); - } - - /* ── any other text file: the editor ──────────────────────────── */ - - function openText(path, text, line) { - const original = diff.normalize(text === null ? "" : text); - const total = original.split("\n").length; - Object.assign(state, { - view: "text", - form: null, - ignore: null, - busy: false, - text: { - value: original, - original, - stage: "edit", - check: validate.validate(path, original), - ack: false, - hunks: null, - jump: line === null ? null : Math.min(line, total), - target: line === null ? null : Math.min(line, total), - far: line !== null && line > total ? { line, total } : null, - }, - }); - setBadge(); - emit(); - } - - function editText(value) { - const text = state.text; - if (!text) return; - text.value = value; - state.saved = false; - if (value.length <= VALIDATE_WHILE_TYPING_MAX) { - text.check = validate.validate(state.path, value); - text.ack = false; - } - setBadge(); - typed(); - } - - function consumeJump() { - if (state.text) state.text.jump = null; - } - - function review() { - const text = state.text; - if (!text || state.view !== "text") return; - text.check = validate.validate(state.path, text.value); - text.ack = false; - text.hunks = diff.hunks(diff.diffLines(text.original, text.value)); - text.stage = "review"; - state.problem = null; - emit(); - } - - function backToEdit() { - if (!state.text) return; - state.text.stage = "edit"; - emit(); - } - - function setAck(checked) { - if (!state.text) return; - state.text.ack = Boolean(checked); - emit(); - } - - async function afterTextSave(written) { - const text = state.text; - text.original = diff.normalize(written); - text.value = text.original; - text.stage = "edit"; - text.hunks = null; - text.ack = false; - state.exists = true; - state.saved = true; - await send(answer.textSaved({ path: state.path }), "sent"); - } - - /** A broken file goes through only once the person has said they know. */ - function saveText() { - const text = state.text; - if (!text || state.view !== "text" || state.busy || state.conflict) return undefined; - text.check = validate.validate(state.path, text.value); - if (!text.check.ok && !text.ack) return undefined; - if (text.value === text.original && state.exists) return undefined; - return persist(diff.restoreEols(lastRead === null ? "" : lastRead, text.value), afterTextSave); - } - - /* ── writing, and what happens when the file moved ────────────── */ - - /** `expected` cannot say "still absent", so a new file is looked for again just before. */ - async function write(path, text) { - if (lastRead === null) { - const now = await readOrNull(path); - if (now !== null) return { conflict: true, theirs: now }; - await hangar.call("files.write", { path, text }); - return { ok: true }; - } - try { - await hangar.call("files.write", { path, text, expected: lastRead }); - return { ok: true }; - } catch (error) { - if (error && error.code === "conflict") return { conflict: true, theirs: await readOrNull(path) }; - throw error; - } - } - - async function persist(text, done) { - const token = generation; - Object.assign(state, { busy: true, problem: null, saved: false, told: null }); - emit(); - let outcome; - try { - outcome = await write(state.path, text); - } catch (error) { - outcome = { error }; - } - if (token !== generation || disposed) return; - if (outcome.error) { - const code = outcome.error.code; - state.busy = false; - state.problem = { code: code === "denied" || code === "rate_limited" || code === "invalid" ? code : "other", detail: String(outcome.error.message || "") }; - emit(); - return; - } - if (outcome.conflict) { - state.busy = false; - state.conflict = state.view === "dotenv" ? formConflict(outcome.theirs) : textConflict(outcome.theirs); - emit(); - return; - } - lastRead = text; - await done(text); - if (token !== generation || disposed) return; - state.busy = false; - setBadge(); - emit(); - } - - function textConflict(theirs) { - const mine = state.text.value; - const disk = diff.normalize(theirs === null ? "" : theirs); - return { kind: "text", theirs, gone: theirs === null, hunks: diff.hunks(diff.diffLines(disk, mine)) }; - } - - function formConflict(theirs) { - const edits = formEdits(); - const theirDoc = dotenv.parse(theirs === null ? "" : theirs); - const disk = new Map(dotenv.rows(theirDoc).map((row) => [row.key, row.value])); - const rows = []; - for (const [key, mine] of edits) { - if (disk.get(key) !== mine) rows.push({ key, mine, theirs: disk.has(key) ? disk.get(key) : null, choice: "mine", revealed: false }); - } - const was = new Map(dotenv.rows(doc).map((row) => [row.key, row.value])); - let changedOnDisk = 0; - for (const key of new Set([...was.keys(), ...disk.keys()])) { - if (!edits.has(key) && was.get(key) !== disk.get(key)) changedOnDisk++; - } - return { kind: "dotenv", theirs, gone: theirs === null, rows, edits, changedOnDisk }; - } - - function conflictChoose(key, choice) { - const row = state.conflict && state.conflict.rows && state.conflict.rows.find((other) => other.key === key); - if (!row || (choice !== "mine" && choice !== "theirs")) return; - row.choice = choice; - emit(); - } - - function conflictReveal(key) { - const row = state.conflict && state.conflict.rows && state.conflict.rows.find((other) => other.key === key); - if (!row) return; - row.revealed = !row.revealed; - emit(); - } - - /** Mine wins, on top of what the disk holds now. Only ever on the person's click. */ - function conflictKeepMine() { - const conflict = state.conflict; - if (!conflict || state.busy) return undefined; - state.conflict = null; - lastRead = conflict.theirs; - if (conflict.kind === "text") { - const text = state.text; - text.original = diff.normalize(conflict.theirs === null ? "" : conflict.theirs); - return persist(diff.restoreEols(conflict.theirs === null ? "" : conflict.theirs, text.value), afterTextSave); - } - const edits = new Map(conflict.edits); - for (const row of conflict.rows) if (row.choice === "theirs") edits.delete(row.key); - doc = dotenv.parse(conflict.theirs === null ? "" : conflict.theirs); - return persist(dotenv.serialize(dotenv.withValues(doc, edits)), afterFormSave); - } - - /** What is on disk wins, and what the person typed is dropped: only on their click too. */ - async function conflictTakeTheirs() { - const conflict = state.conflict; - if (!conflict || state.busy) return; - state.conflict = null; - lastRead = conflict.theirs; - state.exists = conflict.theirs !== null; - Object.assign(state, { saved: false, told: null, problem: null }); - await loadInto(state.path, conflict.theirs, null); - } - - /** Back to the text with mine, measured against what the disk holds now. */ - function conflictBack() { - const conflict = state.conflict; - if (!conflict || conflict.kind !== "text") return; - state.conflict = null; - lastRead = conflict.theirs; - state.exists = conflict.theirs !== null; - state.text.original = diff.normalize(conflict.theirs === null ? "" : conflict.theirs); - state.text.stage = "edit"; - emit(); - } - - /** The person looked and has nothing to change: the waiting agent still hears of it. */ - async function tellNoChange() { - if (!state.caller || state.busy) return; - let message = null; - if (state.view === "dotenv") { - if (formEdits().size) return; - const facts = dotenvFacts(doc, doc); - message = answer.dotenvChecked(facts); - } else if (state.view === "text") { - if (state.text.value !== state.text.original) return; - message = answer.textChecked({ path: state.path }); - } - if (!message) return; - state.busy = true; - emit(); - await send(message, "checked"); - state.busy = false; - emit(); - } - - /* ── opening ──────────────────────────────────────────────────── */ - - async function loadInto(path, text, line) { - const token = generation; - if (dotenv.isDotenvPath(path)) await openDotenv(path, text, token); - else if (token === generation && !disposed) openText(path, text, line); - } - - async function open(path, line) { - const token = ++generation; - Object.assign(state, { - view: "loading", path, busy: false, problem: null, saved: false, told: null, error: null, - conflict: null, form: null, text: null, ignore: null, - }); - unsent = null; - emit(); - await setTitle(logic.tabTitle(path)); - let text; - try { - text = await readOrNull(path); - } catch (error) { - if (token === generation && !disposed) showError(error); - return; - } - if (token !== generation || disposed) return; - lastRead = text; - state.exists = text !== null; - await loadInto(path, text, line); - } - - async function showPicker() { - const token = ++generation; - Object.assign(state, { - view: "loading", path: null, busy: false, problem: null, saved: false, told: null, error: null, - conflict: null, form: null, text: null, ignore: null, fromPicker: false, - }); - unsent = null; - emit(); - await setTitle(t("tab")); - setBadge(); - let listing; - try { - listing = await hangar.call("files.list"); - } catch (error) { - if (token === generation && !disposed) showError(error); - return; - } - if (token !== generation || disposed) return; - const groups = logic.rankFiles(listing && listing.files); - state.picker = { groups, filter: "", truncated: Boolean(listing && listing.truncated) }; - state.view = "picker"; - emit(); - } - - function pick(path) { - const checked = logic.checkPath(path); - if (!checked) return undefined; - state.fromPicker = true; - return open(checked, null); - } - - function setFilter(filter) { - if (!state.picker) return; - state.picker.filter = filter; - typed(); - } - - function isDirty() { - if (state.view === "dotenv" && state.form) return formEdits().size > 0; - if (state.view === "text" && state.text) return state.text.value !== state.text.original; - return false; - } - - /** Asked for again: the latest to ask is the one to answer, and what was typed stays. */ - function handleParams(message) { - const read = logic.readParams(message); - state.caller = read.caller; - unsent = null; - const editing = (state.view === "dotenv" || state.view === "text") && state.path; - if (editing && (!read.path || read.path === state.path)) { - state.why = read.why; - if (state.view === "dotenv" && read.keys.length) { - const fresh = read.keys.filter((key) => !state.asked.includes(key)); - state.asked = [...state.asked, ...fresh]; - for (const key of fresh) { - const row = state.form.rows.find((other) => other.key === key); - if (row) row.asked = true; - else { - state.form.offered = state.form.offered.filter((other) => other.key !== key); - state.form.rows.push({ - key, asked: true, present: false, original: null, value: "", hint: "", - count: 0, revealed: false, added: false, typed: false, - }); - } - } - state.form.rows.sort((a, b) => Number(b.asked) - Number(a.asked)); - } - state.told = null; - state.saved = false; - setBadge(); - emit(); - return undefined; - } - if (read.badPath) { - state.path = null; - showError(null, "bad-path"); - return undefined; - } - state.why = read.why; - state.asked = read.keys; - state.fromPicker = false; - return read.path ? open(read.path, read.line) : showPicker(); - } - - return { - state, - async start() { - if (typeof hangar.on === "function") offParams = hangar.on("tab.params", (data) => handleParams(data)); - let message = { params: {}, caller: null }; - try { - message = await hangar.call("tab.params"); - } catch { - /* no params: the picker */ - } - return handleParams(message); - }, - isDirty, - pick, setFilter, - /** From a file opened in the picker, back to the picker. The view asks first when there are edits. */ - back: () => showPicker(), - retry() { - if (state.path) return open(state.path, null); - return showPicker(); - }, - editRow, toggleReveal, addOffered, addAllOffered, setNewKey, addNewKey, addToGitignore, saveForm, - editText, consumeJump, review, backToEdit, setAck, saveText, - conflictChoose, conflictReveal, conflictKeepMine, conflictTakeTheirs, conflictBack, - tellNoChange, retryTell, - dispose() { - disposed = true; - generation++; - if (typeof offParams === "function") offParams(); - }, - }; - } - - return { createController }; -}); diff --git a/tabs/editor/diff.js b/tabs/editor/diff.js deleted file mode 100644 index 52285a4..0000000 --- a/tabs/editor/diff.js +++ /dev/null @@ -1,114 +0,0 @@ -"use strict"; -// Lines compared, for the diff before saving and the conflict view, and the line -// endings a textarea takes away, given back. No DOM, no Hangar. -(function (root, factory) { - const api = factory(); - if (typeof module === "object" && module.exports) module.exports = api; - else root.EditorDiff = api; -})(typeof globalThis !== "undefined" ? globalThis : this, function () { - const LCS_CELLS = 4000000; // beyond this the changed block is shown as replaced whole - const CONTEXT = 3; - - /** What a textarea does to a text: its `value` only ever holds \n. */ - const normalize = (text) => text.replace(/\r\n?/g, "\n"); - - function middle(a, b, offsetA, offsetB, out) { - const n = a.length; - const m = b.length; - const push = (op, i, j) => - out.push( - op === "add" - ? { op, text: b[j], a: null, b: offsetB + j + 1 } - : { op, text: a[i], a: offsetA + i + 1, b: null }, - ); - if (!n || !m || n * m > LCS_CELLS) { - for (let i = 0; i < n; i++) push("del", i); - for (let j = 0; j < m; j++) push("add", 0, j); - return; - } - const width = m + 1; - const table = new Uint32Array((n + 1) * width); - for (let i = n - 1; i >= 0; i--) { - for (let j = m - 1; j >= 0; j--) { - table[i * width + j] = - a[i] === b[j] ? table[(i + 1) * width + j + 1] + 1 : Math.max(table[(i + 1) * width + j], table[i * width + j + 1]); - } - } - let i = 0; - let j = 0; - while (i < n || j < m) { - if (i < n && j < m && a[i] === b[j]) { - out.push({ op: "same", text: a[i], a: offsetA + i + 1, b: offsetB + j + 1 }); - i++; - j++; - } else if (j >= m || (i < n && table[(i + 1) * width + j] >= table[i * width + j + 1])) { - push("del", i++); - } else { - push("add", 0, j++); - } - } - } - - /** Every line of `before` and `after` (both \n only), in order: same, del or add, with its numbers. */ - function diffLines(before, after) { - const a = before.split("\n"); - const b = after.split("\n"); - let head = 0; - while (head < a.length && head < b.length && a[head] === b[head]) head++; - let tail = 0; - while (tail < a.length - head && tail < b.length - head && a[a.length - 1 - tail] === b[b.length - 1 - tail]) tail++; - const out = []; - for (let i = 0; i < head; i++) out.push({ op: "same", text: a[i], a: i + 1, b: i + 1 }); - middle(a.slice(head, a.length - tail), b.slice(head, b.length - tail), head, head, out); - for (let i = tail; i > 0; i--) out.push({ op: "same", text: a[a.length - i], a: a.length - i + 1, b: b.length - i + 1 }); - return out; - } - - /** The same, unchanged stretches folded into `{ op: "skip", count }`. */ - function hunks(ops, context = CONTEXT) { - const near = new Uint8Array(ops.length); - ops.forEach((op, index) => { - if (op.op === "same") return; - const end = Math.min(ops.length - 1, index + context); - for (let i = Math.max(0, index - context); i <= end; i++) near[i] = 1; - }); - const out = []; - let skipped = 0; - ops.forEach((op, index) => { - if (near[index]) { - if (skipped) out.push({ op: "skip", count: skipped }); - skipped = 0; - out.push(op); - } else { - skipped++; - } - }); - if (skipped) out.push({ op: "skip", count: skipped }); - return out; - } - - const hasChanges = (ops) => ops.some((op) => op.op !== "same"); - - /** - * `edited` (\n only) with the line endings of `original` back: each line that did - * not change keeps its own, and a new one takes the file's most common. - */ - function restoreEols(original, edited) { - const pieces = original.split(/(\r\n|\n|\r)/); - const eols = []; - for (let i = 1; i < pieces.length; i += 2) eols.push(pieces[i]); - const count = (eol) => eols.filter((other) => other === eol).length; - const counts = ["\n", "\r\n", "\r"].map((eol) => [eol, count(eol)]); - if (counts[0][1] === eols.length) return edited; - if (counts[1][1] === eols.length) return edited.replace(/\n/g, "\r\n"); - const common = counts.reduce((best, each) => (each[1] > best[1] ? each : best))[0]; - const lines = edited.split("\n"); - const kept = new Array(lines.length).fill(null); - for (const op of diffLines(normalize(original), edited)) { - if (op.op === "same") kept[op.b - 1] = eols[op.a - 1] || null; - } - return lines.map((line, index) => (index === lines.length - 1 ? line : line + (kept[index] || common))).join(""); - } - - return { normalize, diffLines, hunks, hasChanges, restoreEols }; -}); diff --git a/tabs/editor/dotenv.js b/tabs/editor/dotenv.js deleted file mode 100644 index 155c164..0000000 --- a/tabs/editor/dotenv.js +++ /dev/null @@ -1,228 +0,0 @@ -"use strict"; -// Reads a dotenv file so that saving it changes only what was edited: every line -// keeps its exact bytes (comments, blanks, order, line endings, quotes) unless its -// own value changed. No DOM, no Hangar: the page and the tests both load this file. -(function (root, factory) { - const api = factory(); - if (typeof module === "object" && module.exports) module.exports = api; - else root.EditorDotenv = api; -})(typeof globalThis !== "undefined" ? globalThis : this, function () { - const ASSIGNMENT = /^([ \t]*(?:export[ \t]+)?)([A-Za-z_][A-Za-z0-9_.-]*)([ \t]*=[ \t]*)/; - const KEY = /^[A-Za-z_][A-Za-z0-9_.-]*$/; - const BARE_SAFE = /^[A-Za-z0-9_./:@%+,=~-]+$/; - // `# OLD_TOKEN=abc` is a value put aside, not an explanation: it is never shown as a hint. - const COMMENTED_ASSIGNMENT = /^#+[ \t]*(?:export[ \t]+)?[A-Za-z_][A-Za-z0-9_.-]*[ \t]*=/; - const ESCAPES = { n: "\n", r: "\r", t: "\t", '"': '"', "\\": "\\", $: "$" }; - const HINT_MAX = 300; - - const isKey = (name) => typeof name === "string" && KEY.test(name); - - function lineEnd(text, from) { - for (let i = from; i < text.length; i++) { - if (text[i] === "\n" || text[i] === "\r") return i; - } - return text.length; - } - - function eolAt(text, at) { - if (text[at] === "\r" && text[at + 1] === "\n") return "\r\n"; - return text[at] === "\n" || text[at] === "\r" ? text[at] : ""; - } - - /** Where the quote opened before `from` closes, or -1. */ - function closing(text, from, quote, escapes) { - for (let i = from; i < text.length; i++) { - if (escapes && text[i] === "\\") i++; - else if (text[i] === quote) return i; - } - return -1; - } - - function unquoted(inner, quote, escapes) { - if (quote === '"') { - return inner.replace(/\\([^])/g, (whole, char) => (ESCAPES[char] === undefined ? whole : ESCAPES[char])); - } - return escapes ? inner.split(`\\${quote}`).join(quote) : inner; - } - - /** - * A quoted value, over several lines if it says so. A quote counts as closed only - * when nothing but a comment follows it: otherwise `A="x` would swallow the lines - * below it, and what is a value would be read as keys, or the reverse. - */ - function readQuoted(text, start) { - const quote = text[start]; - for (const escapes of quote === '"' ? [true] : [false, true]) { - const close = closing(text, start + 1, quote, escapes); - if (close < 0) continue; - const end = lineEnd(text, close + 1); - const rest = text.slice(close + 1, end); - if (!/^[ \t]*(?:#[^]*)?$/.test(rest)) continue; - return { value: unquoted(text.slice(start + 1, close), quote, escapes), quote, trailing: rest, end }; - } - return null; - } - - function readBare(rest, afterBlank) { - let cut = rest.length; - for (let i = 0; i < rest.length; i++) { - if (rest[i] === "#" && (i > 0 ? rest[i - 1] === " " || rest[i - 1] === "\t" : afterBlank)) { - cut = i; - break; - } - } - let end = cut; - while (end > 0 && (rest[end - 1] === " " || rest[end - 1] === "\t")) end--; - return { value: rest.slice(0, end), trailing: rest.slice(end), quote: "" }; - } - - /** The text, as entries: a pair, or a line kept as it is. `serialize` gives back the same text. */ - function parse(text) { - const entries = []; - let at = 0; - let crlf = 0; - let lf = 0; - while (at < text.length) { - const end = lineEnd(text, at); - const line = text.slice(at, end); - const match = ASSIGNMENT.exec(line); - let entryEnd = end; - if (match) { - const [head, lead, key, separator] = match; - const start = at + head.length; - const quoted = "\"'`".includes(text[start] || " ") ? readQuoted(text, start) : null; - const read = quoted || readBare(text.slice(start, end), /[ \t]$/.test(separator)); - if (quoted) entryEnd = quoted.end; - entries.push({ - kind: "pair", - key, - value: read.value, - prefix: lead + key, - separator, - quote: read.quote, - trailing: read.trailing, - raw: text.slice(at, entryEnd), - eol: eolAt(text, entryEnd), - }); - } else { - const trimmed = line.trim(); - entries.push({ kind: "other", raw: line, eol: eolAt(text, end), blank: trimmed === "", comment: trimmed[0] === "#" }); - } - const eol = eolAt(text, entryEnd); - if (eol === "\r\n") crlf++; - else if (eol === "\n") lf++; - at = entryEnd + eol.length; - } - return { entries, eol: crlf > lf ? "\r\n" : "\n" }; - } - - const serialize = (doc) => doc.entries.map((entry) => entry.raw + entry.eol).join(""); - - /** - * A value as the file should hold it. Single quotes are the least magical: no - * escape, no expansion, several lines allowed. A value holding one needs double - * quotes, and then every parser reads \\ \" \n and \r back. - */ - function quoted(value, previous) { - if (value === "") return previous ? previous + previous : ""; - if (BARE_SAFE.test(value)) return previous ? previous + value + previous : value; - if (!value.includes("'")) return `'${value}'`; - const escaped = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\r/g, "\\r").replace(/\n/g, "\\n"); - return `"${escaped}"`; - } - - function rendered(entry, value) { - const body = quoted(value, entry.quote); - const gap = body && entry.trailing[0] === "#" ? " " : ""; - return entry.prefix + entry.separator + body + gap + entry.trailing; - } - - /** - * The doc with these values set (a Map of key → value), each on the last line that - * defines its key, the one parsers keep. A key the file does not have goes at the - * end. Nothing else moves. - */ - function withValues(doc, edits) { - const remaining = new Map(edits); - const last = new Map(); - doc.entries.forEach((entry, index) => { - if (entry.kind === "pair") last.set(entry.key, index); - }); - const entries = doc.entries.map((entry, index) => { - if (entry.kind !== "pair" || last.get(entry.key) !== index || !remaining.has(entry.key)) return entry; - const value = remaining.get(entry.key); - remaining.delete(entry.key); - return value === entry.value ? entry : { ...entry, value, raw: rendered(entry, value) }; - }); - for (const [key, value] of remaining) { - const tail = entries[entries.length - 1]; - if (tail && tail.eol === "") entries[entries.length - 1] = { ...tail, eol: doc.eol }; - const fresh = { kind: "pair", key, value, prefix: key, separator: "=", quote: "", trailing: "", eol: doc.eol }; - entries.push({ ...fresh, raw: rendered(fresh, value) }); - } - return { entries, eol: doc.eol }; - } - - /** One row per key, in the file's order: the value parsers keep, the comment above it, how many lines define it. */ - function rows(doc) { - const found = new Map(); - let comments = []; - for (const entry of doc.entries) { - if (entry.kind === "other") { - const line = entry.raw.trim(); - if (entry.comment && !COMMENTED_ASSIGNMENT.test(line)) comments.push(line.replace(/^#+[ \t]?/, "")); - else if (!entry.comment) comments = []; - continue; - } - const known = found.get(entry.key); - if (known) { - known.value = entry.value; - known.count++; - } else { - found.set(entry.key, { key: entry.key, value: entry.value, count: 1, hint: comments.join(" ").slice(0, HINT_MAX) }); - } - comments = []; - } - return [...found.values()]; - } - - /** Every value the file holds, those that a later line overrides included. */ - const allValues = (doc) => doc.entries.filter((entry) => entry.kind === "pair").map((entry) => entry.value); - - /** Lines that are neither a pair, a comment nor blank: never shown, kept as they are. */ - const otherLines = (doc) => doc.entries.filter((entry) => entry.kind === "other" && !entry.blank && !entry.comment).length; - - /** Which keys got a value and which lost theirs, by name. It returns no value. */ - function changedKeys(before, after) { - const old = new Map(rows(before).map((row) => [row.key, row.value])); - const set = []; - const emptied = []; - for (const row of rows(after)) { - if (row.value === old.get(row.key)) continue; - if (row.value !== "") set.push(row.key); - else if (old.has(row.key)) emptied.push(row.key); - } - return { set, emptied }; - } - - const baseName = (path) => path.slice(path.lastIndexOf("/") + 1); - - function isDotenvPath(path) { - const name = baseName(path).toLowerCase(); - return /^\.env(\..+)?$/.test(name) || /.\.env$/.test(name); - } - - /** A template meant to be committed, with no secret to protect. */ - const isExamplePath = (path) => isDotenvPath(path) && /\.(example|sample|template|dist|defaults?)$/i.test(baseName(path)); - - /** Where this file's template may be, the nearest name first. */ - function exampleCandidates(path) { - const slash = path.lastIndexOf("/"); - const dir = slash < 0 ? "" : path.slice(0, slash + 1); - const name = baseName(path); - const names = [`${name}.example`, `${name}.sample`, ".env.example", ".env.sample", ".env.template", ".env.dist"]; - return [...new Set(names)].filter((other) => other !== name).map((other) => dir + other); - } - - return { parse, serialize, withValues, rows, allValues, otherLines, changedKeys, isKey, isDotenvPath, isExamplePath, exampleCandidates }; -}); diff --git a/tabs/editor/gitignore.js b/tabs/editor/gitignore.js deleted file mode 100644 index 7829b88..0000000 --- a/tabs/editor/gitignore.js +++ /dev/null @@ -1,151 +0,0 @@ -"use strict"; -// Whether .gitignore files ignore a path, by git's own rules. What git also reads -// and a tab cannot (.git/info/exclude, the global excludes, whether the file is -// already tracked) is said in the README. No DOM, no Hangar. -(function (root, factory) { - const api = factory(); - if (typeof module === "object" && module.exports) module.exports = api; - else root.EditorGitignore = api; -})(typeof globalThis !== "undefined" ? globalThis : this, function () { - const literal = (char) => char.replace(/[\\^$.*+?()[\]{}|/-]/g, "\\$&"); - - /** A character class at `at`, as a regular expression, and where it ends; null if it never closes. */ - function charClass(glob, at) { - let i = at + 1; - let out = "["; - if (glob[i] === "!" || glob[i] === "^") { - out += "^"; - i++; - } - if (glob[i] === "]") { - out += "\\]"; - i++; - } - for (; i < glob.length; i++) { - if (glob[i] === "]") return { source: `${out}]`, end: i }; - if (glob[i] === "\\" && i + 1 < glob.length) out += literal(glob[++i]); - else if (glob[i] === "[") out += "\\["; - else out += glob[i]; - } - return null; - } - - function toRegExp(glob) { - const anchored = glob.includes("/"); - const body = glob.startsWith("/") ? glob.slice(1) : glob; - let out = anchored ? "^" : "^(?:.*/)?"; - for (let i = 0; i < body.length; i++) { - const char = body[i]; - if (char === "*" && body[i + 1] === "*" && (i === 0 || body[i - 1] === "/")) { - if (body[i + 2] === "/") { - out += "(?:.*/)?"; - i += 2; - continue; - } - if (i + 2 === body.length) { - out += ".+"; - i += 1; - continue; - } - } - if (char === "*") { - while (body[i + 1] === "*") i++; - out += "[^/]*"; - } else if (char === "?") { - out += "[^/]"; - } else if (char === "\\" && i + 1 < body.length) { - out += literal(body[++i]); - } else if (char === "[") { - const found = charClass(body, i); - if (found) { - out += found.source; - i = found.end; - } else { - return null; // never closes: git's wildmatch matches nothing - } - } else { - out += literal(char); - } - } - try { - return new RegExp(`${out}$`); - } catch { - return null; - } - } - - /** The rules of one .gitignore, in order. */ - function rulesOf(text) { - const rules = []; - for (const raw of text.split(/\r\n?|\n/)) { - let line = raw; - // Trailing blanks do not count, unless the last is escaped. - let end = line.length; - while (end > 0 && (line[end - 1] === " " || line[end - 1] === "\t")) end--; - if (end < line.length && line[end - 1] === "\\") end++; - line = line.slice(0, end); - if (!line || line[0] === "#") continue; - const negated = line[0] === "!"; - if (negated) line = line.slice(1); - const dirOnly = line.endsWith("/"); - if (dirOnly) line = line.slice(0, -1); - if (!line) continue; - const regex = toRegExp(line); - if (regex) rules.push({ negated, dirOnly, regex }); - } - return rules; - } - - /** What the sources say of this path: the last rule that matches wins, deeper files last. */ - function decision(sources, path, isDir) { - let ignored = false; - for (const { dir, rules } of sources) { - if (dir && !path.startsWith(`${dir}/`)) continue; - const inside = dir ? path.slice(dir.length + 1) : path; - for (const rule of rules) { - if ((!rule.dirOnly || isDir) && rule.regex.test(inside)) ignored = !rule.negated; - } - } - return ignored; - } - - /** - * @param {{ dir: string, text: string }[]} sources .gitignore files, root first; `dir` is "" for the root - * @param {string} path relative to the root, with / - */ - function isIgnored(sources, path) { - const compiled = sources.map((source) => ({ dir: source.dir, rules: rulesOf(source.text) })); - const parts = path.split("/"); - // A file cannot be brought back when one of its folders is ignored. - for (let i = 1; i < parts.length; i++) { - if (decision(compiled, parts.slice(0, i).join("/"), true)) return true; - } - return decision(compiled, path, false); - } - - /** The .gitignore files that have a say on this path, root first. */ - function sourcesFor(path) { - const parts = path.split("/").slice(0, -1); - const out = [{ dir: "", path: ".gitignore" }]; - for (let i = 1; i <= parts.length; i++) { - const dir = parts.slice(0, i).join("/"); - out.push({ dir, path: `${dir}/.gitignore` }); - } - return out; - } - - /** The line that ignores this very file, for the root's .gitignore. */ - function patternFor(path) { - const escaped = path.replace(/[\\*?[]/g, "\\$&").replace(/ +$/, (spaces) => "\\ ".repeat(spaces.length)); - return /^[#!]/.test(escaped) ? `\\${escaped}` : escaped; - } - - /** The text with that line added, in the file's line endings. */ - function withPattern(text, pattern) { - const eol = text.includes("\r\n") ? "\r\n" : "\n"; - const closed = text === "" || /[\r\n]$/.test(text) ? text : text + eol; - return `${closed}${pattern}${eol}`; - } - - return { isIgnored, sourcesFor, patternFor, withPattern }; -}); diff --git a/tabs/editor/index.html b/tabs/editor/index.html deleted file mode 100644 index 1e8b3c4..0000000 --- a/tabs/editor/index.html +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - Editor - - - - -
- - - - - - - - - - - - - diff --git a/tabs/editor/logic.js b/tabs/editor/logic.js deleted file mode 100644 index 0570e1f..0000000 --- a/tabs/editor/logic.js +++ /dev/null @@ -1,387 +0,0 @@ -"use strict"; -// What is neither a file format nor the behaviour: the tab's words in en and fr, -// its params read like form input, and the picker's order. No DOM, no Hangar. -(function (root, factory) { - const dotenv = typeof module === "object" && module.exports ? require("./dotenv.js") : root.EditorDotenv; - const api = factory(dotenv); - if (typeof module === "object" && module.exports) module.exports = api; - else root.EditorLogic = api; -})(typeof globalThis !== "undefined" ? globalThis : this, function (dotenv) { - const STRINGS = { - en: { - tab: "Editor", - loading: "Loading…", - retry: "Try again", - back: "← Files", - pickTitle: "Choose a file", - pickFilter: "Filter by name", - groupEnv: "Environment files", - groupConfig: "Configuration files", - groupOther: "Other files", - pickEmpty: "No file matches.", - pickNew: "new", - pickTruncated: "This folder holds more files than Hangar lists: use the filter, or ask for the file by its path.", - pickMore: "{n} more: filter to find them.", - askedBy: "{pane} asks:", - askedAnon: "An agent asks:", - newFile: "This file does not exist yet. Saving creates it.", - save: "Save", - saving: "Saving…", - savedLocal: "Saved.", - nothingToSave: "Nothing to save yet.", - told: "{pane} was told, without any value.", - toldText: "{pane} was told the file changed.", - notTold: "Saved, but {pane} could not be told: {reason} No value was sent.", - tellAgain: "Tell {pane} again", - tellNoChange: "Tell {pane}: nothing to change", - toldNoChange: "{pane} was told you changed nothing.", - "tell.not_found": "that pane is gone.", - "tell.denied": "only a Claude Code agent can be told, and this tab must be granted panes.send.", - "tell.unavailable": "its session does not run Hangar's bridge.", - "tell.rate_limited": "too many messages this minute.", - "tell.other": "Hangar refused.", - leaveMessage: "Your changes are not saved.", - leaveConfirm: "Lose them", - leaveCancel: "Keep editing", - - keyMissing: "missing", - keyAsked: "asked", - keySet: "set", - keyChanged: "changed", - keyTwice: "Defined {n} times: this edits the last, the one that is read.", - valueHidden: "Hidden", - valueEmpty: "Empty", - valueLines: "Several lines", - show: "Show", - hide: "Hide", - offeredTitle: "In {file}, missing here", - add: "Add", - addAll: "Add all", - newKeyLabel: "Add a key", - newKeyPlaceholder: "KEY_NAME", - newKeyBad: "A key is letters, digits, _ . and -, not starting with a digit.", - newKeyTaken: "This key is already in the list.", - otherLines_one: "1 line that is not KEY=value is kept as it is.", - otherLines_other: "{n} lines that are not KEY=value are kept as they are.", - sectionAsked: "Asked for", - sectionFile: "In this file", - noKeys: "No key in this file yet.", - - ignoreWarning: "{file} is not ignored by git: git would commit it, secrets included.", - ignoreNoFile: "There is no .gitignore here: git would commit {file}, secrets included.", - ignoreUnknown: "Could not read .gitignore, so this tab cannot say whether git ignores {file}.", - ignoreAdd: "Add {pattern} to .gitignore", - ignoreAdding: "Adding…", - ignoreFailed: ".gitignore was not changed: {reason}", - - editorLabel: "File contents", - review: "Review changes", - backToEdit: "← Back to editing", - diffTitle: "Changes to save", - diffNone: "Nothing changed.", - diffSkip_one: "1 unchanged line", - diffSkip_other: "{n} unchanged lines", - stateNew: "New file", - checkOk: "Valid {kind}", - checkBasic: "{kind}: basic check", - checkBroken: "Broken {kind}", - checkBrokenAt: "Broken {kind}, line {line}", - checkPartial: "{kind}: no problem found. This is a basic check, not a proof.", - checkBad: "Broken {kind}: {reason}", - checkBadAt: "Broken {kind}, line {line}: {reason}", - ackBroken: "I know this file is broken: save it anyway.", - "check.json": "JSON cannot be read past this point.", - "check.yaml-tab": "a tab in the indentation. YAML indents with spaces.", - "check.yaml-quote": "a quote that never closes.", - "check.yaml-bracket": "a bracket that does not match.", - "check.yaml-reserved": "a value cannot start with @ or ` without quotes.", - "check.toml-trailing": "something follows the value on this line.", - "check.toml-string": "a string that never closes.", - "check.toml-escape": "an escape TOML does not know.", - "check.toml-key": "a key is expected here.", - "check.toml-equals": "a key must be followed by =.", - "check.toml-value": "this value cannot be read.", - "check.toml-header": "a table header that does not close.", - "check.toml-duplicate": "this key or table is given twice.", - lineJumpFar: "Line {line} was asked for; the file has {total}.", - - conflictTitle: "This file changed while you were editing it", - conflictHint: "Nothing was written. Choose what to keep.", - conflictGone: "The file was deleted while you were editing it. Nothing was written.", - conflictDiff: "− on disk now + yours", - conflictKeepMine: "Replace it with mine", - conflictWriteMine: "Write mine", - conflictTakeTheirs: "Keep what is on disk, lose mine", - conflictEdit: "Back to editing, with mine", - conflictRows: "Keys that differ", - conflictNone: "No key disagrees: your changes can go in the new file as they are.", - conflictApply: "Save with these choices", - conflictTheirsChanged_one: "1 other key changed on disk, and stays as it is there.", - conflictTheirsChanged_other: "{n} other keys changed on disk, and stay as they are there.", - stateConflict: "Changed on disk", - mine: "Yours", - theirs: "On disk", - absent: "absent", - - "err.denied.title": "This tab may not read or write here", - "err.denied.hint": "Accept files.read and files.write for this kit in Settings › Kits.", - "err.invalid.title": "Hangar refused this path", - "err.invalid.hint": "A hidden file needs both files.read and files.write. The path must stay inside the workspace folder, outside .git.", - "err.bad-path.title": "This path cannot be opened", - "err.bad-path.hint": "The path must be relative to the workspace folder, with no .. and no drive, outside .git.", - "err.failed.title": "This file cannot be opened", - "err.failed.hint": "Only UTF-8 text files of 1 MB at most can be opened here.", - "err.unavailable.title": "Hangar cannot do this now", - "err.unavailable.hint": "The workspace or its folder may be gone. Reload the tab in a moment.", - "err.timeout.title": "Hangar did not answer in time", - "err.timeout.hint": "Try again.", - "err.error.title": "Something went wrong", - "err.error.hint": "Hangar said:", - "write.denied": "this tab was not granted files.write. Your changes are still here.", - "write.rate_limited": "at most 10 saves a minute. Your changes are still here: try again shortly.", - "write.invalid": "Hangar refused it (a file holds 1 MB at most). Your changes are still here.", - "write.other": "it could not be written. Your changes are still here.", - "write.conflict": ".gitignore changed in the meantime. Click again to use the new one.", - badgeMissing: "{n} missing", - stateMissing_one: "{n} missing", - stateMissing_other: "{n} missing", - stateSaved: "Saved", - badgeSaved: "saved", - }, - fr: { - tab: "Éditeur", - loading: "Chargement…", - retry: "Réessayer", - back: "← Fichiers", - pickTitle: "Choisir un fichier", - pickFilter: "Filtrer par nom", - groupEnv: "Fichiers d'environnement", - groupConfig: "Fichiers de configuration", - groupOther: "Autres fichiers", - pickEmpty: "Aucun fichier ne correspond.", - pickNew: "nouveau", - pickTruncated: "Ce dossier contient plus de fichiers que Hangar n'en liste : utilisez le filtre, ou demandez le fichier par son chemin.", - pickMore: "{n} de plus : filtrez pour les trouver.", - askedBy: "{pane} demande :", - askedAnon: "Un agent demande :", - newFile: "Ce fichier n'existe pas encore. L'enregistrer le crée.", - save: "Enregistrer", - saving: "Enregistrement…", - savedLocal: "Enregistré.", - nothingToSave: "Rien à enregistrer pour l'instant.", - told: "{pane} a été prévenu, sans aucune valeur.", - toldText: "{pane} a été prévenu que le fichier a changé.", - notTold: "Enregistré, mais {pane} n'a pas pu être prévenu : {reason} Aucune valeur n'a été envoyée.", - tellAgain: "Prévenir {pane} à nouveau", - tellNoChange: "Dire à {pane} : rien à changer", - toldNoChange: "{pane} sait que vous n'avez rien changé.", - "tell.not_found": "ce panneau n'existe plus.", - "tell.denied": "seul un agent Claude Code peut être prévenu, et cet onglet doit avoir panes.send.", - "tell.unavailable": "sa session ne fait pas tourner le pont de Hangar.", - "tell.rate_limited": "trop de messages cette minute.", - "tell.other": "Hangar a refusé.", - leaveMessage: "Vos changements ne sont pas enregistrés.", - leaveConfirm: "Les perdre", - leaveCancel: "Continuer à modifier", - - keyMissing: "manquante", - keyAsked: "demandée", - keySet: "remplie", - keyChanged: "modifiée", - keyTwice: "Définie {n} fois : ceci modifie la dernière, celle qui est lue.", - valueHidden: "Masquée", - valueEmpty: "Vide", - valueLines: "Plusieurs lignes", - show: "Afficher", - hide: "Masquer", - offeredTitle: "Dans {file}, absentes ici", - add: "Ajouter", - addAll: "Tout ajouter", - newKeyLabel: "Ajouter une clé", - newKeyPlaceholder: "NOM_DE_CLÉ", - newKeyBad: "Une clé s'écrit avec des lettres, des chiffres, _ . et -, sans commencer par un chiffre.", - newKeyTaken: "Cette clé est déjà dans la liste.", - otherLines_one: "1 ligne qui n'est pas de la forme CLÉ=valeur reste telle quelle.", - otherLines_other: "{n} lignes qui ne sont pas de la forme CLÉ=valeur restent telles quelles.", - sectionAsked: "Demandées", - sectionFile: "Dans ce fichier", - noKeys: "Aucune clé dans ce fichier pour l'instant.", - - ignoreWarning: "{file} n'est pas ignoré par git : git le committerait, secrets compris.", - ignoreNoFile: "Il n'y a pas de .gitignore ici : git committerait {file}, secrets compris.", - ignoreUnknown: "Le .gitignore n'a pas pu être lu : cet onglet ne peut pas dire si git ignore {file}.", - ignoreAdd: "Ajouter {pattern} au .gitignore", - ignoreAdding: "Ajout…", - ignoreFailed: "Le .gitignore n'a pas été modifié : {reason}", - - editorLabel: "Contenu du fichier", - review: "Voir les changements", - backToEdit: "← Revenir à l'édition", - diffTitle: "Changements à enregistrer", - diffNone: "Rien n'a changé.", - diffSkip_one: "1 ligne inchangée", - diffSkip_other: "{n} lignes inchangées", - stateNew: "Nouveau fichier", - checkOk: "{kind} valide", - checkBasic: "{kind} : vérification de base", - checkBroken: "{kind} cassé", - checkBrokenAt: "{kind} cassé, ligne {line}", - checkPartial: "{kind} : aucun problème trouvé. C'est une vérification de base, pas une preuve.", - checkBad: "{kind} cassé : {reason}", - checkBadAt: "{kind} cassé, ligne {line} : {reason}", - ackBroken: "Je sais que ce fichier est cassé : l'enregistrer quand même.", - "check.json": "le JSON n'est plus lisible à partir d'ici.", - "check.yaml-tab": "une tabulation dans l'indentation. YAML indente avec des espaces.", - "check.yaml-quote": "un guillemet jamais refermé.", - "check.yaml-bracket": "un crochet ou une accolade qui ne correspond pas.", - "check.yaml-reserved": "une valeur ne peut pas commencer par @ ou ` sans guillemets.", - "check.toml-trailing": "quelque chose suit la valeur sur cette ligne.", - "check.toml-string": "une chaîne jamais refermée.", - "check.toml-escape": "un échappement que TOML ne connaît pas.", - "check.toml-key": "une clé est attendue ici.", - "check.toml-equals": "une clé doit être suivie de =.", - "check.toml-value": "cette valeur n'est pas lisible.", - "check.toml-header": "un en-tête de table qui ne se referme pas.", - "check.toml-duplicate": "cette clé ou cette table apparaît deux fois.", - lineJumpFar: "La ligne {line} était demandée ; le fichier en a {total}.", - - conflictTitle: "Ce fichier a changé pendant que vous le modifiiez", - conflictHint: "Rien n'a été écrit. Choisissez ce que vous gardez.", - conflictGone: "Le fichier a été supprimé pendant que vous le modifiiez. Rien n'a été écrit.", - conflictDiff: "− sur le disque + le vôtre", - conflictKeepMine: "Le remplacer par le mien", - conflictWriteMine: "Écrire le mien", - conflictTakeTheirs: "Garder celui du disque, perdre le mien", - conflictEdit: "Revenir à l'édition, avec le mien", - conflictRows: "Clés qui diffèrent", - conflictNone: "Aucune clé ne diverge : vos changements peuvent aller tels quels dans le nouveau fichier.", - conflictApply: "Enregistrer avec ces choix", - conflictTheirsChanged_one: "1 autre clé a changé sur le disque, et y reste telle quelle.", - conflictTheirsChanged_other: "{n} autres clés ont changé sur le disque, et y restent telles quelles.", - stateConflict: "Modifié sur le disque", - mine: "La vôtre", - theirs: "Sur le disque", - absent: "absente", - - "err.denied.title": "Cet onglet n'a pas le droit de lire ou d'écrire ici", - "err.denied.hint": "Acceptez files.read et files.write pour ce kit dans Réglages › Kits.", - "err.invalid.title": "Hangar a refusé ce chemin", - "err.invalid.hint": "Un fichier caché demande files.read et files.write à la fois. Le chemin doit rester dans le dossier de l'espace de travail, hors de .git.", - "err.bad-path.title": "Ce chemin ne peut pas être ouvert", - "err.bad-path.hint": "Le chemin doit être relatif au dossier de l'espace de travail, sans .. ni lecteur, hors de .git.", - "err.failed.title": "Ce fichier ne peut pas être ouvert", - "err.failed.hint": "Seuls les fichiers texte UTF-8 de 1 Mo au plus s'ouvrent ici.", - "err.unavailable.title": "Hangar ne peut pas le faire maintenant", - "err.unavailable.hint": "L'espace de travail ou son dossier n'existe peut-être plus. Rechargez l'onglet dans un instant.", - "err.timeout.title": "Hangar n'a pas répondu à temps", - "err.timeout.hint": "Réessayez.", - "err.error.title": "Quelque chose s'est mal passé", - "err.error.hint": "Hangar a dit :", - "write.denied": "cet onglet n'a pas reçu files.write. Vos changements sont toujours là.", - "write.rate_limited": "10 enregistrements par minute au plus. Vos changements sont toujours là : réessayez bientôt.", - "write.invalid": "Hangar a refusé (un fichier fait 1 Mo au plus). Vos changements sont toujours là.", - "write.other": "il n'a pas pu être écrit. Vos changements sont toujours là.", - "write.conflict": "le .gitignore a changé entre-temps. Cliquez à nouveau pour partir du nouveau.", - badgeMissing: "{n} à remplir", - stateMissing_one: "{n} manquante", - stateMissing_other: "{n} manquantes", - stateSaved: "Enregistré", - badgeSaved: "enregistré", - }, - }; - - const pickLang = (language) => (String(language || "").toLowerCase().startsWith("fr") ? "fr" : "en"); - - /** The words outside a tab. In one, `hangar.ui.i18n(STRINGS)` gives the same, typeset. */ - function t(lang, key, vars) { - const form = vars && typeof vars.n === "number" ? `${key}_${new Intl.PluralRules(lang).select(vars.n)}` : key; - const text = (STRINGS[lang] && (STRINGS[lang][form] || STRINGS[lang][key])) || STRINGS.en[form] || STRINGS.en[key] || key; - if (!vars) return text; - return text.replace(/\{(\w+)\}/g, (whole, name) => (vars[name] === undefined ? whole : String(vars[name]))); - } - - const baseName = (path) => path.slice(path.lastIndexOf("/") + 1); - - /** A name for the tab strip: one line, 40 characters at most, an emoji counting as one. */ - const tabTitle = (path) => Array.from(baseName(path)).slice(0, 40).join(""); - - /** - * The path in `/` form, or null when Hangar would refuse it. Hangar checks it again; - * this is so that a path a caller got wrong is said to be wrong, not read as a failure. - */ - function checkPath(raw) { - if (typeof raw !== "string" || raw.trim() === "" || raw.length > 1024) return null; - if (/[\u0000-\u001f\u007f]/.test(raw)) return null; - if (/^[/\\]/.test(raw)) return null; - const parts = raw.split(/[/\\]/).filter((part) => part !== "" && part !== "."); - if (!parts.length) return null; - for (const part of parts) { - if (part === ".." || part.includes(":") || part.toLowerCase() === ".git" || /[. ]$/.test(part)) return null; - } - return parts.join("/"); - } - - /** `keys` is one string: names separated by commas. What is not a key name is dropped. */ - function parseKeys(raw) { - if (typeof raw !== "string") return []; - return [...new Set(raw.split(",").map((key) => key.trim()).filter(dotenv.isKey))]; - } - - function parseLine(raw) { - if (typeof raw !== "string" || !/^[1-9][0-9]{0,8}$/.test(raw)) return null; - return Number(raw); - } - - /** What `tab.params` said, read as anything typed into a form. */ - function readParams(message) { - const params = (message && message.params) || {}; - const given = typeof params.path === "string" && params.path !== ""; - const path = given ? checkPath(params.path) : null; - const why = typeof params.why === "string" && params.why.trim() ? params.why.trim() : null; - const caller = - message && message.caller && typeof message.caller.pane === "string" && message.caller.pane - ? { pane: message.caller.pane } - : null; - return { path, badPath: given && !path, keys: parseKeys(params.keys), why, line: parseLine(params.line), caller }; - } - - /* ── the picker ───────────────────────────────────────────────── */ - - const CONFIG_EXTENSION = /\.(json|jsonc|json5|ya?ml|toml|ini|cfg|conf|config|properties|xml|plist)$/i; - const CONFIG_NAME = /^(\.[\w.-]*(rc|ignore|config|attributes)|dockerfile|.*\.dockerfile|docker-compose\..*)$/i; - const GENERATED = /(^|[-.])lock(\.[a-z]+)?$|^package-lock\.json$|^pnpm-lock\.yaml$|^yarn\.lock$/i; - const NOT_TEXT = /\.(png|jpe?g|gif|webp|avif|bmp|ico|tiff?|pdf|zip|gz|tgz|bz2|xz|7z|rar|tar|exe|dll|so|dylib|bin|class|o|obj|a|lib|wasm|woff2?|ttf|otf|eot|mp[34]|wav|ogg|m4a|webm|mov|avi|mkv|sqlite3?|db|pyc|node)$/i; - const SHOWN_PER_GROUP = 200; - - function classify(path) { - const name = baseName(path); - if (NOT_TEXT.test(name)) return null; - if (dotenv.isDotenvPath(path)) return "env"; - if (GENERATED.test(name)) return "other"; - return CONFIG_EXTENSION.test(name) || CONFIG_NAME.test(name) ? "config" : "other"; - } - - /** Env files first, then configuration, in Hangar's order (the nearest first); what is not text is left out. */ - function rankFiles(files) { - const groups = { env: [], config: [], other: [] }; - for (const file of files || []) { - if (!file || typeof file.path !== "string") continue; - const group = classify(file.path); - if (group) groups[group].push({ path: file.path, isNew: false }); - } - // The file an agent or a person usually wants is the one that is not there yet. - if (!groups.env.some((file) => file.path === ".env")) groups.env.unshift({ path: ".env", isNew: true }); - return groups; - } - - /** The groups a filter leaves, each cut to what a page can hold, saying how many it cut. */ - function filterGroups(groups, query) { - const needle = String(query || "").trim().toLowerCase(); - return ["env", "config", "other"].map((id) => { - const all = groups[id].filter((file) => file.path.toLowerCase().includes(needle)); - return { id, files: all.slice(0, SHOWN_PER_GROUP), more: Math.max(0, all.length - SHOWN_PER_GROUP) }; - }); - } - - return { STRINGS, pickLang, t, baseName, tabTitle, checkPath, parseKeys, parseLine, readParams, classify, rankFiles, filterGroups }; -}); diff --git a/tabs/editor/style.css b/tabs/editor/style.css deleted file mode 100644 index 7bccff6..0000000 --- a/tabs/editor/style.css +++ /dev/null @@ -1,73 +0,0 @@ -/* What Hangar UI has no component for: the editor and the shape of a key's row. - Layout and tokens only: every colour is one of /_hangar/kit.css's. */ -#app { display: contents; } - -.editor-column { display: flex; flex-direction: column; overflow: hidden; } -.editor-notes { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--kit-space-6); padding: var(--kit-space-8) var(--kit-space-12); } -.editor-note, .editor-reason { margin: 0; padding: 0 var(--kit-space-2); } -.editor-reason { overflow-wrap: anywhere; } -.editor-reason--bad { color: var(--kit-danger); } - -/* A gutter and a text area that scroll as one: same font, same line height. */ -.editor-code { display: flex; border-top: 1px solid var(--kit-line); background: var(--kit-well); overflow: hidden; } -.editor-gutter, .editor-area { - margin: 0; - padding: var(--kit-space-8) 0; - border: 0; - font-family: var(--kit-mono); - font-size: var(--kit-fs-code); - font-variant-ligatures: none; - line-height: calc(18px * var(--kit-scale)); -} -.editor-gutter { - flex: none; - min-width: 4ch; - padding-inline: var(--kit-space-8) var(--kit-space-6); - overflow: hidden; - color: var(--kit-text-muted); - font-variant-numeric: tabular-nums; - text-align: right; - user-select: none; -} -.editor-gutter__mark { display: inline-block; width: 100%; background: var(--kit-selected); color: var(--kit-text); font-weight: 600; } -.editor-area { - flex: 1; - min-width: 0; - padding-inline: var(--kit-space-8); - overflow: auto; - border-left: 1px solid var(--kit-line); - outline: none; - resize: none; - background: transparent; - color: var(--kit-text); - tab-size: 2; - white-space: pre; -} -.editor-area:focus-visible { box-shadow: inset 0 0 0 1px var(--kit-focus); } - -.editor-diff { --kit-log-height: none; } -.editor-add { - background: color-mix(in srgb, var(--kit-ok-fill) 10%, var(--kit-well)); - box-shadow: inset 2px 0 0 var(--kit-ok-fill); -} -.editor-add .kit-log__num { color: var(--kit-text-dim); } - -/* A key: its name and what is known of it, then its value and the button that shows it. */ -.editor-key__main { gap: var(--kit-space-4); } -.editor-key__name { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: var(--kit-space-2) var(--kit-space-6); min-height: var(--kit-h-small); } -.editor-key__name .kit-row__title { flex: 0 1 auto; min-width: 0; overflow-wrap: anywhere; } -.editor-key__mark { display: inline-flex; flex: none; } -.editor-key__value { display: flex; align-items: flex-start; gap: var(--kit-space-4); } -.editor-key__value .kit-input { flex: 1; min-width: 0; } -.editor-key__value .kit-btn { flex: none; } - -.editor-choice { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--kit-space-2) var(--kit-space-6); cursor: pointer; } -.editor-choice input { accent-color: var(--kit-accent); } -.editor-choice__side { font-size: var(--kit-fs-meta); } -.editor-value { min-width: 0; white-space: pre-wrap; } - -.editor-wide { flex-basis: 100%; } -.kit-banner .kit-switch { align-items: flex-start; white-space: normal; } - -.editor-foot { padding-block: var(--kit-space-6); } -.editor-foot__status { flex: 1 1 calc(120px * var(--kit-scale)); min-width: 0; overflow-wrap: anywhere; } diff --git a/tabs/editor/validate.js b/tabs/editor/validate.js deleted file mode 100644 index 0977511..0000000 --- a/tabs/editor/validate.js +++ /dev/null @@ -1,520 +0,0 @@ -"use strict"; -// Is this file broken? JSON is checked by JSON.parse, so "valid" means valid. TOML -// is parsed for its syntax, and YAML is only scanned for what is certainly wrong; -// both answer `partial: true`, and the page says it is a basic check. An error -// gives a code the page translates, and a line when one can be told. -(function (root, factory) { - const api = factory(); - if (typeof module === "object" && module.exports) module.exports = api; - else root.EditorValidate = api; -})(typeof globalThis !== "undefined" ? globalThis : this, function () { - const baseName = (path) => path.slice(path.lastIndexOf("/") + 1).toLowerCase(); - - /** Which check applies: json, jsonc, yaml, toml, or null for none. */ - function checkerFor(path) { - const name = baseName(path); - if (/\.jsonc$|\.code-workspace$/.test(name)) return "jsonc"; - if (/\.json$/.test(name)) { - // These are read with comments and trailing commas by what uses them. - if (/^(tsconfig|jsconfig)([.-].*)?\.json$|^\.eslintrc\.json$|^devcontainer\.json$|^\.devcontainer\.json$/.test(name)) return "jsonc"; - if (/(^|\/)\.vscode\//i.test(path) || /(^|\/)\.devcontainer\//i.test(path)) return "jsonc"; - return "json"; - } - if (/\.ya?ml$/.test(name)) return "yaml"; - if (/\.toml$/.test(name)) return "toml"; - return null; - } - - function lineOf(text, at) { - let line = 1; - let start = 0; - const limit = Math.min(at, text.length); - for (let i = 0; i < limit; i++) { - if (text[i] === "\n") { - line++; - start = i + 1; - } - } - return { line, column: limit - start + 1 }; - } - - /* ── JSON ─────────────────────────────────────────────────────── */ - - /** Comments and trailing commas blanked, every other character where it was. */ - function blankJsonc(text) { - const out = text.split(""); - const blank = (from, to) => { - for (let i = from; i < to; i++) if (out[i] !== "\n" && out[i] !== "\r") out[i] = " "; - }; - let lastComma = -1; - for (let i = 0; i < text.length; i++) { - const char = text[i]; - if (char === '"') { - for (i++; i < text.length && text[i] !== '"'; i++) if (text[i] === "\\") i++; - lastComma = -1; - } else if (char === "/" && text[i + 1] === "/") { - let end = i; - while (end < text.length && text[end] !== "\n") end++; - blank(i, end); - i = end - 1; - } else if (char === "/" && text[i + 1] === "*") { - const close = text.indexOf("*/", i + 2); - const end = close < 0 ? text.length : close + 2; - blank(i, end); - i = end - 1; - } else if (char === ",") { - lastComma = i; - } else if (char === "]" || char === "}") { - if (lastComma >= 0) out[lastComma] = " "; - lastComma = -1; - } else if (!/\s/.test(char)) { - lastComma = -1; - } - } - return out.join(""); - } - - /** - * Where JSON goes wrong. JSON.parse is what says it does; engines differ on saying - * where (WebKit never does, V8 only sometimes), so this walks the text to find it. - */ - function jsonErrorAt(text) { - let i = 0; - const stop = () => { - throw { json: true }; - }; - const blanks = () => { - while (i < text.length && " \t\r\n".includes(text[i])) i++; - }; - const SCALAR = /-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null/y; - function string() { - i++; - for (;;) { - if (i >= text.length || text.charCodeAt(i) < 0x20) stop(); - if (text[i] === '"') { - i++; - return; - } - if (text[i] === "\\") { - const next = text[i + 1]; - if (next === "u") { - if (!/^[0-9A-Fa-f]{4}$/.test(text.slice(i + 2, i + 6))) stop(); - i += 6; - } else if (next !== undefined && '"\\/bfnrt'.includes(next)) { - i += 2; - } else { - stop(); - } - } else { - i++; - } - } - } - function value() { - blanks(); - const char = text[i]; - if (char === '"') return string(); - if (char === "[" || char === "{") { - const close = char === "[" ? "]" : "}"; - i++; - blanks(); - if (text[i] === close) { - i++; - return undefined; - } - for (;;) { - blanks(); - if (char === "{") { - if (text[i] !== '"') stop(); - string(); - blanks(); - if (text[i] !== ":") stop(); - i++; - } - value(); - blanks(); - if (text[i] === close) { - i++; - return undefined; - } - if (text[i] !== ",") stop(); - i++; - } - } - SCALAR.lastIndex = i; - const match = SCALAR.exec(text); - if (!match) stop(); - i += match[0].length; - return undefined; - } - try { - value(); - blanks(); - return i < text.length ? i : null; - } catch (error) { - return error && error.json ? i : null; // too deep to walk: JSON.parse's word stands, without a line - } - } - - function checkJson(text, kind) { - const source = kind === "jsonc" ? blankJsonc(text) : text; - try { - JSON.parse(source); - return { kind, ok: true, partial: false }; - } catch { - const at = jsonErrorAt(source); - return { kind, ok: false, partial: false, code: "json", ...(at === null ? {} : lineOf(source, at)) }; - } - } - - /* ── YAML: only what is certainly wrong ───────────────────────── */ - - function checkYaml(text) { - const lines = text.split(/\r\n?|\n/); - const closes = { "[": "]", "{": "}" }; - const flow = []; - let quote = null; - let blockIndent = null; - let plainIndent = null; // the indent of the line that ended in a plain scalar, which may go on below - const fail = (code, line, column) => ({ kind: "yaml", ok: false, partial: true, code, line, column }); - - for (let n = 0; n < lines.length; n++) { - const line = lines[n]; - let at = 0; - let start = true; // a token may start here: a quote or a bracket means something - - if (!quote && !flow.length) { - const lead = /^[ \t]*/.exec(line)[0]; - const rest = line.slice(lead.length); - const indent = /^ */.exec(line)[0].length; // only spaces indent: that is the rule being checked - if (rest === "") continue; - if (blockIndent !== null) { - if (indent > blockIndent) continue; - blockIndent = null; - } - if (rest[0] === "#") continue; - if (plainIndent !== null && indent > plainIndent) continue; - plainIndent = null; - if (lead.includes("\t")) return fail("yaml-tab", n + 1, lead.indexOf("\t") + 1); - if (line[0] === "%") continue; - at = lead.length; - if (/^(---|\.\.\.)([ \t]|$)/.test(rest)) at += 3; - } - - let plain = false; - const lineIndent = /^ */.exec(line)[0].length; - for (; at < line.length; at++) { - const char = line[at]; - if (quote) { - if (quote.char === '"' && char === "\\") at++; - else if (char === quote.char) { - if (quote.char === "'" && line[at + 1] === "'") at++; - else quote = null; - } - plain = false; - start = false; - continue; - } - const previous = line[at - 1]; - const next = line[at + 1]; - const blankNext = next === undefined || next === " " || next === "\t"; - if (char === " " || char === "\t") continue; - if (char === "#" && (previous === undefined || previous === " " || previous === "\t")) break; - if (start) { - if (char === '"' || char === "'") { - quote = { char, line: n + 1, column: at + 1 }; - start = false; - continue; - } - if (char === "[" || char === "{") { - flow.push({ char, line: n + 1, column: at + 1 }); - continue; - } - if ((char === "]" || char === "}") && !flow.length) return fail("yaml-bracket", n + 1, at + 1); - if (!flow.length && (char === "|" || char === ">") && /^[|>][-+0-9]*[ \t]*(#.*)?$/.test(line.slice(at))) { - blockIndent = lineIndent; - plain = false; - break; - } - if ((char === "&" || char === "!") && !blankNext) { - while (at + 1 < line.length && line[at + 1] !== " " && line[at + 1] !== "\t") at++; - continue; - } - if ((char === "-" || char === "?" || char === ":") && blankNext) continue; - if (char === "@" || char === "`") return fail("yaml-reserved", n + 1, at + 1); - start = false; - plain = true; - } - if (char === ":" && (blankNext || (flow.length && ",[]{}".includes(next)))) { - start = true; - plain = false; - } else if (flow.length) { - if (char === ",") { - start = true; - plain = false; - } else if (char === ":" && previous === '"') { - start = true; - plain = false; - } else if (char === "]" || char === "}") { - const open = flow.pop(); - if (closes[open.char] !== char) return fail("yaml-bracket", n + 1, at + 1); - plain = false; - } - } - } - plainIndent = plain && !quote && !flow.length ? lineIndent : null; - } - if (quote) return fail("yaml-quote", quote.line, quote.column); - if (flow.length) { - const open = flow[flow.length - 1]; - return fail("yaml-bracket", open.line, open.column); - } - return { kind: "yaml", ok: true, partial: true }; - } - - /* ── TOML: its syntax, and keys or tables given twice ─────────── */ - - const NUMBER_OR_DATE = new RegExp( - [ - "[+-]?(?:inf|nan)", - "0x[0-9A-Fa-f](?:_?[0-9A-Fa-f])*", - "0o[0-7](?:_?[0-7])*", - "0b[01](?:_?[01])*", - "\\d{4}-\\d{2}-\\d{2}(?:[Tt ]\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:[Zz]|[+-]\\d{2}:\\d{2})?)?", - "\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?", - "[+-]?(?:0|[1-9](?:_?\\d)*)(?:\\.\\d(?:_?\\d)*)?(?:[eE][+-]?\\d(?:_?\\d)*)?", - ].join("|"), - "y", - ); - - function checkToml(text) { - let i = 0; - const stop = (code, at = i) => { - throw { toml: code, at }; - }; - const blanks = () => { - while (text[i] === " " || text[i] === "\t") i++; - }; - const comment = () => { - if (text[i] === "#") while (i < text.length && text[i] !== "\n") i++; - }; - const atEol = () => i >= text.length || text[i] === "\n" || (text[i] === "\r" && text[i + 1] === "\n"); - const endOfLine = () => { - blanks(); - comment(); - if (!atEol()) stop("toml-trailing"); - i += text[i] === "\r" ? 2 : 1; - }; - const skipBlankLines = () => { - for (;;) { - blanks(); - comment(); - if (i >= text.length || !atEol()) return; - i += text[i] === "\r" ? 2 : 1; - } - }; - - function basicString(multi) { - const open = i; - i += multi ? 3 : 1; - for (;;) { - if (i >= text.length) stop("toml-string", open); - const char = text[i]; - if (multi && text.startsWith('"""', i)) { - i += 3; - while (text[i] === '"' && i - open < text.length) i++; - return; - } - if (!multi && char === '"') { - i++; - return; - } - if (!multi && (char === "\n" || char === "\r")) stop("toml-string", open); - if (char === "\\") { - const next = text[i + 1]; - if ("btnfr\"\\".includes(next || "?")) i += 2; - else if (next === "u" && /^[0-9A-Fa-f]{4}$/.test(text.slice(i + 2, i + 6))) i += 6; - else if (next === "U" && /^[0-9A-Fa-f]{8}$/.test(text.slice(i + 2, i + 10))) i += 10; - else if (multi && /^\\[ \t]*\r?\n/.test(text.slice(i, i + 200))) i += 2; - else stop("toml-escape"); - } else { - i++; - } - } - } - - function literalString(multi) { - const open = i; - i += multi ? 3 : 1; - for (;;) { - if (i >= text.length) stop("toml-string", open); - if (multi && text.startsWith("'''", i)) { - i += 3; - while (text[i] === "'") i++; - return; - } - if (!multi && text[i] === "'") { - i++; - return; - } - if (!multi && (text[i] === "\n" || text[i] === "\r")) stop("toml-string", open); - i++; - } - } - - /** One part of a key; returns it, for telling duplicates. */ - function keyPart() { - const open = i; - if (text[i] === '"') { - basicString(false); - return text.slice(open, i); - } - if (text[i] === "'") { - literalString(false); - return text.slice(open, i); - } - while (i < text.length && /[A-Za-z0-9_-]/.test(text[i])) i++; - if (i === open) stop("toml-key"); - return text.slice(open, i); - } - - function key() { - const parts = [keyPart()]; - for (;;) { - blanks(); - if (text[i] !== ".") return parts; - i++; - blanks(); - parts.push(keyPart()); - } - } - - function arrayGap() { - for (;;) { - blanks(); - comment(); - if (i < text.length && atEol()) i += text[i] === "\r" ? 2 : 1; - else return; - } - } - - function array() { - const open = i; - i++; - arrayGap(); - while (text[i] !== "]") { - if (i >= text.length) stop("toml-value", open); - value(); - arrayGap(); - if (text[i] === ",") { - i++; - arrayGap(); - } else if (text[i] !== "]") { - stop("toml-value", i >= text.length ? open : i); - } - } - i++; - } - - function inlineTable() { - i++; - blanks(); - if (text[i] === "}") { - i++; - return; - } - for (;;) { - key(); - if (text[i] !== "=") stop("toml-equals"); - i++; - blanks(); - value(); - blanks(); - if (text[i] === ",") { - i++; - blanks(); - } else if (text[i] === "}") { - i++; - return; - } else { - stop("toml-value"); - } - } - } - - function value() { - if (text.startsWith('"""', i)) return basicString(true); - if (text.startsWith("'''", i)) return literalString(true); - if (text[i] === '"') return basicString(false); - if (text[i] === "'") return literalString(false); - if (text[i] === "[") return array(); - if (text[i] === "{") return inlineTable(); - if (text.startsWith("true", i) || text.startsWith("false", i)) { - i += text[i] === "t" ? 4 : 5; - } else { - NUMBER_OR_DATE.lastIndex = i; - const match = NUMBER_OR_DATE.exec(text); - if (!match || !match[0]) stop("toml-value"); - i += match[0].length; - } - if (i < text.length && !/[\s,\]}#]/.test(text[i])) stop("toml-value"); - return undefined; - } - - const seen = new Set(); - let table = ""; - try { - for (;;) { - skipBlankLines(); - if (i >= text.length) break; - const start = i; - if (text[i] === "[") { - const isArray = text[i + 1] === "["; - i += isArray ? 2 : 1; - blanks(); - const name = key().join("\u0000"); - if (text[i] !== "]" || (isArray && text[i + 1] !== "]")) stop("toml-header"); - i += isArray ? 2 : 1; - endOfLine(); - if (isArray) { - // Each [[item]] is a table of its own: its keys may repeat those of the last. - for (const other of [...seen]) { - if (other.startsWith(`${name}\u0000`) || other.startsWith(`[${name}\u0000`)) seen.delete(other); - } - } else { - if (seen.has(`[${name}]`)) stop("toml-duplicate", start); - seen.add(`[${name}]`); - } - table = name; - } else { - const name = key().join("\u0000"); - if (text[i] !== "=") stop("toml-equals"); - i++; - blanks(); - value(); - endOfLine(); - const whole = table ? `${table}\u0000${name}` : name; - if (seen.has(whole)) stop("toml-duplicate", start); - seen.add(whole); - } - } - } catch (error) { - if (!error || !error.toml) throw error; - return { kind: "toml", ok: false, partial: true, code: error.toml, ...lineOf(text, error.at) }; - } - return { kind: "toml", ok: true, partial: true }; - } - - /** - * @returns {{ kind: string|null, ok: boolean, partial: boolean, code?: string, line?: number, column?: number }} - */ - function validate(path, text) { - const kind = checkerFor(path); - if (kind === "json" || kind === "jsonc") return checkJson(text, kind); - if (kind === "yaml") return checkYaml(text); - if (kind === "toml") return checkToml(text); - return { kind: null, ok: true, partial: false }; - } - - return { validate, checkerFor }; -}); diff --git a/tabs/editor/view.js b/tabs/editor/view.js deleted file mode 100644 index 1970cd5..0000000 --- a/tabs/editor/view.js +++ /dev/null @@ -1,765 +0,0 @@ -"use strict"; -// Draws the controller's state with Hangar UI's classes (docs/kit-ui.md). Only -// elements made by hand and text: nothing a file or a caller said is parsed as -// markup. `render` answers a function that refreshes what typing changes, so a -// keystroke never rebuilds the field being typed in. -(function (root, factory) { - const api = factory(); - if (typeof module === "object" && module.exports) module.exports = api; - else root.EditorView = api; -})(typeof globalThis !== "undefined" ? globalThis : this, function () { - const MASK = "••••••••"; - const VALUE_LINES_MAX = 8; - - function make(doc, tag, className, text) { - const element = doc.createElement(tag); - if (className) element.className = className; - if (text !== undefined && text !== null) element.textContent = text; - return element; - } - - function button(doc, label, className, handler, focusId) { - const element = make(doc, "button", className ? `kit-btn ${className}` : "kit-btn", label); - element.type = "button"; - element.onclick = handler; - if (focusId) element.setAttribute("data-focus", focusId); - return element; - } - - function dirName(path) { - const slash = path.lastIndexOf("/"); - return slash < 0 ? "" : path.slice(0, slash + 1); - } - - function focusedId(doc) { - const active = doc.activeElement; - return active && typeof active.getAttribute === "function" ? active.getAttribute("data-focus") : null; - } - - function isSaveKey(event) { - return (event.ctrlKey || event.metaKey) && !event.altKey && String(event.key).toLowerCase() === "s"; - } - - /** @param {{ doc, t, logic, actions, confirm?: Function }} ctx */ - function render(container, state, ctx) { - const { doc, t, logic, actions } = ctx; - const memory = ctx.memory || (ctx.memory = {}); - const keepFocus = focusedId(doc); - const updaters = []; - const afterAttach = []; - - const small = (label, kind, handler, focusId) => button(doc, label, `kit-btn--small ${kind || ""}`.trim(), handler, focusId); - - function banner(kind, text, action) { - const element = make(doc, "p", kind ? `kit-banner kit-banner--${kind}` : "kit-banner"); - if (kind === "error") element.setAttribute("role", "alert"); - element.append(make(doc, "span", "kit-banner__text", text)); - if (action) { - const holder = make(doc, "span", "kit-banner__action"); - holder.append(action); - element.append(holder); - } - return element; - } - - /** The part that scrolls, and the padded column inside it. */ - function scroller() { - const outer = make(doc, "main", "kit-grow"); - const page = make(doc, "div", "kit-page"); - outer.append(page); - return { outer, page }; - } - - function stateWord(kind, word) { - return make(doc, "span", `kit-state kit-state--${kind}`, word); - } - - function empty({ icon, title, text, detail, action }) { - const box = make(doc, "div", "kit-empty"); - if (icon) box.append(make(doc, "span", `kit-icon kit-icon--${icon} kit-empty__icon`)); - box.append(make(doc, "p", "kit-empty__title", title)); - if (text) box.append(make(doc, "p", "kit-empty__text", text)); - if (detail) box.append(make(doc, "p", "kit-empty__text kit-mono", detail)); - if (action) { - const holder = make(doc, "div", "kit-empty__actions"); - holder.append(action); - box.append(holder); - } - return box; - } - - function section(title, count, ...content) { - const element = make(doc, "section", "kit-section"); - const head = make(doc, "div", "kit-section__head"); - head.append(make(doc, "h2", "kit-section__title", title)); - if (count !== null && count !== undefined) head.append(make(doc, "span", "kit-section__count", count)); - element.append(head, ...content); - return element; - } - - /* ── the parts every file shows ───────────────────────────────── */ - - function goBack(event) { - if (!actions.isDirty()) return actions.back(); - const asked = ctx.confirm - ? ctx.confirm(event && event.currentTarget, { message: t("leaveMessage"), confirm: t("leaveConfirm"), cancel: t("leaveCancel") }) - : Promise.resolve(false); - return asked.then((leave) => (leave ? actions.back() : undefined)); - } - - function header(stateOf) { - const head = make(doc, "header", "kit-header"); - const main = make(doc, "div", "kit-header__main"); - const title = make(doc, "h1", "kit-header__title", logic.baseName(state.path)); - title.title = state.path; - const line = make(doc, "p", "kit-header__state"); - const draw = () => { - const parts = stateOf(state); - const dir = dirName(state.path); - if (dir) parts.push(make(doc, "span", "kit-mono", dir)); - const spaced = []; - parts.forEach((part, index) => spaced.push(...(index ? [" ", part] : [part]))); - line.replaceChildren(...spaced); - line.title = state.path; - }; - draw(); - updaters.push(draw); - main.append(title, line); - head.append(main); - if (state.fromPicker) { - const actionsBox = make(doc, "div", "kit-header__actions"); - actionsBox.append(small(t("back"), "kit-btn--ghost", goBack, "back")); - head.append(actionsBox); - } - return head; - } - - function requestBanner() { - if (!state.why) return null; - const pane = state.caller ? t("askedBy", { pane: state.caller.pane }) : t("askedAnon"); - const element = make(doc, "p", "kit-banner"); - const text = make(doc, "span", "kit-banner__text"); - text.append(make(doc, "strong", "", pane), " ", state.why); - element.append(text); - return element; - } - - function saveProblem() { - if (!state.problem) return null; - return banner("error", t(`write.${state.problem.code}`)); - } - - function tellProblem() { - if (!state.told || state.told.status !== "failed") return null; - const reasonKey = `tell.${state.told.code}`; - const reason = logic.STRINGS.en[reasonKey] ? t(reasonKey) : t("tell.other"); - return banner( - "warning", - t("notTold", { pane: state.told.pane, reason }), - small(t("tellAgain", { pane: state.told.pane }), "", actions.retryTell, "tell-again"), - ); - } - - /** What is true right now, and the one thing to do: a line of its own at the foot of the page. */ - function foot(buildStatus, buildButtons) { - const bar = make(doc, "footer", "kit-bar kit-bar--foot editor-foot"); - const draw = () => { - const status = make(doc, "span", "editor-foot__status", buildStatus()); - status.setAttribute("role", "status"); - const buttons = make(doc, "span", "kit-actions"); - buttons.append(...buildButtons()); - bar.replaceChildren(status, buttons); - }; - draw(); - updaters.push(draw); - return bar; - } - - function savedStatus() { - if (state.busy) return t("saving"); - if (!state.told) return state.saved ? t("savedLocal") : ""; - if (state.told.status === "sent") { - return t(state.view === "text" ? "toldText" : "told", { pane: state.told.pane }); - } - if (state.told.status === "checked") return t("toldNoChange", { pane: state.told.pane }); - return state.saved ? t("savedLocal") : ""; - } - - const canTellNoChange = () => - Boolean(state.caller) && !actions.isDirty() && !state.saved && !(state.told && state.told.status !== "failed"); - - /* ── the form ─────────────────────────────────────────────────── */ - - function valueInput(row) { - const id = `value:${row.key}`; - const multiline = row.value.includes("\n"); - if (multiline && !row.revealed) { - // A password field would drop the line breaks: there is nothing to edit until it shows. - const hidden = make(doc, "input", "kit-input kit-mono"); - hidden.type = "password"; - hidden.disabled = true; - hidden.placeholder = t("valueLines"); - hidden.setAttribute("aria-label", row.key); - return hidden; - } - const field = multiline ? make(doc, "textarea", "kit-input kit-mono") : make(doc, "input", "kit-input kit-mono"); - if (multiline) field.rows = Math.min(VALUE_LINES_MAX, row.value.split("\n").length); - else field.type = row.revealed ? "text" : "password"; - field.value = row.value; - field.placeholder = t("valueEmpty"); - field.spellcheck = false; - field.setAttribute("autocapitalize", "off"); - field.setAttribute("autocomplete", "new-password"); // no password manager offers to fill this in - field.setAttribute("aria-label", row.key); - field.setAttribute("data-focus", id); - field.oninput = () => actions.editRow(row.key, field.value); - field.onkeydown = (event) => { - if (!isSaveKey(event)) return; - event.preventDefault(); - actions.saveForm(); - }; - return field; - } - - function rowMark(row) { - if (row.asked && row.value === "") return stateWord("waiting", t("keyMissing")); - if (row.present ? row.value !== row.original : row.value !== "") return make(doc, "span", "kit-chip", t("keyChanged")); - return row.asked ? stateWord("success", t("keySet")) : null; - } - - function keyRow(row) { - const item = make(doc, "li", "kit-row kit-row--wrap editor-key"); - const main = make(doc, "div", "kit-row__main editor-key__main"); - const name = make(doc, "div", "editor-key__name"); - const mark = make(doc, "span", "editor-key__mark"); - const drawMark = () => { - const now = rowMark(row); - mark.replaceChildren(...(now ? [now] : [])); - }; - drawMark(); - updaters.push(drawMark); - const title = make(doc, "span", "kit-mono kit-row__title", row.key); - title.title = row.key; - name.append(title, mark); - const value = make(doc, "div", "editor-key__value"); - value.append( - valueInput(row), - small(row.revealed ? t("hide") : t("show"), "kit-btn--ghost", () => actions.toggleReveal(row.key), `reveal:${row.key}`), - ); - main.append(name, value); - if (row.hint) main.append(make(doc, "span", "kit-field__hint", row.hint)); - if (row.count > 1) main.append(make(doc, "span", "kit-field__hint", t("keyTwice", { n: row.count }))); - item.append(main); - return item; - } - - function ignoreBanner() { - const ignore = state.ignore; - if (!ignore || ignore.status === "ignored") return null; - const file = logic.baseName(state.path); - if (ignore.status === "unknown") return banner("", t("ignoreUnknown", { file })); - const text = t(ignore.status === "no-file" ? "ignoreNoFile" : "ignoreWarning", { file }); - const add = small( - ignore.busy ? t("ignoreAdding") : t("ignoreAdd", { pattern: ctx.gitignore.patternFor(state.path) }), - "", - actions.addToGitignore, - "ignore-add", - ); - add.disabled = Boolean(ignore.busy); - const element = banner("warning", text, add); - if (ignore.problem) { - const code = logic.STRINGS.en[`write.${ignore.problem}`] ? ignore.problem : "other"; - element.append(make(doc, "span", "kit-field__error editor-wide", t("ignoreFailed", { reason: t(`write.${code}`) }))); - } - return element; - } - - function offeredSection(form) { - if (!form.offered.length) return null; - const list = make(doc, "ul", "kit-rows kit-rows--group"); - for (const offer of form.offered) { - const item = make(doc, "li", "kit-row kit-row--wrap"); - const main = make(doc, "span", "kit-row__main"); - main.append(make(doc, "span", "kit-mono kit-row__title", offer.key)); - if (offer.hint) main.append(make(doc, "span", "kit-row__sub", offer.hint)); - item.append(main, small(t("add"), "", () => actions.addOffered(offer.key), `offer:${offer.key}`)); - list.append(item); - } - const part = section(t("offeredTitle", { file: form.exampleName }), form.offered.length, list); - if (form.offered.length > 1) { - const holder = make(doc, "div", "kit-section__actions"); - holder.append(small(t("addAll"), "kit-btn--ghost", actions.addAllOffered, "offer-all")); - part.children[0].append(holder); - } - return part; - } - - function newKeyField(form) { - const field = make(doc, "div", "kit-field"); - const input = make(doc, "input", "kit-input kit-mono"); - input.type = "text"; - input.value = form.newKey; - input.placeholder = t("newKeyPlaceholder"); - input.spellcheck = false; - input.setAttribute("aria-label", t("newKeyLabel")); - input.setAttribute("autocapitalize", "off"); - input.setAttribute("data-focus", "new-key"); - if (form.newKeyProblem) input.setAttribute("aria-invalid", "true"); - input.oninput = () => actions.setNewKey(input.value); - input.onkeydown = (event) => { - if (event.key !== "Enter") return; - event.preventDefault(); - actions.addNewKey(); - }; - const line = make(doc, "div", "editor-key__value"); - line.append(input, small(t("add"), "", actions.addNewKey, "new-key-add")); - field.append(line); - if (form.newKeyProblem) field.append(make(doc, "span", "kit-field__error", t(form.newKeyProblem))); - return field; - } - - function dotenvView() { - const form = state.form; - const head = header(() => { - const missing = form.rows.filter((row) => row.asked && row.value === "").length; - if (missing) return [stateWord("waiting", t("stateMissing", { n: missing }))]; - if (state.saved) return [stateWord("success", t("stateSaved"))]; - if (!state.exists) return [stateWord("neutral", t("stateNew"))]; - return []; - }); - const { outer, page } = scroller(); - for (const part of [requestBanner(), ignoreBanner(), saveProblem(), tellProblem()]) if (part) page.append(part); - if (!state.exists && !state.why) page.append(banner("", t("newFile"))); - - const asked = form.rows.filter((row) => row.asked); - const rest = form.rows.filter((row) => !row.asked); - const list = (rows) => { - const element = make(doc, "ul", "kit-rows kit-rows--group"); - element.append(...rows.map(keyRow)); - return element; - }; - if (asked.length) page.append(section(t("sectionAsked"), asked.length, list(asked))); - if (rest.length) page.append(section(t("sectionFile"), rest.length, list(rest))); - if (!form.rows.length) page.append(empty({ title: t("noKeys") })); - const offered = offeredSection(form); - if (offered) page.append(offered); - page.append(section(t("newKeyLabel"), null, newKeyField(form))); - if (form.otherLines) page.append(make(doc, "p", "kit-muted kit-small editor-note", t("otherLines", { n: form.otherLines }))); - - const bar = foot(savedStatus, () => { - const out = []; - // With keys still to fill in, saying there is nothing to change is the lesser choice. - const missing = form.rows.some((row) => row.asked && row.value === ""); - const offerTell = canTellNoChange(); - if (offerTell) { - const tell = small(t("tellNoChange", { pane: state.caller.pane }), missing ? "" : "kit-btn--primary", actions.tellNoChange, "tell"); - tell.disabled = state.busy; - out.push(tell); - } - if (!offerTell || missing) { - const save = small(t("save"), "kit-btn--primary", actions.saveForm, "save"); - save.disabled = state.busy || !actions.isDirty(); - save.title = save.disabled && !state.busy ? t("nothingToSave") : ""; - out.push(save); - } - return out; - }); - return [head, outer, bar]; - } - - /* ── diffs ────────────────────────────────────────────────────── */ - - function diffBlock(hunks) { - const box = make(doc, "div", "kit-log editor-diff"); - box.setAttribute("tabindex", "0"); - for (const hunk of hunks) { - const line = make(doc, "div", "kit-log__line"); - if (hunk.op === "skip") { - line.className = "kit-log__line kit-log__line--head"; - line.append(make(doc, "span", "kit-log__text", t("diffSkip", { n: hunk.count }))); - } else { - if (hunk.op === "del") line.className = "kit-log__line kit-log__line--error"; - if (hunk.op === "add") line.className = "kit-log__line editor-add"; - const number = hunk.op === "add" ? hunk.b : hunk.a; - const sign = hunk.op === "add" ? "+ " : hunk.op === "del" ? "− " : " "; - line.append(make(doc, "span", "kit-log__num", number), make(doc, "span", "kit-log__text", sign + hunk.text)); - } - box.append(line); - } - return box; - } - - /* ── the conflict ─────────────────────────────────────────────── */ - - function conflictHead() { - return header(() => [stateWord("failure", t("stateConflict"))]); - } - - function conflictIntro(conflict) { - return banner("error", conflict.gone ? t("conflictGone") : `${t("conflictTitle")}. ${t("conflictHint")}`); - } - - function textConflictView(conflict) { - const { outer, page } = scroller(); - page.append(conflictIntro(conflict), make(doc, "p", "kit-mono kit-small kit-dim editor-note", t("conflictDiff")), diffBlock(conflict.hunks)); - const bar = foot( - () => "", - () => [ - small(conflict.gone ? t("conflictWriteMine") : t("conflictKeepMine"), "", actions.conflictKeepMine, "conflict-mine"), - small(t("conflictTakeTheirs"), "", actions.conflictTakeTheirs, "conflict-theirs"), - small(t("conflictEdit"), "kit-btn--ghost", actions.conflictBack, "conflict-edit"), - ], - ); - return [conflictHead(), outer, bar]; - } - - function conflictChoice(row, side) { - const label = make(doc, "label", "editor-choice"); - const radio = make(doc, "input"); - radio.type = "radio"; - radio.name = `choice-${row.key}`; - radio.checked = row.choice === side; - radio.setAttribute("data-focus", `choice:${side}:${row.key}`); - radio.onchange = () => actions.conflictChoose(row.key, side); - const value = row[side]; - let shown; - if (value === null) shown = make(doc, "span", "kit-muted", t("absent")); - else if (value === "") shown = make(doc, "span", "kit-muted", t("valueEmpty")); - else if (row.revealed) shown = make(doc, "span", "kit-mono kit-wrap editor-value", value); - else shown = make(doc, "span", "kit-mono kit-muted", MASK); - label.append(radio, make(doc, "span", "kit-dim editor-choice__side", t(side)), shown); - return label; - } - - function formConflictView(conflict) { - const { outer, page } = scroller(); - page.append(conflictIntro(conflict)); - if (conflict.rows.length) { - const list = make(doc, "ul", "kit-rows kit-rows--group"); - for (const row of conflict.rows) { - const item = make(doc, "li", "kit-row kit-row--wrap editor-key"); - const main = make(doc, "div", "kit-row__main editor-key__main"); - const name = make(doc, "div", "editor-key__name"); - const mark = make(doc, "span", "editor-key__mark"); - mark.append(small(row.revealed ? t("hide") : t("show"), "kit-btn--ghost", () => actions.conflictReveal(row.key), `conflict-reveal:${row.key}`)); - name.append(make(doc, "span", "kit-mono kit-row__title", row.key), mark); - main.append(name, conflictChoice(row, "mine"), conflictChoice(row, "theirs")); - item.append(main); - list.append(item); - } - page.append(section(t("conflictRows"), conflict.rows.length, list)); - } else { - page.append(banner("", t("conflictNone"))); - } - if (conflict.changedOnDisk) page.append(make(doc, "p", "kit-small kit-dim editor-note", t("conflictTheirsChanged", { n: conflict.changedOnDisk }))); - const bar = foot( - () => "", - () => [ - small(t("conflictApply"), "kit-btn--primary", actions.conflictKeepMine, "conflict-apply"), - small(t("conflictTakeTheirs"), "", actions.conflictTakeTheirs, "conflict-theirs"), - ], - ); - return [conflictHead(), outer, bar]; - } - - /* ── the editor ───────────────────────────────────────────────── */ - - function checkWord(check) { - if (!check || !check.kind) return null; - const name = check.kind === "jsonc" ? "JSONC" : check.kind.toUpperCase(); - if (check.ok) return stateWord(check.partial ? "neutral" : "success", check.partial ? t("checkBasic", { kind: name }) : t("checkOk", { kind: name })); - return stateWord("failure", check.line ? t("checkBrokenAt", { kind: name, line: check.line }) : t("checkBroken", { kind: name })); - } - - function textHeader() { - return header(() => { - const word = checkWord(state.text.check); - if (state.saved) return [stateWord("success", t("stateSaved"))]; - if (word) return [word]; - return state.exists ? [] : [stateWord("neutral", t("stateNew"))]; - }); - } - - function checkReason(check) { - if (!check || !check.kind) return ""; - const name = check.kind === "jsonc" ? "JSONC" : check.kind.toUpperCase(); - if (check.ok) return check.partial ? t("checkPartial", { kind: name }) : ""; - const reason = t(`check.${check.code}`); - return check.line ? t("checkBadAt", { kind: name, line: check.line, reason }) : t("checkBad", { kind: name, reason }); - } - - function gutterMarks() { - const marks = new Set(); - const text = state.text; - if (text.target) marks.add(text.target); - if (text.check && !text.check.ok && text.check.line) marks.add(text.check.line); - return marks; - } - - function drawGutter(gutter, count, marks) { - const parts = []; - let run = ""; - for (let line = 1; line <= count; line++) { - if (marks.has(line)) { - if (run) parts.push(run); - run = ""; - parts.push(make(doc, "span", "editor-gutter__mark", String(line))); - run = "\n"; - } else { - run += `${line}\n`; - } - } - if (run) parts.push(run); - gutter.replaceChildren(...parts); - } - - function textEditView() { - const text = state.text; - const page = make(doc, "main", "editor-column kit-grow"); - const notes = make(doc, "div", "editor-notes"); - const fixed = [requestBanner(), saveProblem(), tellProblem()]; - if (text.far) fixed.push(banner("", t("lineJumpFar", { line: text.far.line, total: text.far.total }))); - if (!state.exists) fixed.push(banner("", t("newFile"))); - for (const part of fixed) if (part) notes.append(part); - const reason = make(doc, "p", "editor-reason kit-small"); - const held = fixed.some(Boolean); - const drawReason = () => { - const check = state.text.check; - let words = checkReason(check); - if (check && !check.ok) { - const bare = t(`check.${check.code}`); - words = bare[0].toUpperCase() + bare.slice(1); - } - reason.textContent = words; - reason.hidden = !words; - reason.className = check && !check.ok ? "editor-reason kit-small editor-reason--bad" : "editor-reason kit-small kit-dim"; - notes.hidden = !held && !words; - }; - drawReason(); - updaters.push(drawReason); - notes.append(reason); - - const wrap = make(doc, "div", "editor-code kit-grow"); - const gutter = make(doc, "pre", "editor-gutter"); - gutter.setAttribute("aria-hidden", "true"); - const area = make(doc, "textarea", "editor-area"); - area.value = text.value; - area.wrap = "off"; - area.spellcheck = false; - area.setAttribute("autocapitalize", "off"); - area.setAttribute("aria-label", t("editorLabel")); - area.setAttribute("data-focus", "editor"); - - let drawnCount = -1; - let drawnMarks = ""; - const syncGutter = () => { - const count = state.text.value.split("\n").length; - const marks = gutterMarks(); - const key = [...marks].join(","); - if (count === drawnCount && key === drawnMarks) return; - drawnCount = count; - drawnMarks = key; - drawGutter(gutter, count, marks); - gutter.scrollTop = area.scrollTop; - }; - syncGutter(); - updaters.push(syncGutter); - - area.oninput = () => actions.editText(area.value); - area.onscroll = () => { - gutter.scrollTop = area.scrollTop; - memory.scrollTop = area.scrollTop; - memory.scrollLeft = area.scrollLeft; - }; - area.onkeydown = (event) => { - if (!isSaveKey(event)) return; - event.preventDefault(); - actions.review(); - }; - wrap.append(gutter, area); - page.append(notes, wrap); - - afterAttach.push(() => { - const jump = text.jump; - if (jump) { - // The caret moves there without taking the keyboard: a page never grabs it unasked. - const lines = text.value.split("\n"); - const start = lines.slice(0, jump - 1).reduce((sum, line) => sum + line.length + 1, 0); - if (typeof area.setSelectionRange === "function") area.setSelectionRange(start, start + lines[jump - 1].length); - const view = doc.defaultView; - const height = (view && parseFloat(view.getComputedStyle(area).lineHeight)) || 18; - area.scrollTop = Math.max(0, (jump - 4) * height); - gutter.scrollTop = area.scrollTop; - actions.consumeJump(); - } else if (memory.scrollTop) { - area.scrollTop = memory.scrollTop; - area.scrollLeft = memory.scrollLeft || 0; - gutter.scrollTop = area.scrollTop; - } - }); - - const bar = foot(savedStatus, () => { - if (canTellNoChange()) { - const tell = small(t("tellNoChange", { pane: state.caller.pane }), "kit-btn--primary", actions.tellNoChange, "tell"); - tell.disabled = state.busy; - return [tell]; - } - const go = small(t("review"), "kit-btn--primary", actions.review, "review"); - go.disabled = state.busy || (!actions.isDirty() && state.exists); - go.title = go.disabled && !state.busy ? t("nothingToSave") : ""; - return [go]; - }); - return [textHeader(), page, bar]; - } - - function textReviewView() { - const text = state.text; - const { outer, page } = scroller(); - for (const part of [saveProblem()]) if (part) page.append(part); - const broken = text.check && !text.check.ok; - if (broken) { - const box = banner("error", checkReason(text.check)); - const say = make(doc, "label", "kit-switch editor-wide"); - const toggle = make(doc, "input"); - toggle.type = "checkbox"; - toggle.setAttribute("role", "switch"); - toggle.checked = text.ack; - toggle.setAttribute("data-focus", "ack"); - toggle.onchange = () => actions.setAck(toggle.checked); - say.append(toggle, make(doc, "span", "kit-switch__track"), t("ackBroken")); - box.append(say); - page.append(box); - } else if (text.check && text.check.ok && text.check.partial) { - page.append(make(doc, "p", "kit-small kit-dim editor-note", checkReason(text.check))); - } - const changed = text.hunks && text.hunks.some((hunk) => hunk.op === "add" || hunk.op === "del"); - page.append(section(t("diffTitle"), null, changed ? diffBlock(text.hunks) : make(doc, "p", "kit-small kit-dim editor-note", t("diffNone")))); - const bar = foot( - () => (state.busy ? t("saving") : ""), - () => { - const save = small(t("save"), "kit-btn--primary", actions.saveText, "save"); - save.disabled = state.busy || (broken && !text.ack) || (!changed && state.exists); - return [small(t("backToEdit"), "kit-btn--ghost", actions.backToEdit, "edit"), save]; - }, - ); - return [textHeader(), outer, bar]; - } - - /* ── the picker ───────────────────────────────────────────────── */ - - function pickerView() { - const picker = state.picker; - const head = make(doc, "header", "kit-header"); - const main = make(doc, "div", "kit-header__main"); - main.append(make(doc, "h1", "kit-header__title", t("pickTitle"))); - head.append(main); - - const tools = make(doc, "div", "kit-bar"); - const search = make(doc, "div", "kit-search"); - const input = make(doc, "input"); - input.type = "search"; - input.value = picker.filter; - input.placeholder = t("pickFilter"); - input.setAttribute("aria-label", t("pickFilter")); - input.setAttribute("data-focus", "filter"); - input.oninput = () => actions.setFilter(input.value); - search.append(input); - tools.append(search); - - const { outer, page } = scroller(); - const notes = make(doc, "div", "kit-stack"); - if (picker.truncated) notes.append(banner("warning", t("pickTruncated"))); - const list = make(doc, "div", "kit-stack"); - const titles = { env: "groupEnv", config: "groupConfig", other: "groupOther" }; - const drawList = () => { - const groups = logic.filterGroups(state.picker.groups, state.picker.filter).filter((group) => group.files.length); - if (!groups.length) { - list.replaceChildren(empty({ title: t("pickEmpty") })); - return; - } - list.replaceChildren( - ...groups.map((group) => { - const rows = make(doc, "ul", "kit-rows"); - for (const file of group.files) { - const item = make(doc, "li"); - const row = make(doc, "button", "kit-row"); - row.type = "button"; - row.title = file.path; - row.onclick = () => actions.pick(file.path); - const text = make(doc, "span", "kit-row__main"); - text.append(make(doc, "span", "kit-row__title kit-mono", logic.baseName(file.path))); - const dir = dirName(file.path); - if (dir) text.append(make(doc, "span", "kit-row__sub kit-mono", dir)); - row.append(text); - if (file.isNew) { - const end = make(doc, "span", "kit-row__end"); - end.append(make(doc, "span", "kit-chip", t("pickNew"))); - row.append(end); - } - item.append(row); - rows.append(item); - } - const part = section(t(titles[group.id]), group.files.length + group.more, rows); - if (group.more) part.append(make(doc, "p", "kit-small kit-dim editor-note", t("pickMore", { n: group.more }))); - return part; - }), - ); - }; - drawList(); - updaters.push(drawList); - if (picker.truncated) page.append(notes); - page.append(list); - return [head, tools, outer]; - } - - /* ── the rest ─────────────────────────────────────────────────── */ - - function errorView() { - const kind = (state.error && state.error.kind) || "error"; - const { outer, page } = scroller(); - const retry = kind === "bad-path" - ? small(t("pickTitle"), "kit-btn--primary", actions.back, "pick") - : small(t("retry"), "kit-btn--primary", actions.retry, "retry"); - page.append( - empty({ - icon: kind === "denied" ? "lock" : "alert", - title: t(`err.${kind}.title`), - text: t(`err.${kind}.hint`), - detail: kind === "denied" ? null : state.error && state.error.detail, - action: retry, - }), - ); - return [outer]; - } - - function loadingView() { - const { outer, page } = scroller(); - const inner = make(doc, "div", "kit-empty"); - inner.append(stateWord("running", t("loading"))); - page.append(inner); - return [outer]; - } - - let parts; - if (state.view === "picker") parts = pickerView(); - else if (state.view === "error") parts = errorView(); - else if (state.view === "loading") parts = loadingView(); - else if (state.conflict) parts = state.conflict.kind === "text" ? textConflictView(state.conflict) : formConflictView(state.conflict); - else if (state.view === "dotenv") parts = dotenvView(); - else parts = state.text.stage === "review" ? textReviewView() : textEditView(); - - container.replaceChildren(...parts); - - if (keepFocus) { - const found = container.find - ? container.find((node) => node.getAttribute && node.getAttribute("data-focus") === keepFocus)[0] - : [...container.querySelectorAll("[data-focus]")].find((node) => node.getAttribute("data-focus") === keepFocus); - if (found) found.focus(); - } - for (const run of afterAttach) run(); - - return () => updaters.forEach((update) => update()); - } - - return { render, MASK }; -}); diff --git a/test/controller.test.js b/test/controller.test.js deleted file mode 100644 index 35d1b87..0000000 --- a/test/controller.test.js +++ /dev/null @@ -1,650 +0,0 @@ -"use strict"; -// The tab's behaviour against a fake window.hangar: what it reads, when it writes, -// what it refuses to write, and what it says when Hangar answers no. -const test = require("node:test"); -const assert = require("node:assert/strict"); -const { fakeHangar, opened, row, settle } = require("./helpers.js"); - -const CALLER = { pane: "Asker" }; -const IGNORED = { ".gitignore": ".env\n" }; -const writes = (hangar) => hangar.callsTo("files.write"); -const writesTo = (hangar, path) => writes(hangar).filter((call) => call.args.path === path); -const lastBadge = (hangar) => hangar.callsTo("tab.setBadge").at(-1).args; - -/* ── the dotenv form ──────────────────────────────────────────────── */ - -test("a dotenv file opens as a form: one row per key, hidden, its comments and order kept on save", async () => { - const text = "# Database\nDB_URL=old\n\n# Payments\nexport STRIPE_KEY='x' # test mode\nLOG=debug\nDB_URL=later\n"; - const { hangar, controller, state } = await opened({ params: { path: ".env" }, files: { ".env": text, ...IGNORED } }); - assert.equal(state.view, "dotenv"); - assert.deepEqual(state.form.rows.map((each) => each.key), ["DB_URL", "STRIPE_KEY", "LOG"]); - assert.ok(state.form.rows.every((each) => each.revealed === false), "hidden until revealed"); - assert.equal(row(state, "DB_URL").value, "later"); - assert.equal(row(state, "DB_URL").count, 2); - assert.equal(row(state, "STRIPE_KEY").hint, "Payments"); - - controller.editRow("STRIPE_KEY", "sk_new"); - await controller.saveForm(); - await settle(); - assert.equal(hangar.store.get(".env"), "# Database\nDB_URL=old\n\n# Payments\nexport STRIPE_KEY='sk_new' # test mode\nLOG=debug\nDB_URL=later\n"); - assert.equal(writes(hangar)[0].args.expected, text, "with what it read"); - assert.equal(state.saved, true); - assert.equal(lastBadge(hangar).state, "success"); -}); - -test("a value is revealed row by row, and hidden again after saving", async () => { - const { controller, state } = await opened({ params: { path: ".env" }, files: { ".env": "A=1\nB=2\n", ...IGNORED } }); - controller.toggleReveal("A"); - assert.equal(row(state, "A").revealed, true); - assert.equal(row(state, "B").revealed, false); - controller.editRow("A", "9"); - await controller.saveForm(); - await settle(); - assert.equal(row(state, "A").revealed, false); -}); - -test("the keys an agent asks for come first, marked missing, with why at the top", async () => { - const { hangar, state, controller } = await opened({ - params: { path: ".env", keys: "NEW_ONE, PRESENT,EMPTY", why: "For the payment tests." }, - caller: CALLER, - files: { ".env": "OTHER=1\nPRESENT=x\nEMPTY=\n", ...IGNORED }, - }); - assert.equal(state.why, "For the payment tests."); - assert.deepEqual(state.form.rows.map((each) => each.key), ["NEW_ONE", "PRESENT", "EMPTY", "OTHER"]); - assert.deepEqual(state.form.rows.map((each) => each.asked), [true, true, true, false]); - assert.equal(lastBadge(hangar).text, "2 missing"); - controller.editRow("NEW_ONE", "v"); - assert.equal(lastBadge(hangar).text, "1 missing"); - controller.editRow("EMPTY", "v"); - assert.equal(lastBadge(hangar).state, null); -}); - -test("a key asked and left empty is not written; one filled in goes at the end", async () => { - const { hangar, controller, state } = await opened({ - params: { path: ".env", keys: "FILLED,LEFT" }, caller: CALLER, files: { ".env": "OTHER=1\n", ...IGNORED }, - }); - controller.editRow("FILLED", "v"); - await controller.saveForm(); - await settle(); - assert.equal(hangar.store.get(".env"), "OTHER=1\nFILLED=v\n"); - assert.equal( - hangar.callsTo("panes.send")[0].args.text, - "The person saved `.env`. Set: FILLED. Still empty: LEFT. The values stay in the file: do not read them back, use them through the program that loads it.", - ); - assert.deepEqual(hangar.callsTo("panes.send")[0].args.pane, "Asker"); - assert.equal(row(state, "LEFT").asked, true, "still asked for"); -}); - -test("a file that does not exist yet opens empty, and saving creates it", async () => { - const { hangar, controller, state } = await opened({ params: { path: "config/.env", keys: "A" }, files: { ".gitignore": "*.env\n.env\n" } }); - assert.equal(state.view, "dotenv"); - assert.equal(state.exists, false); - controller.editRow("A", "1"); - await controller.saveForm(); - await settle(); - assert.equal(hangar.store.get("config/.env"), "A=1\n"); - assert.equal(writes(hangar)[0].args.expected, undefined, "there was nothing to expect"); - assert.equal(state.exists, true); -}); - -test("keys of .env.example missing here are offered, not added", async () => { - const { hangar, controller, state } = await opened({ - params: { path: ".env", keys: "FROM_EXAMPLE" }, - files: { ".env": "HERE=1\n", ".env.example": "HERE=\n# Where to find it\nFROM_EXAMPLE=placeholder\n# Second\nEXTRA=placeholder\nANOTHER=\n", ...IGNORED }, - }); - assert.deepEqual(state.form.offered.map((offer) => offer.key), ["EXTRA", "ANOTHER"]); - assert.equal(state.form.offered[0].hint, "Second"); - assert.equal(state.form.exampleName, ".env.example"); - assert.equal(row(state, "FROM_EXAMPLE").hint, "Where to find it"); - assert.equal(row(state, "FROM_EXAMPLE").value, "", "the example's value is not taken for a real one"); - assert.equal(controller.isDirty(), false, "nothing is added until asked"); - - controller.addOffered("EXTRA"); - assert.equal(row(state, "EXTRA").value, ""); - assert.deepEqual(state.form.offered.map((offer) => offer.key), ["ANOTHER"]); - controller.editRow("EXTRA", "mine"); - await controller.saveForm(); - await settle(); - assert.equal(hangar.store.get(".env"), "HERE=1\nEXTRA=mine\n"); - assert.deepEqual(state.form.offered.map((offer) => offer.key), ["ANOTHER"], "what is still missing stays offered"); - assert.equal(row(state, "FROM_EXAMPLE").hint, "Where to find it", "and the template still explains what is asked"); - - controller.addAllOffered(); - await controller.saveForm(); - await settle(); - assert.equal(hangar.store.get(".env"), "HERE=1\nEXTRA=mine\nANOTHER=\n", "an explicit add is written, even empty"); - assert.equal(state.form.offered.length, 0); -}); - -test("a template offers nothing, and needs no warning", async () => { - const { state, hangar } = await opened({ params: { path: ".env.example" }, files: { ".env.example": "A=\n" } }); - assert.equal(state.form.offered.length, 0); - assert.equal(state.ignore.status, "ignored"); - assert.equal(hangar.callsTo("files.read").filter((call) => call.args.path.endsWith(".gitignore")).length, 0); -}); - -test("a key the person adds is checked, and a bad one says why", async () => { - const { controller, state } = await opened({ params: { path: ".env" }, files: { ".env": "A=1\n", ...IGNORED } }); - controller.setNewKey("not a key"); - controller.addNewKey(); - assert.equal(state.form.newKeyProblem, "newKeyBad"); - controller.setNewKey("A"); - controller.addNewKey(); - assert.equal(state.form.newKeyProblem, "newKeyTaken"); - controller.setNewKey(" B_KEY "); - controller.addNewKey(); - assert.equal(state.form.newKeyProblem, null); - assert.equal(state.form.newKey, ""); - assert.equal(row(state, "B_KEY").added, true); -}); - -/* ── git ──────────────────────────────────────────────────────────── */ - -test("not ignored: it says so, and .gitignore changes only on a click", async () => { - const { hangar, controller, state } = await opened({ params: { path: ".env" }, files: { ".env": "A=1\n", ".gitignore": "node_modules/\n" } }); - assert.equal(state.ignore.status, "not-ignored"); - assert.equal(writes(hangar).length, 0, "opening writes nothing"); - controller.editRow("A", "2"); - await controller.saveForm(); - await settle(); - assert.equal(writesTo(hangar, ".gitignore").length, 0, "saving the file does not touch it either"); - - await controller.addToGitignore(); - assert.equal(hangar.store.get(".gitignore"), "node_modules/\n.env\n"); - assert.equal(writesTo(hangar, ".gitignore")[0].args.expected, "node_modules/\n"); - assert.equal(state.ignore.status, "ignored"); -}); - -test("no .gitignore at all: said plainly, and the click creates one", async () => { - const { hangar, controller, state } = await opened({ params: { path: "sub/.env.local" }, files: { "sub/.env.local": "A=1\n" } }); - assert.equal(state.ignore.status, "no-file"); - await controller.addToGitignore(); - assert.equal(hangar.store.get(".gitignore"), "sub/.env.local\n"); - assert.equal(writesTo(hangar, ".gitignore")[0].args.expected, undefined); - assert.equal(state.ignore.status, "ignored"); -}); - -test("a .gitignore that moved under the click is not overwritten, and a denied one says so", async () => { - const { hangar, controller, state } = await opened({ params: { path: ".env" }, files: { ".env": "A=1\n", ".gitignore": "old\n" } }); - hangar.writeError = "rate_limited"; - await controller.addToGitignore(); - assert.equal(state.ignore.problem, "rate_limited"); - assert.equal(state.ignore.status, "not-ignored"); - assert.equal(hangar.store.get(".gitignore"), "old\n"); - hangar.writeError = null; - await controller.addToGitignore(); - assert.equal(hangar.store.get(".gitignore"), "old\n.env\n"); -}); - -test("a .gitignore that cannot be read leaves the question open, and the form works", async () => { - const hangar = fakeHangar({ params: { path: ".env" }, files: { ".env": "A=1\n" } }); - const read = hangar.call; - hangar.call = async (method, args) => { - if (method === "files.read" && args.path === ".gitignore") throw Object.assign(new Error("no"), { code: "denied" }); - return read(method, args); - }; - const { state } = await opened({ hangar }); - assert.equal(state.ignore.status, "unknown"); - assert.equal(state.view, "dotenv"); -}); - -/* ── any other text file ──────────────────────────────────────────── */ - -test("a text file opens in the editor at the line asked for", async () => { - const lines = Array.from({ length: 9 }, (_, i) => `line ${i + 1}`).join("\n"); - const { state } = await opened({ params: { path: "notes.txt", line: "7" }, files: { "notes.txt": lines } }); - assert.equal(state.view, "text"); - assert.equal(state.text.jump, 7); - assert.equal(state.text.target, 7); - assert.equal(state.text.check.kind, null); - const far = await opened({ params: { path: "notes.txt", line: "70" }, files: { "notes.txt": lines } }); - assert.equal(far.state.text.jump, 9, "as far as the file goes"); - assert.deepEqual(far.state.text.far, { line: 70, total: 9 }); -}); - -test("a diff comes before saving, and saving sends what was reviewed", async () => { - const { hangar, controller, state } = await opened({ params: { path: "a.txt" }, files: { "a.txt": "one\ntwo\nthree\n" } }); - controller.editText("one\nTWO\nthree\n"); - assert.equal(writes(hangar).length, 0, "typing writes nothing"); - controller.review(); - assert.equal(state.text.stage, "review"); - assert.deepEqual(state.text.hunks.filter((hunk) => hunk.op !== "same").map((hunk) => [hunk.op, hunk.text]), [["del", "two"], ["add", "TWO"]]); - assert.equal(writes(hangar).length, 0, "reviewing writes nothing"); - await controller.saveText(); - await settle(); - assert.equal(hangar.store.get("a.txt"), "one\nTWO\nthree\n"); - assert.equal(writes(hangar)[0].args.expected, "one\ntwo\nthree\n"); - assert.equal(state.text.stage, "edit"); - assert.equal(state.saved, true); -}); - -test("line endings survive the textarea", async () => { - const crlf = await opened({ params: { path: "a.txt" }, files: { "a.txt": "one\r\ntwo\r\n" } }); - assert.equal(crlf.state.text.value, "one\ntwo\n", "as a textarea would hold it"); - crlf.controller.editText("one\ntwo\nthree\n"); - crlf.controller.review(); - assert.deepEqual(crlf.state.text.hunks.filter((hunk) => hunk.op !== "same").map((hunk) => hunk.text), ["three"], "the line endings are no change"); - await crlf.controller.saveText(); - await settle(); - assert.equal(crlf.hangar.store.get("a.txt"), "one\r\ntwo\r\nthree\r\n"); - - const mixed = await opened({ params: { path: "a.txt" }, files: { "a.txt": "a\r\nb\nc\r\nd\r\n" } }); - mixed.controller.editText("a\nB\nc\nd\n"); - mixed.controller.review(); - await mixed.controller.saveText(); - await settle(); - assert.equal(mixed.hangar.store.get("a.txt"), "a\r\nB\r\nc\r\nd\r\n", "only the changed line takes the common one"); -}); - -test("a broken file is saved only after saying so", async () => { - const { hangar, controller, state } = await opened({ params: { path: "a.json" }, files: { "a.json": '{"a": 1}\n' } }); - assert.equal(state.text.check.ok, true); - controller.editText('{"a": 1,}\n'); - assert.equal(state.text.check.ok, false); - controller.review(); - await controller.saveText(); - await settle(); - assert.equal(writes(hangar).length, 0, "not without saying so"); - assert.equal(hangar.store.get("a.json"), '{"a": 1}\n'); - - controller.setAck(true); - controller.editText('{"a": 1,,}\n'); - assert.equal(state.text.ack, false, "changing the text takes back what was said"); - controller.review(); - assert.equal(state.text.ack, false); - await controller.saveText(); - await settle(); - assert.equal(writes(hangar).length, 0); - - controller.setAck(true); - await controller.saveText(); - await settle(); - assert.equal(hangar.store.get("a.json"), '{"a": 1,,}\n'); -}); - -test("a file already broken when opened follows the same rule", async () => { - const { hangar, controller, state } = await opened({ params: { path: "a.toml" }, files: { "a.toml": "a = \n" } }); - assert.equal(state.text.check.ok, false); - controller.editText("a = \nb = 2\n"); - controller.review(); - await controller.saveText(); - assert.equal(writes(hangar).length, 0); -}); - -test("a new text file: the whole of it is the diff, and it is created", async () => { - const { hangar, controller, state } = await opened({ params: { path: "conf/new.yaml" }, files: {} }); - assert.equal(state.view, "text"); - assert.equal(state.exists, false); - controller.editText("a: 1\n"); - controller.review(); - await controller.saveText(); - await settle(); - assert.equal(hangar.store.get("conf/new.yaml"), "a: 1\n"); - assert.equal(writes(hangar)[0].args.expected, undefined); -}); - -/* ── conflicts ────────────────────────────────────────────────────── */ - -test("text conflict: nothing is written until the person chooses, and both sides show", async () => { - const { hangar, controller, state } = await opened({ params: { path: "a.txt" }, caller: CALLER, files: { "a.txt": "base\n" } }); - controller.editText("mine\n"); - controller.review(); - hangar.store.set("a.txt", "theirs\n"); - await controller.saveText(); - await settle(); - - assert.equal(hangar.store.get("a.txt"), "theirs\n", "never overwritten silently"); - assert.equal(state.conflict.kind, "text"); - assert.equal(state.conflict.theirs, "theirs\n"); - assert.deepEqual(state.conflict.hunks.map((hunk) => [hunk.op, hunk.text]).filter(([op]) => op !== "same"), [["del", "theirs"], ["add", "mine"]]); - assert.equal(hangar.callsTo("panes.send").length, 0, "no answer for what was not written"); - - await controller.conflictKeepMine(); - await settle(); - assert.equal(hangar.store.get("a.txt"), "mine\n"); - assert.equal(writes(hangar).at(-1).args.expected, "theirs\n", "measured against what the person just saw"); - assert.equal(state.conflict, null); - assert.equal(hangar.callsTo("panes.send").length, 1); -}); - -test("text conflict: taking theirs drops mine and writes nothing", async () => { - const { hangar, controller, state } = await opened({ params: { path: "a.txt" }, files: { "a.txt": "base\n" } }); - controller.editText("mine\n"); - controller.review(); - hangar.store.set("a.txt", "theirs\n"); - await controller.saveText(); - await settle(); - const before = writes(hangar).length; - await controller.conflictTakeTheirs(); - await settle(); - assert.equal(state.text.value, "theirs\n"); - assert.equal(controller.isDirty(), false); - assert.equal(writes(hangar).length, before); - assert.equal(hangar.store.get("a.txt"), "theirs\n"); -}); - -test("text conflict: back to editing keeps mine, against what the disk holds now", async () => { - const { hangar, controller, state } = await opened({ params: { path: "a.txt" }, files: { "a.txt": "base\n" } }); - controller.editText("mine\n"); - controller.review(); - hangar.store.set("a.txt", "theirs\n"); - await controller.saveText(); - await settle(); - controller.conflictBack(); - assert.equal(state.text.value, "mine\n"); - assert.equal(state.text.original, "theirs\n"); - assert.equal(state.text.stage, "edit"); - controller.review(); - await controller.saveText(); - await settle(); - assert.equal(hangar.store.get("a.txt"), "mine\n"); -}); - -test("the file moved twice: a second conflict is a conflict again", async () => { - const { hangar, controller, state } = await opened({ params: { path: "a.txt" }, files: { "a.txt": "base\n" } }); - controller.editText("mine\n"); - controller.review(); - hangar.store.set("a.txt", "theirs\n"); - await controller.saveText(); - await settle(); - hangar.store.set("a.txt", "theirs again\n"); - await controller.conflictKeepMine(); - await settle(); - assert.equal(hangar.store.get("a.txt"), "theirs again\n"); - assert.equal(state.conflict.theirs, "theirs again\n"); -}); - -test("a file deleted meanwhile is a conflict, and writing it back is a choice", async () => { - const { hangar, controller, state } = await opened({ params: { path: "a.txt" }, files: { "a.txt": "base\n" } }); - controller.editText("mine\n"); - controller.review(); - hangar.store.delete("a.txt"); - await controller.saveText(); - await settle(); - assert.equal(hangar.store.has("a.txt"), false); - assert.equal(state.conflict.gone, true); - await controller.conflictKeepMine(); - await settle(); - assert.equal(hangar.store.get("a.txt"), "mine\n"); -}); - -test("a new file that appeared meanwhile is a conflict too", async () => { - const { hangar, controller, state } = await opened({ params: { path: ".env", keys: "A" }, files: { ...IGNORED } }); - controller.editRow("A", "mine"); - hangar.store.set(".env", "A=theirs\n"); - await controller.saveForm(); - await settle(); - assert.equal(hangar.store.get(".env"), "A=theirs\n", "not overwritten though nothing was expected"); - assert.equal(state.conflict.kind, "dotenv"); -}); - -test("dotenv conflict: key by key, hidden, and my keys go on top of what the disk holds", async () => { - const { hangar, controller, state } = await opened({ - params: { path: ".env" }, caller: CALLER, files: { ".env": "# base\nA=1\nB=2\nC=3\n", ...IGNORED }, - }); - controller.editRow("A", "mine-a"); - controller.editRow("B", "mine-b"); - hangar.store.set(".env", "# moved\nA=theirs-a\nB=2\nC=3\nD=new\n"); - await controller.saveForm(); - await settle(); - - assert.equal(hangar.store.get(".env"), "# moved\nA=theirs-a\nB=2\nC=3\nD=new\n"); - assert.equal(state.conflict.kind, "dotenv"); - assert.deepEqual(state.conflict.rows.map((each) => [each.key, each.mine, each.theirs, each.choice, each.revealed]), [ - ["A", "mine-a", "theirs-a", "mine", false], - ["B", "mine-b", "2", "mine", false], - ]); - assert.equal(state.conflict.changedOnDisk, 1, "D"); - assert.equal(hangar.callsTo("panes.send").length, 0); - - controller.conflictReveal("A"); - assert.equal(state.conflict.rows[0].revealed, true); - controller.conflictChoose("A", "theirs"); - await controller.conflictKeepMine(); - await settle(); - assert.equal(hangar.store.get(".env"), "# moved\nA=theirs-a\nB=mine-b\nC=3\nD=new\n", "their comment and their key stay"); - assert.equal(writes(hangar).at(-1).args.expected, "# moved\nA=theirs-a\nB=2\nC=3\nD=new\n"); - assert.match(hangar.callsTo("panes.send")[0].args.text, /Set: B\./); - assert.equal(state.conflict, null); - assert.equal(row(state, "D").value, "new", "the form now reads the new file"); -}); - -test("dotenv conflict: when nothing collides it still asks", async () => { - const { hangar, controller, state } = await opened({ params: { path: ".env" }, files: { ".env": "A=1\nB=2\n", ...IGNORED } }); - controller.editRow("A", "mine"); - hangar.store.set(".env", "A=1\nB=theirs\n"); - await controller.saveForm(); - await settle(); - assert.equal(state.conflict.rows.length, 1, "A: mine is not what the disk holds"); - assert.equal(hangar.store.get(".env"), "A=1\nB=theirs\n"); - await controller.conflictTakeTheirs(); - await settle(); - assert.equal(row(state, "B").value, "theirs"); - assert.equal(row(state, "A").value, "1"); - assert.equal(controller.isDirty(), false); -}); - -/* ── who asked ────────────────────────────────────────────────────── */ - -test("the agent is answered on save, and only when one asked", async () => { - const text = await opened({ params: { path: "a.txt" }, caller: CALLER, files: { "a.txt": "x\n" } }); - text.controller.editText("y\n"); - text.controller.review(); - await text.controller.saveText(); - await settle(); - assert.deepEqual(text.hangar.callsTo("panes.send").map((call) => call.args), [{ pane: "Asker", text: "The person saved `a.txt`: the file changed." }]); - assert.equal(text.state.told.status, "sent"); - - const nobody = await opened({ params: { path: "a.txt" }, files: { "a.txt": "x\n" } }); - nobody.controller.editText("y\n"); - nobody.controller.review(); - await nobody.controller.saveText(); - await settle(); - assert.equal(nobody.hangar.callsTo("panes.send").length, 0); - assert.equal(nobody.state.told, null); -}); - -test("nothing to change: the waiting agent can still be told, with names only", async () => { - const { hangar, controller, state } = await opened({ - params: { path: ".env", keys: "SET_KEY,EMPTY_KEY" }, caller: CALLER, files: { ".env": "SET_KEY=abc\nEMPTY_KEY=\n", ...IGNORED }, - }); - await controller.tellNoChange(); - assert.equal( - hangar.callsTo("panes.send")[0].args.text, - "The person checked `.env` and changed nothing. Already set: SET_KEY. Still empty: EMPTY_KEY. The values stay in the file: do not read them back, use them through the program that loads it.", - ); - assert.equal(state.told.status, "checked"); - assert.equal(writes(hangar).length, 0); - - const text = await opened({ params: { path: "a.txt" }, caller: CALLER, files: { "a.txt": "x\n" } }); - await text.controller.tellNoChange(); - assert.equal(text.hangar.callsTo("panes.send")[0].args.text, "The person checked `a.txt` and changed nothing."); - text.controller.editText("y\n"); - await text.controller.tellNoChange(); - assert.equal(text.hangar.callsTo("panes.send").length, 1, "not while something is unsaved"); -}); - -test("an agent that cannot be told: saved all the same, it says so, and it can try again", async () => { - const { hangar, controller, state } = await opened({ - params: { path: ".env" }, caller: CALLER, files: { ".env": "A=1\n", ...IGNORED }, sendError: "not_found", - }); - controller.editRow("A", "2"); - await controller.saveForm(); - await settle(); - assert.equal(hangar.store.get(".env"), "A=2\n"); - assert.equal(state.saved, true); - assert.deepEqual(state.told, { status: "failed", pane: "Asker", code: "not_found" }); - hangar.sendError = null; - await controller.retryTell(); - assert.equal(state.told.status, "sent"); -}); - -test("asked again: the latest to ask is answered, and what was typed stays", async () => { - const { hangar, controller, state } = await opened({ - params: { path: ".env", keys: "A" }, caller: CALLER, files: { ".env": "A=\nB=2\n", ...IGNORED }, - }); - controller.editRow("A", "typing"); - hangar.emit("tab.params", { params: { path: ".env", keys: "A,NEW", why: "Now this too." }, caller: { pane: "Other" } }); - await settle(); - assert.equal(state.caller.pane, "Other"); - assert.equal(row(state, "A").value, "typing"); - assert.equal(state.why, "Now this too."); - assert.deepEqual(state.form.rows.map((each) => [each.key, each.asked]), [["A", true], ["NEW", true], ["B", false]]); - assert.equal(hangar.callsTo("files.read").filter((call) => call.args.path === ".env").length, 1, "not read again"); - await controller.saveForm(); - await settle(); - assert.equal(hangar.callsTo("panes.send")[0].args.pane, "Other"); -}); - -test("asked again after a save: the new asker can be told there is nothing more to change", async () => { - const { hangar, controller, state } = await opened({ params: { path: "a.txt" }, caller: CALLER, files: { "a.txt": "x\n" } }); - controller.editText("y\n"); - controller.review(); - await controller.saveText(); - await settle(); - assert.equal(state.saved, true); - hangar.emit("tab.params", { params: { path: "a.txt" }, caller: { pane: "Other" } }); - await settle(); - assert.equal(state.saved, false); - assert.equal(state.told, null); - await controller.tellNoChange(); - assert.deepEqual(hangar.callsTo("panes.send").at(-1).args, { pane: "Other", text: "The person checked `a.txt` and changed nothing." }); -}); - -test("the person opening it again takes the caller away, and nobody is told", async () => { - const { hangar, controller, state } = await opened({ params: { path: "a.txt" }, caller: CALLER, files: { "a.txt": "x\n" } }); - hangar.emit("tab.params", { params: { path: "a.txt" }, caller: null }); - await settle(); - assert.equal(state.caller, null); - controller.editText("y\n"); - controller.review(); - await controller.saveText(); - await settle(); - assert.equal(hangar.callsTo("panes.send").length, 0); -}); - -/* ── what Hangar refuses ──────────────────────────────────────────── */ - -test("reading denied: a page that says what to do, with nothing written", async () => { - const { state, hangar } = await opened({ params: { path: ".env" }, files: { ".env": "A=1\n" }, deny: ["files.read"] }); - assert.equal(state.view, "error"); - assert.equal(state.error.kind, "denied"); - assert.equal(writes(hangar).length, 0); -}); - -test("listing denied: the picker says so too", async () => { - const { state } = await opened({ deny: ["files.list"] }); - assert.equal(state.view, "error"); - assert.equal(state.error.kind, "denied"); -}); - -test("writing denied or over the limit: the edits stay, and it says so", async () => { - for (const code of ["denied", "rate_limited", "invalid", "failed"]) { - const { hangar, controller, state } = await opened({ params: { path: ".env" }, files: { ".env": "A=1\n", ...IGNORED } }); - hangar.writeError = code; - controller.editRow("A", "typed"); - await controller.saveForm(); - await settle(); - assert.equal(state.problem.code, code === "failed" ? "other" : code); - assert.equal(row(state, "A").value, "typed", code); - assert.equal(controller.isDirty(), true); - assert.equal(state.saved, false); - assert.equal(state.busy, false); - hangar.writeError = null; - await controller.saveForm(); - await settle(); - assert.equal(hangar.store.get(".env"), "A=typed\n"); - assert.equal(state.problem, null); - } -}); - -test("panes.send denied: saved, and it says the agent was not told", async () => { - const { hangar, controller, state } = await opened({ params: { path: "a.txt" }, caller: CALLER, files: { "a.txt": "x\n" }, deny: ["panes.send"] }); - controller.editText("y\n"); - controller.review(); - await controller.saveText(); - await settle(); - assert.equal(hangar.store.get("a.txt"), "y\n"); - assert.equal(state.told.code, "denied"); -}); - -test("a title or a badge refused changes nothing", async () => { - const { state } = await opened({ params: { path: ".env", keys: "A" }, files: { ".env": "", ...IGNORED }, deny: ["tab.setTitle", "tab.setBadge"] }); - assert.equal(state.view, "dotenv"); -}); - -test("a path that can never open: said as such, and Hangar is not asked", async () => { - for (const path of ["../outside", "/etc/passwd", "C:/x", ".git/config", "a/../b", "sub\\.GIT\\hooks", "a. "]) { - const { state, hangar } = await opened({ params: { path } }); - assert.equal(state.view, "error", path); - assert.equal(state.error.kind, "bad-path", path); - assert.equal(hangar.callsTo("files.read").length, 0, path); - } -}); - -test("a file Hangar cannot read shows why", async () => { - const hangar = fakeHangar({ params: { path: "big.txt" } }); - const read = hangar.call; - hangar.call = async (method, args) => { - if (method === "files.read") throw Object.assign(new Error("big.txt is larger than 1 MB"), { code: "failed" }); - return read(method, args); - }; - const { state } = await opened({ hangar }); - assert.equal(state.error.kind, "failed"); - assert.equal(state.error.detail, "big.txt is larger than 1 MB"); -}); - -/* ── the picker ───────────────────────────────────────────────────── */ - -test("no params: a picker, env files first, then config, what is not text left out", async () => { - const { state, hangar, controller } = await opened({ - files: { - "README.md": "", "src/app.ts": "", "logo.png": "", "package.json": "{}", "pnpm-lock.yaml": "", "config/app.yaml": "", ".env.local": "A=1", "sub/.env": "", ".npmrc": "", "tsconfig.json": "{}", - }, - }); - assert.equal(state.view, "picker"); - assert.equal(hangar.callsTo("files.list").length, 1); - assert.deepEqual(state.picker.groups.env.map((file) => [file.path, file.isNew]), [[".env", true], [".env.local", false], ["sub/.env", false]]); - assert.deepEqual(state.picker.groups.config.map((file) => file.path), ["package.json", "config/app.yaml", ".npmrc", "tsconfig.json"]); - assert.deepEqual(state.picker.groups.other.map((file) => file.path), ["README.md", "src/app.ts", "pnpm-lock.yaml"]); - - await controller.pick(".env.local"); - await settle(); - assert.equal(state.view, "dotenv"); - assert.equal(state.fromPicker, true); - assert.equal(state.path, ".env.local"); - assert.equal(hangar.callsTo("tab.setTitle").at(-1).args.title, ".env.local"); - - await controller.back(); - await settle(); - assert.equal(state.view, "picker"); - assert.equal(state.path, null); -}); - -test("the picker's filter, and a listing that was cut", async () => { - const { lib: { logic } } = require("./helpers.js"); - const groups = logic.rankFiles([{ path: "a.yaml" }, { path: "b/.env" }, ...Array.from({ length: 450 }, (_, i) => ({ path: `src/f${i}.ts` }))]); - assert.deepEqual(logic.filterGroups(groups, "YAML").map((group) => group.files.length), [0, 1, 0], "any case"); - const all = logic.filterGroups(groups, ""); - assert.equal(all[2].files.length, 200); - assert.equal(all[2].more, 250); - const { state } = await opened({ files: { "a.txt": "" }, truncated: true }); - assert.equal(state.picker.truncated, true); -}); - -/* ── params, read like form input ─────────────────────────────────── */ - -test("params", () => { - const { lib: { logic } } = require("./helpers.js"); - assert.deepEqual(logic.parseKeys("A, B ,A,not a key,1BAD,C.D"), ["A", "B", "C.D"]); - assert.deepEqual(logic.parseKeys(undefined), []); - assert.equal(logic.parseLine("12"), 12); - for (const bad of ["0", "-1", "1e3", "abc", "", undefined]) assert.equal(logic.parseLine(bad), null, String(bad)); - assert.equal(logic.checkPath("a\\b/./c.txt"), "a/b/c.txt"); - assert.equal(logic.checkPath(".env"), ".env"); - assert.equal(logic.checkPath(".github/x.yml"), ".github/x.yml"); - const read = logic.readParams({ params: { path: ".env", why: " why ", keys: "A" }, caller: { pane: "P" } }); - assert.deepEqual(read, { path: ".env", badPath: false, keys: ["A"], why: "why", line: null, caller: { pane: "P" } }); - assert.equal(logic.readParams({ params: {}, caller: { pane: "" } }).caller, null); - assert.equal(logic.tabTitle(`a/${"x".repeat(60)}`).length, 40); -}); diff --git a/test/diff.test.js b/test/diff.test.js deleted file mode 100644 index 7d1aa16..0000000 --- a/test/diff.test.js +++ /dev/null @@ -1,61 +0,0 @@ -"use strict"; -const test = require("node:test"); -const assert = require("node:assert/strict"); -const { diff } = require("./helpers.js"); - -const changes = (before, after) => diff.diffLines(before, after).filter((op) => op.op !== "same").map((op) => [op.op, op.text]); - -test("what changed, line by line, with both numberings", () => { - assert.deepEqual(changes("a\nb\nc", "a\nb\nc"), []); - assert.deepEqual(changes("a\nb\nc", "a\nX\nc"), [["del", "b"], ["add", "X"]]); - assert.deepEqual(changes("a\nc", "a\nb\nc"), [["add", "b"]]); - assert.deepEqual(changes("a\nb\nc", "a\nc"), [["del", "b"]]); - assert.deepEqual(changes("", "a\n"), [["add", "a"]]); - const ops = diff.diffLines("a\nb\nc", "a\nX\nY\nc"); - assert.deepEqual(ops.map((op) => [op.op, op.a, op.b]), [ - ["same", 1, 1], ["del", 2, null], ["add", null, 2], ["add", null, 3], ["same", 3, 4], - ]); -}); - -test("lines moved in the middle of a block are found", () => { - assert.deepEqual(changes("1\n2\n3\n4\n5\n6", "1\n3\n4\nnew\n5\n6"), [["del", "2"], ["add", "new"]]); -}); - -test("a change too large to compare is shown replaced, not lost", () => { - const big = (prefix) => Array.from({ length: 3000 }, (_, i) => `${prefix}${i}`).join("\n"); - const ops = diff.diffLines(big("a"), big("b")); - assert.equal(ops.filter((op) => op.op === "del").length, 3000); - assert.equal(ops.filter((op) => op.op === "add").length, 3000); -}); - -test("a small change in a large file is cheap", () => { - const lines = Array.from({ length: 50000 }, (_, i) => `line ${i}`); - const changed = [...lines]; - changed[25000] = "changed"; - const started = Date.now(); - const ops = diff.diffLines(lines.join("\n"), changed.join("\n")); - assert.ok(Date.now() - started < 1000); - assert.deepEqual(ops.filter((op) => op.op !== "same").map((op) => op.text), ["line 25000", "changed"]); -}); - -test("unchanged stretches fold around the changes", () => { - const lines = Array.from({ length: 20 }, (_, i) => String(i)).join("\n"); - const changed = lines.replace("\n10\n", "\nten\n"); - const hunks = diff.hunks(diff.diffLines(lines, changed)); - assert.deepEqual(hunks.map((hunk) => (hunk.op === "skip" ? hunk.count : hunk.text)), [7, "7", "8", "9", "10", "ten", "11", "12", "13", 6]); - assert.equal(diff.hasChanges(diff.diffLines("a", "a")), false); - assert.equal(diff.hasChanges(diff.diffLines("a", "b")), true); - assert.deepEqual(diff.hunks(diff.diffLines("a\nb", "a\nb")), [{ op: "skip", count: 2 }]); -}); - -test("what a textarea takes away comes back", () => { - assert.equal(diff.normalize("a\r\nb\rc\n"), "a\nb\nc\n"); - assert.equal(diff.restoreEols("a\nb\n", "a\nc\n"), "a\nc\n"); - assert.equal(diff.restoreEols("a\r\nb\r\n", "a\nc\nd\n"), "a\r\nc\r\nd\r\n"); - assert.equal(diff.restoreEols("no end of line", "no end\nof line"), "no end\nof line"); - assert.equal(diff.restoreEols("", "new\n"), "new\n"); - assert.equal(diff.restoreEols("a\r\nb\nc\r\n", "a\nb\nc\n"), "a\r\nb\nc\r\n", "mixed, untouched"); - assert.equal(diff.restoreEols("a\r\nb\nc\r\n", "a\nb\nnew\nc\n"), "a\r\nb\nnew\r\nc\r\n", "a new line takes the common one"); - assert.equal(diff.restoreEols("a\rb\r", "a\nb\nc\n"), "a\rb\rc\r"); - assert.equal(diff.restoreEols("a\r\nb", "a\nb\nc"), "a\r\nb\r\nc", "the old last line had none of its own"); -}); diff --git a/test/dotenv.test.js b/test/dotenv.test.js deleted file mode 100644 index 4f8fa63..0000000 --- a/test/dotenv.test.js +++ /dev/null @@ -1,152 +0,0 @@ -"use strict"; -// Comments, order and every untouched byte survive a save; a value is a value, even -// over several lines, and is never read as a key. -const test = require("node:test"); -const assert = require("node:assert/strict"); -const { dotenv } = require("./helpers.js"); - -const value = (doc, key) => dotenv.rows(doc).find((row) => row.key === key)?.value; -const edit = (text, edits) => dotenv.serialize(dotenv.withValues(dotenv.parse(text), new Map(Object.entries(edits)))); - -const SHAPES = { - empty: "", - "one line, no end of line": "A=1", - plain: "# head\n\nA=1\nB=2\n", - crlf: "# head\r\n\r\nA=1\r\nB=2\r\n", - "mixed endings": "A=1\r\nB=2\nC=3\r\n", - "lone CR": "A=1\rB=2\r", - exported: "export A=1\n export B = 2\n", - spaced: "A = 1\nB= 2\nC =3\n\tD=4\n", - quotes: "A=\"1\"\nB='2'\nC=`3`\nD=\"\"\nE=''\n", - "inline comments": "A=1 # one\nB=\"2\" # two\nC= # three\nD=a#b\n", - "several lines": "A=\"one\ntwo\nB=inside\"\nC='x\ny=z'\nD=1\n", - "CRLF inside a value": "A='one\r\ntwo'\r\nB=2\r\n", - "unclosed quotes": "A=\"open\nB=2\nC='open\nD=4\n", - "escaped quotes": "A=\"say \\\"hi\\\"\"\nB='it\\'s'\nC=\"back\\\\\"\n", - "not understood": "just-a-token\nA=1\n1BAD=2\nKEY: value\n=lonely\n", - duplicates: "A=1\n# again\nA=2\nB=3\nA=4\n", - "blank lines at the end": "A=1\n\n\n", - "trailing blanks": "A=1 \nB=2\t\n", - unicode: "NOM=Éléonore\nÉTÉ=chaud\nA=✓\n", - "equals in a value": "A=b=c==\nURL=https://x.y/?a=1&b=2\n", -}; - -for (const [name, text] of Object.entries(SHAPES)) { - test(`read and written back unchanged: ${name}`, () => { - assert.equal(dotenv.serialize(dotenv.parse(text)), text); - assert.equal(edit(text, {}), text); - }); -} - -test("values are read as parsers read them", () => { - const doc = dotenv.parse(SHAPES.quotes + SHAPES["inline comments"].replace(/^A/gm, "F").replace(/^B/gm, "G").replace(/^C/gm, "H").replace(/^D/gm, "I")); - assert.equal(value(doc, "A"), "1"); - assert.equal(value(doc, "B"), "2"); - assert.equal(value(doc, "C"), "3"); - assert.equal(value(doc, "D"), ""); - assert.equal(value(doc, "E"), ""); - assert.equal(value(doc, "F"), "1", "a comment after a blank is no part of the value"); - assert.equal(value(doc, "G"), "2"); - assert.equal(value(doc, "H"), "", "nothing but a comment"); - assert.equal(value(doc, "I"), "a#b", "a # inside a word is part of it"); - assert.equal(value(dotenv.parse(SHAPES.exported), "B"), "2"); - assert.equal(value(dotenv.parse(SHAPES.spaced), "D"), "4"); - assert.equal(value(dotenv.parse(SHAPES["equals in a value"]), "A"), "b=c=="); - assert.equal(value(dotenv.parse(SHAPES["escaped quotes"]), "A"), 'say "hi"'); - assert.equal(value(dotenv.parse(SHAPES["escaped quotes"]), "B"), "it's"); - assert.equal(value(dotenv.parse(SHAPES["escaped quotes"]), "C"), "back\\"); -}); - -test("what is inside a multi-line value is no key, and an unclosed quote swallows nothing", () => { - const several = dotenv.parse(SHAPES["several lines"]); - assert.deepEqual(dotenv.rows(several).map((row) => row.key), ["A", "C", "D"], "B=inside and y=z belong to values"); - assert.equal(value(several, "A"), "one\ntwo\nB=inside"); - assert.equal(value(several, "C"), "x\ny=z"); - const unclosed = dotenv.parse(SHAPES["unclosed quotes"]); - assert.deepEqual(dotenv.rows(unclosed).map((row) => row.key), ["A", "B", "C", "D"]); - assert.equal(value(unclosed, "A"), '"open'); -}); - -test("a private key over several lines: none of its lines is a key", () => { - const pem = "-----BEGIN KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQ=\nabcDEF123=\n-----END KEY-----"; - const doc = dotenv.parse(`A=1\nPRIVATE_KEY="${pem}"\nB=2\n`); - assert.deepEqual(dotenv.rows(doc).map((row) => row.key), ["A", "PRIVATE_KEY", "B"]); - assert.equal(value(doc, "PRIVATE_KEY"), pem); -}); - -test("a line that is no pair is no key, and is counted to say so", () => { - const doc = dotenv.parse(SHAPES["not understood"]); - assert.deepEqual(dotenv.rows(doc).map((row) => row.key), ["A"]); - assert.equal(dotenv.otherLines(doc), 4); - assert.equal(dotenv.otherLines(dotenv.parse("# comment\n\nA=1\n")), 0); -}); - -test("setting a value changes that line and no other", () => { - assert.equal(edit("# head\n\nA=1\n\n# about b\nB=2 # inline\n# tail\n", { B: "new" }), "# head\n\nA=1\n\n# about b\nB=new # inline\n# tail\n"); - assert.equal(edit("export A=1\n", { A: "2" }), "export A=2\n"); - assert.equal(edit(" A = 1\n", { A: "2" }), " A = 2\n"); - assert.equal(edit('A="1"\n', { A: "2" }), 'A="2"\n', "its quotes are kept when nothing needs them changed"); - assert.equal(edit("A='1'\r\nB=2\r\n", { A: "x" }), "A='x'\r\nB=2\r\n"); - assert.equal(edit("A= # empty\n", { A: "x" }), "A= x # empty\n"); - assert.equal(edit('A="one\ntwo" # c\nB=1\n', { A: "x" }), 'A="x" # c\nB=1\n'); - assert.equal(edit("A=1\n", { A: "1" }), "A=1\n"); -}); - -test("a new key goes at the end, in the file's line endings, and nothing moves", () => { - assert.equal(edit("A=1\n", { Z: "9" }), "A=1\nZ=9\n"); - assert.equal(edit("A=1", { Z: "9" }), "A=1\nZ=9\n", "the last line gets its end of line first"); - assert.equal(edit("A=1\r\nB=2\r\n", { Z: "9" }), "A=1\r\nB=2\r\nZ=9\r\n"); - assert.equal(edit("", { Z: "9" }), "Z=9\n"); - assert.equal(edit("# only a comment\n", { Z: "9", Y: "8" }), "# only a comment\nZ=9\nY=8\n"); -}); - -test("a key defined twice shows once, and the last line is the one read and edited", () => { - const doc = dotenv.parse(SHAPES.duplicates); - const a = dotenv.rows(doc).find((row) => row.key === "A"); - assert.equal(a.value, "4"); - assert.equal(a.count, 3); - assert.equal(edit(SHAPES.duplicates, { A: "x" }), "A=1\n# again\nA=2\nB=3\nA=x\n"); -}); - -test("any value is read back the same once written", () => { - const values = [ - "plain", "with space", " leading", "trailing ", "#hash", "a #b", "it's", 'say "hi"', "both ' and \"", "back\\slash", "ends\\", - "$HOME", "${HOME}", "`tick`", "two\nlines", "two\r\nlines", "it's\ntwo", "a=b", "é✓", "=", "'", '"', "\\", "\\n", "'\\n'", "tab\there", - ]; - for (const original of ["A=1\n", 'A="1"\n', "A='1'\n", "export A = 1 # c\n"]) { - for (const wanted of values) { - const text = edit(original, { A: wanted, B: wanted }); - const doc = dotenv.parse(text); - assert.equal(value(doc, "A"), wanted, `${JSON.stringify(wanted)} over ${JSON.stringify(original)}: ${JSON.stringify(text)}`); - assert.equal(value(doc, "B"), wanted, `${JSON.stringify(wanted)} as a new key: ${JSON.stringify(text)}`); - assert.deepEqual(dotenv.rows(doc).map((row) => row.key), ["A", "B"], JSON.stringify(text)); - } - } -}); - -test("the comment above a key is its hint, but a value put aside in a comment is not", () => { - const rows = dotenv.rows(dotenv.parse("# Get one at the dashboard\n# (free)\nA=1\n\n# unrelated\n\nB=2\n# OLD_TOKEN=abc123\n#export C=1\nC=3\n")); - assert.equal(rows[0].hint, "Get one at the dashboard (free)"); - assert.equal(rows[1].hint, "", "a blank line cuts the link"); - assert.equal(rows[2].hint, ""); -}); - -test("which keys changed: names only", () => { - const changed = dotenv.changedKeys(dotenv.parse("A=1\nB=2\nC=\nD=4\n"), dotenv.parse("A=1\nB=x\nC=y\nD=\nE=z\nF=\n")); - assert.deepEqual(changed, { set: ["B", "C", "E"], emptied: ["D"] }); -}); - -test("what counts as a dotenv file, and what as a template", () => { - for (const path of [".env", ".env.local", "config/.env.production", "app.env", "a/b/prod.ENV", ".env.example"]) { - assert.ok(dotenv.isDotenvPath(path), path); - } - for (const path of [".envrc", "env", "env.json", "dotenv", ".environment", "config.yaml", ".env/file"]) { - assert.ok(!dotenv.isDotenvPath(path), path); - } - assert.ok(dotenv.isExamplePath("sub/.env.example")); - assert.ok(dotenv.isExamplePath(".env.sample")); - assert.ok(!dotenv.isExamplePath(".env")); - assert.ok(!dotenv.isExamplePath(".env.local")); - assert.deepEqual(dotenv.exampleCandidates("sub/.env.local").slice(0, 3), ["sub/.env.local.example", "sub/.env.local.sample", "sub/.env.example"]); - assert.ok(!dotenv.exampleCandidates(".env.example").includes(".env.example")); -}); diff --git a/test/gitignore.test.js b/test/gitignore.test.js deleted file mode 100644 index 548e577..0000000 --- a/test/gitignore.test.js +++ /dev/null @@ -1,115 +0,0 @@ -"use strict"; -// Git's rules, and git itself as the judge: the table below is run through -// `git check-ignore` in a temporary repository when git is on the machine. -const test = require("node:test"); -const assert = require("node:assert/strict"); -const fs = require("node:fs"); -const os = require("node:os"); -const path = require("node:path"); -const { spawnSync } = require("node:child_process"); -const { gitignore } = require("./helpers.js"); - -const root = (text) => [{ dir: "", text }]; - -// [.gitignore, path, ignored?] -const TABLE = [ - ["", ".env", false], - [".env\n", ".env", true], - [".env\n", "sub/.env", true], - ["/.env\n", ".env", true], - ["/.env\n", "sub/.env", false], - ["sub/.env\n", "sub/.env", true], - ["sub/.env\n", "other/sub/.env", false], - [".env*\n", ".env.local", true], - [".env*\n", "sub/.env", true], - ["*.env\n", "app.env", true], - ["*.env\n", ".env", true], - ["*.env\n", "sub/app.env", true], - [".env\n!.env\n", ".env", false], - [".env*\n!.env.example\n", ".env.example", false], - [".env*\n!.env.example\n", ".env.local", true], - ["!.env\n.env\n", ".env", true], - ["# .env\n", ".env", false], - ["\\#x\n", "#x", true], - ["\\!x\n", "!x", true], - ["config/\n", "config/.env", true], - ["config/\n", "a/config/.env", true], - ["config/\n", "config", false], - ["/config/\n", "a/config/.env", false], - ["config\n", "config", true], - ["config\n", "config/.env", true], - ["config/*\n!config/.env\n", "config/.env", false], - ["config/\n!config/.env\n", "config/.env", true], - ["**/.env\n", "a/b/.env", true], - ["**/.env\n", ".env", true], - ["a/**/.env\n", "a/.env", true], - ["a/**/.env\n", "a/b/c/.env", true], - ["a/**\n", "a/b/.env", true], - ["a/**\n", "a", false], - ["*\n", "a/b", true], - ["*\n!a/\n!a/b\n", "a/b", false], - [".en?\n", ".env", true], - [".en?\n", ".env/x", true], - [".e[nm]v\n", ".env", true], - [".e[!n]v\n", ".env", false], - [".e[a-z]v\n", ".env", true], - [" .env\n", ".env", false], - [".env \n", ".env", true], - [".env\r\n", ".env", true], - ["a b\n", "a b", true], - ["foo*bar\n", "foo/bar", false], - ["a/*/b\n", "a/x/b", true], - ["a/*/b\n", "a/x/y/b", false], - ["[\n", "[", false], -]; - -test("git's rules", () => { - for (const [text, file, expected] of TABLE) { - assert.equal(gitignore.isIgnored(root(text), file), expected, `${JSON.stringify(text)} on ${file}`); - } -}); - -test("deeper .gitignore files have the last word", () => { - const sources = [{ dir: "", text: ".env\n" }, { dir: "sub", text: "!.env\n" }]; - assert.equal(gitignore.isIgnored(sources, "sub/.env"), false); - assert.equal(gitignore.isIgnored(sources, ".env"), true); - assert.equal(gitignore.isIgnored(sources, "other/.env"), true); - assert.equal(gitignore.isIgnored([{ dir: "sub", text: "/x\n" }], "sub/x"), true); - assert.equal(gitignore.isIgnored([{ dir: "sub", text: "/x\n" }], "x"), false); - assert.equal(gitignore.isIgnored([{ dir: "sub", text: "/x\n" }], "sub/y/x"), false); -}); - -test("the .gitignore files that have a say", () => { - assert.deepEqual(gitignore.sourcesFor(".env"), [{ dir: "", path: ".gitignore" }]); - assert.deepEqual(gitignore.sourcesFor("a/b/.env").map((source) => source.path), [".gitignore", "a/.gitignore", "a/b/.gitignore"]); -}); - -test("the line a click adds ignores that very file, whatever its name", () => { - for (const file of [".env", "sub/.env", "a b/.env", "we[ird]/.env", "st*r/.env", "#x/.env", "!x/.env", "back\\slash.env"]) { - const pattern = gitignore.patternFor(file); - assert.ok(gitignore.isIgnored(root(`${pattern}\n`), file), `${file} by ${pattern}`); - } - assert.equal(gitignore.patternFor(".env"), ".env"); - assert.equal(gitignore.withPattern("", ".env"), ".env\n"); - assert.equal(gitignore.withPattern("a\n", ".env"), "a\n.env\n"); - assert.equal(gitignore.withPattern("a", ".env"), "a\n.env\n"); - assert.equal(gitignore.withPattern("a\r\nb\r\n", ".env"), "a\r\nb\r\n.env\r\n"); -}); - -const git = (cwd, ...args) => spawnSync("git", args, { cwd, encoding: "utf8", windowsHide: true }); - -test("git agrees with the table", { skip: git(os.tmpdir(), "--version").status !== 0 && "git is not installed" }, () => { - for (const [text, file, expected] of TABLE) { - // Names Windows cannot create are for the logic above, not for git here. - if (process.platform === "win32" && /[*?[\]]/.test(file)) continue; - const dir = fs.mkdtempSync(path.join(os.tmpdir(), "editor-kit-")); - try { - git(dir, "init", "-q"); - fs.writeFileSync(path.join(dir, ".gitignore"), text); - const answer = git(dir, "-c", "core.excludesFile=", "-c", "core.ignorecase=false", "check-ignore", "--no-index", "-q", file); - assert.equal(answer.status === 0, expected, `git says otherwise of ${JSON.stringify(text)} on ${file}: ${answer.status} ${answer.stderr}`); - } finally { - fs.rmSync(dir, { recursive: true, force: true }); - } - } -}); diff --git a/test/hangar-ui.js b/test/hangar-ui.js deleted file mode 100644 index 8bf4350..0000000 --- a/test/hangar-ui.js +++ /dev/null @@ -1,48 +0,0 @@ -"use strict"; -// Hangar's own files, which some tests compare against: Hangar UI's sheet, so that a class a page -// names exists, and the docs, so that a method it calls is documented. Hangar ships them, so this -// repository holds no copy. CI gets them at the tag the manifest's `hangar` names and passes the -// folder in HANGAR_UI_DIR. Without them, the tests that need them skip and say so. -// -// node test/hangar-ui.js --get into .hangar-ui/, which git ignores -// node test/hangar-ui.js --get v1.9.0 from another Hangar tag -const fs = require("node:fs"); -const path = require("node:path"); - -const KIT = path.join(__dirname, ".."); -const DIR = process.env.HANGAR_UI_DIR ? path.resolve(process.env.HANGAR_UI_DIR) : path.join(KIT, ".hangar-ui"); -const FILES = { - "kit.css": "src-tauri/kit-sdk/kit.css", - "kit.js": "src-tauri/kit-sdk/kit.js", - "kit-ui.js": "src-tauri/kit-sdk/kit-ui.js", - "kits.md": "docs/kits.md", - "kit-ui.md": "docs/kit-ui.md", -}; -const HANGAR_FILES_MISSING = "Hangar's files are not here: run `node test/hangar-ui.js --get`, then the tests again"; - -/** The path of one of Hangar's files, or null when it is not here. */ -function hangarFile(name) { - const file = path.join(DIR, name); - return fs.existsSync(file) ? file : null; -} - -async function get(ref) { - const manifest = JSON.parse(fs.readFileSync(path.join(KIT, "hangar-kit.json"), "utf8")); - const tag = ref || `v${String(manifest.hangar).match(/\d+\.\d+\.\d+/)}`; - fs.mkdirSync(DIR, { recursive: true }); - for (const [name, source] of Object.entries(FILES)) { - const answer = await fetch(`https://raw.githubusercontent.com/hangar-ai/hangar/${tag}/${source}`); - if (!answer.ok) throw new Error(`Hangar ${tag} has no ${source} (${answer.status}). It may not be tagged yet.`); - fs.writeFileSync(path.join(DIR, name), Buffer.from(await answer.arrayBuffer())); - } - console.log(`Hangar's files of ${tag} are in ${DIR}`); -} - -if (process.argv[2] === "--get") { - get(process.argv[3]).catch((error) => { - console.error(error.message); - process.exitCode = 1; - }); -} - -module.exports = { hangarFile, HANGAR_FILES_MISSING }; diff --git a/test/helpers.js b/test/helpers.js deleted file mode 100644 index 2117c08..0000000 --- a/test/helpers.js +++ /dev/null @@ -1,138 +0,0 @@ -"use strict"; -// Shared by the tests: the libraries as the page gets them, a fake window.hangar over -// files held in memory (no test touches a real file of anyone's), and a fake DOM. -const path = require("node:path"); - -const KIT = path.join(__dirname, ".."); -const TAB = path.join(KIT, "tabs", "editor"); - -const logic = require(path.join(TAB, "logic.js")); -const dotenv = require(path.join(TAB, "dotenv.js")); -const validate = require(path.join(TAB, "validate.js")); -const diff = require(path.join(TAB, "diff.js")); -const gitignore = require(path.join(TAB, "gitignore.js")); -const answer = require(path.join(TAB, "answer.js")); -const { createController } = require(path.join(TAB, "controller.js")); -const lib = { logic, dotenv, validate, diff, gitignore, answer }; - -const settle = async () => { - for (let i = 0; i < 20; i++) await new Promise((resolve) => setImmediate(resolve)); -}; - -const refusal = (code, message) => Object.assign(new Error(message || code), { code }); - -/** - * A window.hangar that answers as docs/kits.md says, over `files` (path → text): - * `files.read` says not_found for what is absent and drops a BOM, `files.write` with - * `expected` answers conflict when the file holds anything else or is gone, and - * `deny` lists the methods answered `denied`. `sendError` makes panes.send refuse. - */ -function fakeHangar({ params = {}, caller = null, files = {}, deny = [], sendError = null, writeError = null, truncated = false } = {}) { - const store = new Map(Object.entries(files)); - const calls = []; - const listeners = new Map(); - const hangar = { - calls, - store, - callsTo: (method) => calls.filter((call) => call.method === method), - emit: (event, data) => (listeners.get(event) || []).forEach((fn) => fn(data)), - on(event, fn) { - listeners.set(event, [...(listeners.get(event) || []), fn]); - return () => listeners.set(event, (listeners.get(event) || []).filter((other) => other !== fn)); - }, - /** What the next `files.write` finds on disk, as if a program had just written it. */ - sendError, - writeError, - async call(method, args) { - calls.push({ method, args }); - if (deny.includes(method)) throw refusal("denied", `this tab was not granted ${method}`); - switch (method) { - case "tab.params": - return { params, caller }; - case "tab.setTitle": - case "tab.setBadge": - return {}; - case "files.read": - if (!store.has(args.path)) throw refusal("not_found", `${args.path} was not found in the workspace folder`); - return store.get(args.path).replace(/^/, ""); - case "files.list": - return { files: [...store.keys()].map((file) => ({ path: file, size: store.get(file).length, modified: 0 })), truncated }; - case "files.write": { - if (hangar.writeError) throw refusal(hangar.writeError); - if (args.expected !== undefined) { - const now = store.has(args.path) ? store.get(args.path).replace(/^/, "") : null; - if (now !== args.expected) throw refusal("conflict", "the file changed"); - } - store.set(args.path, args.text); - return {}; - } - case "panes.send": - if (hangar.sendError) throw refusal(hangar.sendError); - return { queued: true, pane: args.pane }; - default: - throw refusal("unknown", `unknown ${method}`); - } - }, - }; - return hangar; -} - -/** A controller already started on these params, and its fake Hangar. */ -async function opened(options = {}) { - const hangar = options.hangar || fakeHangar(options); - const changes = []; - const controller = createController({ hangar, lib, lang: options.lang || "en", onChange: (state) => changes.push(state.view) }); - await controller.start(); - await settle(); - return { hangar, controller, state: controller.state, changes }; -} - -const row = (state, key) => state.form.rows.find((other) => other.key === key); - -/** Just enough DOM for view.js: elements, text, children, properties. */ -class FakeNode { - constructor(tag) { - this.tag = tag; - this.className = ""; - this.children = []; - this.attributes = {}; - this.style = {}; - } - set textContent(text) { - this.children = [String(text)]; - } - get textContent() { - return this.text; - } - append(...nodes) { - this.children.push(...nodes); - } - replaceChildren(...nodes) { - this.children = nodes; - } - setAttribute(name, value) { - this.attributes[name] = String(value); - } - getAttribute(name) { - return this.attributes[name] === undefined ? null : this.attributes[name]; - } - focus() { - fakeDocument.activeElement = this; - } - get text() { - return this.children.map((child) => (typeof child === "string" ? child : child.text)).join(""); - } - find(predicate, found = []) { - if (predicate(this)) found.push(this); - for (const child of this.children) if (typeof child !== "string") child.find(predicate, found); - return found; - } - /** Every string this node and those below it hold or show, attributes and values included. */ - everything() { - const own = [this.value, this.placeholder, this.title, ...Object.values(this.attributes)].filter((item) => typeof item === "string"); - return [...own, ...this.children.flatMap((child) => (typeof child === "string" ? [child] : child.everything()))]; - } -} -const fakeDocument = { createElement: (tag) => new FakeNode(tag), activeElement: null }; - -module.exports = { KIT, TAB, lib, logic, dotenv, validate, diff, gitignore, answer, createController, settle, refusal, fakeHangar, opened, row, FakeNode, fakeDocument }; diff --git a/test/manifest.test.js b/test/manifest.test.js index d91a96c..3f28d41 100644 --- a/test/manifest.test.js +++ b/test/manifest.test.js @@ -1,13 +1,13 @@ "use strict"; -// The manifest, checked by hand against docs/kits.md: Hangar's validator is Rust -// (src-tauri/src/kits/manifest.rs) and cannot be reached from a Node test. A value's -// rule is written in what Rust and JavaScript read alike, as Hangar's window reads it. +// The manifest and the plugin, checked by hand against docs/kits.md: Hangar's validator is Rust +// and cannot be reached from a Node test. A value's rule is written in what Rust and JavaScript +// read alike. The native tab's own tests are native/tests (cargo test). const test = require("node:test"); const assert = require("node:assert/strict"); const fs = require("node:fs"); const path = require("node:path"); -const { KIT, TAB } = require("./helpers.js"); -const { hangarFile, HANGAR_FILES_MISSING } = require("./hangar-ui.js"); + +const KIT = path.join(__dirname, ".."); const manifest = JSON.parse(fs.readFileSync(path.join(KIT, "hangar-kit.json"), "utf8")); const exists = (relative) => fs.existsSync(path.join(KIT, relative)); @@ -21,12 +21,12 @@ function safePath(relative, extensions, at) { } test("the manifest's own fields", () => { - assert.equal(manifest.schema, 1); + assert.equal(manifest.schema, 2); assert.equal(manifest.id, "editor"); assert.equal(manifest.name, "Editor"); assert.match(manifest.version, /^\d+\.\d+\.\d+$/); assert.ok(manifest.description.trim()); - assert.equal(manifest.hangar, ">=1.9.0"); + assert.equal(manifest.hangar, ">=2.0.0"); assert.equal(manifest.homepage, "https://github.com/hangar-ai/kit-editor"); safePath(manifest.icon, [".svg"], "icon"); }); @@ -52,12 +52,26 @@ test("the tab: three permissions and nothing more, one tab per set of params", ( const [tab] = manifest.tabs; assert.equal(tab.id, "editor"); assert.equal(tab.title, "Editor"); - safePath(tab.entry, [".html"], "entry"); + safePath(tab.entry, [".wasm"], "entry"); safePath(tab.icon, [".svg"], "icon"); assert.deepEqual([...tab.permissions].sort(), ["files.read", "files.write", "panes.send"]); assert.notEqual(tab.singleton, true, "one tab per file: another file is another tab"); }); +test("the tab is native: schema 2, a .wasm inside the kit as its entry, no page", () => { + const [tab] = manifest.tabs; + assert.equal(manifest.schema, 2, "an entry that is a module needs schema 2"); + safePath(tab.entry, [".wasm"], "entry"); + assert.equal(tab.entry, "tabs/editor.wasm"); + assert.equal(tab.native, undefined, "the entry is the module itself"); + assert.ok(!exists("tabs/editor"), "no HTML page is left"); + const module = fs.readFileSync(path.join(KIT, tab.entry)); + assert.deepEqual([...module.subarray(0, 4)], [0x00, 0x61, 0x73, 0x6d], "a WebAssembly module"); + assert.ok(fs.existsSync(path.join(KIT, "native", "Cargo.toml")), "built from native/"); + assert.ok(fs.existsSync(path.join(KIT, "native", "Cargo.lock")), "its versions pinned"); + assert.ok(fs.existsSync(path.join(KIT, "scripts", "build-native.sh")), "by scripts/build-native.sh"); +}); + test("the params: what is declared, what each rule lets through", () => { const { params } = manifest.tabs[0]; assert.deepEqual(Object.keys(params).sort(), ["keys", "line", "path", "why"]); @@ -93,48 +107,11 @@ test("the skill says what the brief says", () => { assert.match(skill, /Wait/); }); -test("the tab's page loads only the kit's own files and Hangar's", () => { - const html = fs.readFileSync(path.join(TAB, "index.html"), "utf8"); - const sources = [...html.matchAll(/(?:src|href)="([^"]+)"/g)].map((match) => match[1]); - const own = sources.filter((source) => !source.startsWith("/_hangar/")); - assert.deepEqual(sources.filter((source) => source.startsWith("/_hangar/")).sort(), ["/_hangar/kit-ui.js", "/_hangar/kit.css", "/_hangar/kit.js"]); - for (const source of own) { - assert.doesNotMatch(source, /^([a-z]+:)?\/\//i, `${source} leaves the kit`); - assert.doesNotMatch(source, /^\//, `${source} must be relative`); - assert.ok(fs.existsSync(path.join(TAB, source)), source); - } - for (const name of fs.readdirSync(TAB)) { - const text = fs.readFileSync(path.join(TAB, name), "utf8"); - assert.doesNotMatch(text, /\bfetch\(|XMLHttpRequest|WebSocket|localStorage|sessionStorage|\beval\(|innerHTML|outerHTML|insertAdjacentHTML|document\.write|@import|url\(\s*["']?https?:|console\.log/, `${name} reaches outside what a tab may`); - } - const everyScript = fs.readdirSync(TAB).filter((name) => name.endsWith(".js")); - assert.deepEqual(own.filter((source) => source.endsWith(".js")).sort(), everyScript.sort(), "every script is loaded"); -}); - -test("the page calls nothing it did not ask for", () => { - const allowed = new Set(["tab.params", "tab.setTitle", "tab.setBadge", "files.read", "files.write", "files.list", "panes.send"]); - const seen = new Set(); - for (const name of fs.readdirSync(TAB).filter((file) => file.endsWith(".js"))) { - const text = fs.readFileSync(path.join(TAB, name), "utf8"); - for (const [, method] of text.matchAll(/hangar\.call\("([\w.]+)"/g)) seen.add(method); - } - for (const method of seen) assert.ok(allowed.has(method), method); - for (const method of allowed) assert.ok(seen.has(method), `${method} is declared but unused`); -}); - -test("the permissions and methods used are in the docs, when the docs are around", (t) => { - const docs = hangarFile("kits.md"); - if (!docs) return t.skip(HANGAR_FILES_MISSING); - const text = fs.readFileSync(docs, "utf8"); - for (const permission of manifest.tabs[0].permissions) assert.ok(text.includes(`\`${permission}\``), permission); - for (const method of ["tab.params", "tab.setTitle", "tab.setBadge", "files.list", "kit_tab_open"]) assert.ok(text.includes(`\`${method}\``), method); -}); - test("nothing personal, nothing outside its folder is named", () => { const files = []; const walk = (dir) => { for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { - if ([".git", ".hangar-ui", "node_modules"].includes(entry.name)) continue; + if ([".git", ".hangar-ui", "node_modules", "target"].includes(entry.name)) continue; if (entry.isDirectory()) walk(path.join(dir, entry.name)); else files.push(path.join(dir, entry.name)); } diff --git a/test/no-value-reaches-an-agent.test.js b/test/no-value-reaches-an-agent.test.js deleted file mode 100644 index 4656344..0000000 --- a/test/no-value-reaches-an-agent.test.js +++ /dev/null @@ -1,274 +0,0 @@ -"use strict"; -// The proof the kit stands on: whatever the file holds, whatever the person types, -// however the save goes, no value reaches panes.send. Every test drives the real -// controller against a fake Hangar, marks every value with a sentinel, and looks at -// what left the page: panes.send above all, and every other call but the file ones. -const test = require("node:test"); -const assert = require("node:assert/strict"); -const fs = require("node:fs"); -const path = require("node:path"); -const { TAB, answer, fakeHangar, opened, settle } = require("./helpers.js"); - -const CALLER = { pane: "Asker" }; - -/** A deterministic generator: a failure here can be run again as it is. */ -function randomizer(seed) { - let state = seed >>> 0 || 1; - const next = () => { - state ^= state << 13; - state ^= state >>> 17; - state ^= state << 5; - state >>>= 0; - return state; - }; - return { int: (max) => next() % max, pick: (list) => list[next() % list.length] }; -} - -/** What every message must look like: fixed sentences, a path, names, counts. Nothing else fits. */ -const SHAPE = new RegExp( - "^The person (?:saved|checked) `[^`\\n]+`(?:" + - ": the file changed\\.|" + - " and changed nothing\\.(?: (?:Already set|Still empty): [A-Za-z_][\\w.-]*(?:, [A-Za-z_][\\w.-]*)*\\.)*(?: \\d+ other keys? set or empty\\.)?(?: The values stay in the file: do not read them back, use them through the program that loads it\\.)?|" + - "\\.(?: (?:Set|Emptied|Still empty): [A-Za-z_][\\w.-]*(?:, [A-Za-z_][\\w.-]*)*\\.)*(?: \\d+ other keys? changed or empty\\.)? The values stay in the file: do not read them back, use them through the program that loads it\\." + - ")$", -); - -function assertClean(hangar, secrets, label) { - const sent = hangar.callsTo("panes.send"); - for (const call of sent) { - assert.match(call.args.text, SHAPE, `${label}: not one of the fixed sentences: ${call.args.text}`); - for (const secret of secrets) { - assert.ok(!call.args.text.includes(secret), `${label}: a value reached panes.send: ${secret} in ${call.args.text}`); - } - } - // Only the file calls may carry a value, and only to the file itself. - for (const call of hangar.calls) { - if (call.method === "files.write" || call.method === "files.read") continue; - const seen = JSON.stringify(call.args === undefined ? null : call.args); - for (const secret of secrets) assert.ok(!seen.includes(secret), `${label}: ${secret} left in ${call.method}: ${seen}`); - } - return sent; -} - -const S = (n) => `s3cr3t-${n}-XqZ9`; - -/** Every way a value can sit in a dotenv file, and the values to look for. */ -const HOSTILE_LINES = [ - (v) => `PLAIN=${v}`, - (v) => `export EXPORTED=${v}`, - (v) => `SPACED = ${v}`, - (v) => `DOUBLE="${v}"`, - (v) => `SINGLE='${v}'`, - (v) => `TICK=\`${v}\``, - (v) => `INLINE=${v} # also ${v}`, - (v) => `# COMMENTED=${v}`, - (v) => `#${v}`, - (v) => `${v}`, // a token alone on its line - (v) => `MULTI="first ${v}\nINNER_KEY=${v}\nlast"`, - (v) => `MULTISINGLE='${v}\nOTHER=${v}'`, - (v) => `UNCLOSED="${v}`, - (v) => `DUP=${v}`, - (v) => `DUP=${v}x`, - (v) => `COLON: ${v}`, - (v) => `EQUALS=${v}=${v}==`, - (v) => `A${v.replace(/-/g, "_")}=${v.replace(/-/g, "_")}`, // the value is also in the key's name - (v) => `${v.replace(/-/g, "_")}=${v.replace(/-/g, "_")}`, // a key that is its own value - (v) => `NOTE=see ${v.replace(/-/g, "_")}`, -]; - -test("every hostile line, one by one: the answer holds no value", async () => { - for (const [index, line] of HOSTILE_LINES.entries()) { - const secret = S(index); - const text = `# head\n${line(secret)}\nTARGET=old\n`; - const { hangar, controller, state } = await opened({ - params: { path: ".env", keys: "TARGET,NEW_KEY" }, caller: CALLER, files: { ".env": text, ".gitignore": ".env\n" }, - }); - controller.editRow("TARGET", `${secret}-typed`); - controller.editRow("NEW_KEY", `${secret}-new`); - for (const each of state.form.rows) controller.editRow(each.key, `${each.value}-${secret}`); - await controller.saveForm(); - await settle(); - const sent = assertClean(hangar, [secret, secret.replace(/-/g, "_")], `line ${index}`); - assert.equal(sent.length, 1, `line ${index}: it answered once`); - } -}); - -test("random files, random edits, 400 of them: the answer holds no value", async () => { - const random = randomizer(20261031); - const eols = ["\n", "\r\n"]; - const keys = ["API_KEY", "DB_URL", "TOKEN", "PORT", "A.B", "x-y", "_z", "DEBUG"]; - for (let run = 0; run < 400; run++) { - const secrets = []; - const secret = () => { - const value = `v${run}-${secrets.length}-${random.int(1e9).toString(36)}Q`; - secrets.push(value); - return value; - }; - const eol = random.pick(eols); - const lines = []; - for (let i = random.int(12); i >= 0; i--) lines.push(random.pick(HOSTILE_LINES)(secret())); - for (const key of keys) if (random.int(2)) lines.splice(random.int(lines.length + 1), 0, `${key}=${secret()}`); - const text = lines.join(eol) + (random.int(2) ? eol : ""); - const example = random.int(2) ? { ".env.example": `# say what\nFROM_EXAMPLE=${secret()}\nAPI_KEY=${secret()}\n` } : {}; - const ignore = random.int(2) ? { ".gitignore": ".env\n" } : {}; - const asked = keys.filter(() => random.int(3) === 0).join(","); - const { hangar, controller, state } = await opened({ - params: { path: ".env", ...(asked ? { keys: asked } : {}), why: "for the test" }, - caller: CALLER, - files: { ".env": text, ...example, ...ignore }, - }); - - assert.equal(state.view, "dotenv", `run ${run}`); - for (const each of [...state.form.rows]) { - const dice = random.int(4); - if (dice === 0) controller.editRow(each.key, secret()); - else if (dice === 1) controller.editRow(each.key, ""); - else if (dice === 2) controller.editRow(each.key, `${secret()}\n${secret()}=x`); - } - if (state.form.offered.length && random.int(2)) controller.addAllOffered(); - if (random.int(4) === 0) { - // The person pastes a secret where the name of a new key goes. - const pasted = `Pasted_${secret().replace(/-/g, "_")}`; - secrets.push(pasted); - controller.setNewKey(pasted); - controller.addNewKey(); - controller.editRow(pasted, secret()); - } - // The file may have moved in the meantime, and the person chooses. - if (random.int(4) === 0) hangar.store.set(".env", `# moved\nMOVED=${secret()}\n${text}`); - if (controller.isDirty()) await controller.saveForm(); - else await controller.tellNoChange(); - await settle(); - if (state.conflict) { - if (random.int(2)) await controller.conflictKeepMine(); - else await controller.conflictTakeTheirs(); - await settle(); - await controller.tellNoChange(); - await settle(); - } - assertClean(hangar, secrets, `run ${run} of ${JSON.stringify(text)}`); - } -}); - -test("a text file: only that it changed, whatever it holds", async () => { - const secret = S("text"); - const files = { - "config.json": `{ "password": "${secret}" }\n`, - "values.yaml": `password: ${secret}\n`, - "app.toml": `password = "${secret}"\n`, - "notes.txt": `${secret}\n`, - }; - for (const file of Object.keys(files)) { - const { hangar, controller, state } = await opened({ params: { path: file }, caller: CALLER, files }); - controller.editText(`${state.text.value}# ${secret}-typed\n`); - controller.review(); - controller.setAck(true); - await controller.saveText(); - await settle(); - const [sent] = assertClean(hangar, [secret], file); - assert.equal(sent.args.text, `The person saved \`${file}\`: the file changed.`); - } -}); - -test("failures and retries carry no value either", async () => { - const secret = S("retry"); - for (const code of ["not_found", "denied", "unavailable", "rate_limited"]) { - const { hangar, controller, state } = await opened({ - params: { path: ".env", keys: "A" }, caller: CALLER, files: { ".env": `A=${secret}\n`, ".gitignore": ".env\n" }, sendError: code, - }); - controller.editRow("A", `${secret}2`); - await controller.saveForm(); - await settle(); - assert.equal(state.told.status, "failed"); - hangar.sendError = null; - await controller.retryTell(); - await settle(); - assert.equal(state.told.status, "sent"); - const sent = assertClean(hangar, [secret], code); - assert.equal(sent.length, 2); - assert.equal(sent[0].args.text, sent[1].args.text, "the same message, sent again"); - } -}); - -test("with nobody to answer, nothing is sent", async () => { - const { hangar, controller } = await opened({ params: { path: ".env" }, files: { ".env": "A=1\n", ".gitignore": ".env\n" } }); - controller.editRow("A", "2"); - await controller.saveForm(); - await settle(); - assert.equal(hangar.callsTo("panes.send").length, 0); - assert.equal(hangar.store.get(".env"), "A=2\n"); -}); - -test("the message is made of names: what is not a name, or is a value, stays unsaid", () => { - const known = new Set(["API_KEY", "hunter2hunter2", "HAS_hunter2hunter2_IN", "SHORT", "Bad Name", "a=b"]); - const text = answer.dotenvSaved({ - path: ".env", - set: ["API_KEY", "hunter2hunter2", "HAS_hunter2hunter2_IN", "NEVER_SEEN", "Bad Name", "a=b", "line\nbreak", 42], - emptied: [], - stillEmpty: ["SHORT"], - known, - values: ["hunter2hunter2", "x"], - }); - assert.equal( - text, - "The person saved `.env`. Set: API_KEY. Still empty: SHORT. 7 other keys changed or empty. The values stay in the file: do not read them back, use them through the program that loads it.", - ); - assert.ok(answer.mayName("A1", new Set(["A1"]), ["1"]), "a short value does not silence a name by chance"); - assert.ok(!answer.mayName("A1", new Set(["A1"]), ["A1"]), "but a name that is a value does"); - assert.ok(!answer.mayName("x".repeat(65), new Set(["x".repeat(65)]), []), "a name this long reads as a token"); -}); - -test("a key the person typed is counted, never named", async () => { - const { hangar, controller } = await opened({ params: { path: ".env", keys: "A" }, caller: CALLER, files: { ".env": "A=\n", ".gitignore": ".env\n" } }); - controller.setNewKey("sk_live_PASTED_BY_MISTAKE"); - controller.addNewKey(); - controller.editRow("sk_live_PASTED_BY_MISTAKE", "whatever"); - controller.editRow("A", "filled"); - await controller.saveForm(); - await settle(); - const [{ args }] = hangar.callsTo("panes.send"); - assert.match(args.text, /Set: A\. 1 other key changed or empty\./); - assert.ok(!args.text.includes("sk_live")); -}); - -test("a long list of keys stays a list of names, and within what panes.send carries", async () => { - const lines = Array.from({ length: 300 }, (_, i) => `KEY_${i}=old${i}`).join("\n"); - const { hangar, controller, state } = await opened({ params: { path: ".env" }, caller: CALLER, files: { ".env": lines, ".gitignore": ".env\n" } }); - for (const each of state.form.rows) controller.editRow(each.key, `new-${each.key}`); - await controller.saveForm(); - await settle(); - const [{ args }] = assertClean(hangar, ["new-KEY", "old1"], "long"); - assert.match(args.text, /260 other keys changed or empty\./); - assert.ok(args.text.length < 20000); -}); - -test("in the sources: one panes.send, fed by answer.js alone", () => { - const sources = fs.readdirSync(TAB).filter((name) => name.endsWith(".js")); - const uses = sources.flatMap((name) => { - const text = fs.readFileSync(path.join(TAB, name), "utf8"); - return (text.match(/["']panes\.send["']/g) || []).map(() => name); - }); - assert.deepEqual(uses, ["controller.js"], "panes.send is called from one place"); - const controller = fs.readFileSync(path.join(TAB, "controller.js"), "utf8"); - assert.match(controller, /hangar\.call\("panes\.send", \{ pane, text: message \}\)/); - // Each `send(` is given what answer.js made, or the message already made for it. - const senders = controller.match(/\bsend\([^)]*\)/g).filter((call) => !call.startsWith("send(message, status)")); - for (const call of senders) assert.match(call, /^send\((message|answer\.\w+|unsent\.message)/, call); - // And answer.js takes no field that could carry a value but `values`, used only to stay silent. - const speech = fs.readFileSync(path.join(TAB, "answer.js"), "utf8"); - assert.doesNotMatch(speech, /\$\{\s*values/); - assert.doesNotMatch(speech, /\.value\b/); -}); - -test("the fuzz would catch a leak: a value in the message fails the checks", () => { - // Guards the checks themselves: a broken answer.js must not slip past `assertClean`. - const fake = fakeHangar(); - fake.calls.push({ method: "panes.send", args: { pane: "Asker", text: `The person saved \`.env\`. Set: API_KEY=${S("leak")}. The values stay in the file: do not read them back, use them through the program that loads it.` } }); - assert.throws(() => assertClean(fake, [S("leak")], "planted")); - const named = fakeHangar(); - named.calls.push({ method: "panes.send", args: { pane: "Asker", text: `The person saved \`.env\`. Set: ${S("leak").replace(/-/g, "_")}. The values stay in the file: do not read them back, use them through the program that loads it.` } }); - assert.throws(() => assertClean(named, [S("leak").replace(/-/g, "_")], "planted name")); - const title = fakeHangar(); - title.calls.push({ method: "tab.setBadge", args: { state: "neutral", text: S("leak") } }); - assert.throws(() => assertClean(title, [S("leak")], "planted badge")); -}); diff --git a/test/validate.test.js b/test/validate.test.js deleted file mode 100644 index 09d18c4..0000000 --- a/test/validate.test.js +++ /dev/null @@ -1,289 +0,0 @@ -"use strict"; -// JSON's answer is JSON.parse's. YAML is scanned and TOML parsed for what is certainly -// wrong, so the first thing checked is that valid files, full of traps, pass. -const test = require("node:test"); -const assert = require("node:assert/strict"); -const { validate: check } = require("./helpers.js"); -const { validate, checkerFor } = check; - -test("which check applies", () => { - const table = { - "a.json": "json", "pkg/package.json": "json", "b.JSON": "json", - "tsconfig.json": "jsonc", "tsconfig.app.json": "jsonc", ".vscode/settings.json": "jsonc", "c.jsonc": "jsonc", "w.code-workspace": "jsonc", - "a.yaml": "yaml", "a.yml": "yaml", "a.toml": "toml", "Cargo.toml": "toml", - "a.txt": null, "a.ini": null, "a.json5": null, Dockerfile: null, - }; - for (const [path, kind] of Object.entries(table)) assert.equal(checkerFor(path), kind, path); -}); - -test("JSON: what JSON.parse says, with a line when the engine gives one", () => { - assert.deepEqual(validate("a.json", '{"a": [1, 2]}'), { kind: "json", ok: true, partial: false }); - const bad = validate("a.json", '{\n "a": 1,\n "b": \n}\n'); - assert.equal(bad.ok, false); - assert.equal(bad.partial, false); - assert.equal(bad.code, "json"); - assert.equal(bad.line, 4); - assert.equal(validate("a.json", "").ok, false, "an empty file is no JSON"); - assert.equal(validate("a.json", '{"a": 1} // no').ok, false); - assert.equal(validate("a.json", '{"a": 1,}').ok, false); -}); - -test("JSON: where it goes wrong is found on any engine, and agrees with JSON.parse on what is wrong", () => { - const cases = [ - ['{"a": 1,}', 1, 9], - ['[1, 2\n', 2, 1], - ['{\n"a" 1}', 2, 5], - ['{"a": tru}', 1, 7], - ['"\\q"', 1, 2], - ['"new\nline"', 1, 5], - ['1 2', 1, 3], - ['{"a":01}', 1, 7], - ['[1,\n2,\n,3]', 3, 1], - ['nul', 1, 1], - ]; - for (const [text, line, column] of cases) { - assert.throws(() => JSON.parse(text), undefined, text); - const result = validate("a.json", text); - assert.equal(result.ok, false, text); - assert.deepEqual([result.line, result.column], [line, column], text); - } - for (const text of ['"\\u00e9 \\" \\n"', '[[], {}, [{"a": [null, true, false, -1.5e+3, 0]}]]', " \n 1 \n"]) { - assert.equal(validate("a.json", text).ok, true, text); - } - assert.equal(validate("a.json", "[".repeat(200000)).ok, false, "too deep to walk is still not valid"); -}); - -test("JSONC: comments and trailing commas are fine, and strings are left alone", () => { - const good = '// head\n{\n /* block\n over lines */\n "url": "http://x.y/*z*/", // tail\n "list": [1, 2,],\n "o": { "a": "// not, a comment", },\n}\n'; - assert.equal(validate("tsconfig.json", good).ok, true); - assert.equal(validate(".vscode/settings.json", good).ok, true); - assert.equal(validate("a.json", good).ok, false, "plain JSON has neither"); - const bad = validate("c.jsonc", '{\n // fine\n "a": 1\n "b": 2\n}\n'); - assert.equal(bad.ok, false); - assert.equal(bad.line, 4, "the lines are still the file's"); - assert.equal(validate("c.jsonc", '{"a": ",", }').ok, true); - assert.equal(validate("c.jsonc", "[1,,]").ok, false, "only the last comma goes"); -}); - -const GOOD_YAML = { - workflow: `name: CI -on: - push: - branches: [main, "release/**"] -env: { A: 1, B: "x,y" } -jobs: - build: - runs-on: \${{ matrix.os }} - if: github.event_name == 'push' && contains(x, 'y') - steps: - - uses: actions/checkout@v4 - - name: Say "hi" # a comment with a ' quote and a [ bracket - run: | - echo "unterminated - it's [fine { here - tab inside a block scalar - - run: >- - folded 'text - env: - X: 'it''s' - Y: "a \\" b" -`, - plain: `key: it's fine -other: a "quoted" word -url: http://x.y:80/a#b -time: 12:30:00 -list: -- a -- b: c - d: [e, {f: g}] -- 'single' -- "double" -- - nested - - more -empty: -tilde: ~ -glob: "*.js" -star: *anchor -amp: &anchor value -tagged: !!str "text" -tagged2: !custom [a, b] -? complex key -: complex value -`, - documents: `%YAML 1.2 ---- -a: 1 -... ---- # second -b: 2 ---- | - text with 'a quote ---- "quoted" -`, - multiline: `a: "first line - second 'line" -b: 'first - second "line' -c: [1, - 2, - 3] -d: { - e: f -} -plain: this goes on - 'over several lines - and "another -next: 1 -`, - jsonish: '{"a": 1, "b": [true, null], "c": {"d": "e"}}\n', - tabs: "a: 1\n\t\n \t# a comment after a tab\nb: 2 \t\n", - empty: "", - crlf: "a: 1\r\nb:\r\n - c\r\n", -}; - -for (const [name, text] of Object.entries(GOOD_YAML)) { - test(`valid YAML passes: ${name}`, () => { - assert.deepEqual(validate("a.yaml", text), { kind: "yaml", ok: true, partial: true }); - }); -} - -test("broken YAML: what is certainly wrong, with its line", () => { - const cases = [ - ["a: 1\n\tb: 2\n", "yaml-tab", 2], - ["a:\n - b\n \t- c\n", "yaml-tab", 3], - ['a: "never closed\nb: 2\n', "yaml-quote", 1], - ["a: 1\nb: 'never closed\n", "yaml-quote", 2], - ["a: [1, 2\nb: 3\n", "yaml-bracket", 1], - ["a: {b: 1]\n", "yaml-bracket", 1], - ["a: ]\n", "yaml-bracket", 1], - ["a: @scope/pkg\n", "yaml-reserved", 1], - ["a: `tick`\n", "yaml-reserved", 1], - ]; - for (const [text, code, line] of cases) { - const result = validate("a.yml", text); - assert.equal(result.ok, false, JSON.stringify(text)); - assert.equal(result.code, code, JSON.stringify(text)); - assert.equal(result.line, line, JSON.stringify(text)); - assert.equal(result.partial, true); - } -}); - -const GOOD_TOML = { - everything: `# comment -title = "TOML" # trailing -"quoted key" = 1 -'lit key' = 2 -a.b.c = 3 -d . e = 4 -bare-key_1 = true -no = false -int = +1_000 -hex = 0xDEAD_beef -oct = 0o755 -bin = 0b1010 -float = 6.626e-34 -inf = -inf -nan = nan -date = 1979-05-27 -dt = 1979-05-27T07:32:00Z -dt2 = 1979-05-27 07:32:00.5-07:00 -time = 07:32:00 -str = "esc \\" \\\\ \\t \\u00E9 \\U0001F600" -lit = 'C:\\no\\escape' -multi = """ -line \\ - joined "quotes" "" -""" -multi2 = ''' -raw 'x' '' -''' -arr = [1, 2, 3,] -arr2 = [ - "a", # comment - [1, 2], - - { x = 1, y = "z" }, -] -empty = [] -inline = { a = 1, b.c = 2 } -none = {} - -[table] -x = 1 - -[table.sub] -x = 2 - -[ spaced . "name" ] -x = 3 - -[[items]] -name = "one" - -[[items]] -name = "two" - -[other] -x = 4 -`, - crlf: 'a = 1\r\n# c\r\n[b]\r\nc = "d"\r\n', - empty: "", - "no final newline": "a = 1", -}; - -for (const [name, text] of Object.entries(GOOD_TOML)) { - test(`valid TOML passes: ${name}`, () => { - assert.deepEqual(validate("a.toml", text), { kind: "toml", ok: true, partial: true }); - }); -} - -test("broken TOML, with its line", () => { - const cases = [ - ["a = \n", "toml-value", 1], - ["ok = 1\nb\n", "toml-equals", 2], - ["a = 1 2\n", "toml-trailing", 1], - ['a = "open\n', "toml-string", 1], - ['ok = 1\nb = "bad \\q"\n', "toml-escape", 2], - ["= 1\n", "toml-key", 1], - ["[table\nb = 1\n", "toml-header", 1], - ["[[table]\n", "toml-header", 1], - ["a = 1\na = 2\n", "toml-duplicate", 2], - ["[t]\nx = 1\n[t]\ny = 2\n", "toml-duplicate", 3], - ["[t]\nx = 1\nx = 2\n", "toml-duplicate", 3], - ["a = [1, 2\n", "toml-value", 1], - ["a = { b = 1,\n}\n", "toml-key", 1], - ["a = nope\n", "toml-value", 1], - ["a = 01\n", "toml-value", 1], - ["a = 1_\n", "toml-value", 1], - ["a = truex\n", "toml-value", 1], - ["a = '''open\n", "toml-string", 1], - ]; - for (const [text, code, line] of cases) { - const result = validate("a.toml", text); - assert.equal(result.ok, false, JSON.stringify(text)); - assert.equal(result.code, code, JSON.stringify(text)); - assert.equal(result.line, line, JSON.stringify(text)); - } -}); - -test("the same key in two tables, or two [[items]], is no duplicate", () => { - assert.equal(validate("a.toml", "[a]\nx = 1\n[b]\nx = 2\n").ok, true); - assert.equal(validate("a.toml", "[[a]]\nx = 1\n[[a]]\nx = 2\n").ok, true); -}); - -test("the repository's own files pass, when they are around", () => { - const fs = require("node:fs"); - const path = require("node:path"); - const root = path.join(__dirname, ".."); - const samples = [".github/workflows/ci.yml", ".github/repo.json", "hangar-kit.json", "package.json"]; - for (const sample of samples) { - const file = path.join(root, sample); - if (!fs.existsSync(file)) continue; // a kit installed on its own has none beside it - const result = validate(sample, fs.readFileSync(file, "utf8")); - assert.equal(result.ok, true, `${sample}: ${JSON.stringify(result)}`); - } -}); - -test("no check for other files: nothing can be said, so nothing is claimed", () => { - assert.deepEqual(validate("a.txt", "whatever {{{"), { kind: null, ok: true, partial: false }); -}); diff --git a/test/view.test.js b/test/view.test.js deleted file mode 100644 index d163a60..0000000 --- a/test/view.test.js +++ /dev/null @@ -1,349 +0,0 @@ -"use strict"; -// What the page draws for each state, on a fake DOM: values masked until revealed, -// text never parsed as markup, both languages, Hangar UI's classes. -const test = require("node:test"); -const assert = require("node:assert/strict"); -const fs = require("node:fs"); -const path = require("node:path"); -const { KIT, TAB, lib, logic, createController, fakeHangar, fakeDocument, FakeNode, row, settle } = require("./helpers.js"); -const view = require(path.join(TAB, "view.js")); -const { hangarFile, HANGAR_FILES_MISSING } = require("./hangar-ui.js"); - -const SECRET = "s3cr3t-value-XqZ9"; - -async function drawn(options = {}) { - const hangar = options.hangar || fakeHangar(options); - const lang = options.lang || "en"; - const t = (key, vars) => logic.t(lang, key, vars); - const root = new FakeNode("div"); - const asked = []; - let refresh = () => undefined; - const ctx = { doc: fakeDocument, t, logic, gitignore: lib.gitignore, confirm: async (...args) => (asked.push(args), options.confirmAnswer ?? false) }; - const controller = createController({ - hangar, lib, t, - onChange: (state) => { - refresh = view.render(root, state, ctx); - }, - onTyping: () => refresh(), - }); - ctx.actions = controller; - await controller.start(); - await settle(); - const buttonNamed = (label) => root.find((node) => node.tag === "button" && node.text.includes(label))[0]; - return { root, hangar, controller, state: controller.state, buttonNamed, asked, refresh: () => refresh() }; -} - -const inputOf = (root, key) => root.find((node) => (node.tag === "input" || node.tag === "textarea") && node.getAttribute("aria-label") === key)[0]; -const classed = (root, name) => root.find((node) => node.className.split(" ").includes(name)); - -test("a value is masked until its row is revealed, and shows nowhere else", async () => { - const { root, controller, state } = await drawn({ - params: { path: ".env" }, files: { ".env": `# about it\nAPI_KEY=${SECRET}\n# OLD=${SECRET}\n`, ".gitignore": ".env\n" }, - }); - const input = inputOf(root, "API_KEY"); - assert.equal(input.type, "password"); - assert.equal(input.value, SECRET, "the field holds it, and the browser masks it"); - assert.equal(input.getAttribute("autocomplete"), "new-password"); - assert.equal(root.text.includes(SECRET), false, "no text node holds it"); - const shown = root.everything().filter((item) => item.includes(SECRET)); - assert.deepEqual(shown, [SECRET], "only that field's value, not a title, a hint or a comment"); - - controller.toggleReveal("API_KEY"); - assert.equal(inputOf(root, "API_KEY").type, "text"); - assert.equal(row(state, "API_KEY").revealed, true); -}); - -test("a value over several lines stays hidden, and is edited whole once shown", async () => { - const { root, controller } = await drawn({ params: { path: ".env" }, files: { ".env": `KEY='first\n${SECRET}'\n`, ".gitignore": ".env\n" } }); - const hidden = inputOf(root, "KEY"); - assert.equal(hidden.disabled, true); - assert.equal(hidden.value, undefined, "a password field would drop its line breaks"); - assert.ok(!root.everything().some((item) => item.includes(SECRET))); - controller.toggleReveal("KEY"); - const area = inputOf(root, "KEY"); - assert.equal(area.tag, "textarea"); - assert.equal(area.value, `first\n${SECRET}`); -}); - -test("asked keys come first with their state, then the file's, and why at the top", async () => { - const { root } = await drawn({ - params: { path: "sub/.env", keys: "MISSING,DONE", why: "For the tests." }, - caller: { pane: "Asker" }, - files: { "sub/.env": "OTHER=1\nDONE=x\n", "sub/.env.example": "# Offer hint\nOFFERED=y\n", ".gitignore": ".env\n" }, - }); - const text = root.text; - assert.match(text, /Asker asks:/); - assert.match(text, /For the tests<\/b>\./, "shown as written, not as markup"); - assert.equal(classed(root, "kit-header__title")[0].text, ".env"); - assert.match(classed(root, "kit-header__state")[0].text, /1 missing.*sub\//); - const titles = classed(root, "kit-section__title").map((node) => node.text); - assert.deepEqual(titles, ["Asked for", "In this file", "In .env.example, missing here", "Add a key"]); - const keys = classed(root, "kit-row__title").map((node) => node.text); - assert.deepEqual(keys, ["MISSING", "DONE", "OTHER", "OFFERED"]); - assert.match(text, /Offer hint/); - assert.equal(classed(root, "kit-state--waiting").filter((node) => node.text === "missing").length, 1); - assert.equal(classed(root, "kit-state--success").filter((node) => node.text === "set").length, 1); -}); - -test("the warning says it plainly, and the button is what writes", async () => { - const { root, hangar, buttonNamed } = await drawn({ params: { path: ".env" }, files: { ".env": "A=1\n", ".gitignore": "x\n" } }); - assert.match(root.text, /\.env is not ignored by git: git would commit it, secrets included\./); - assert.equal(classed(root, "kit-banner--warning").length, 1); - assert.equal(hangar.callsTo("files.write").length, 0); - await buttonNamed("Add .env to .gitignore").onclick(); - assert.equal(hangar.store.get(".gitignore"), "x\n.env\n"); - assert.equal(classed(root, "kit-banner--warning").length, 0); -}); - -test("typing refreshes what depends on it and leaves the field alone", async () => { - const { root, controller, buttonNamed } = await drawn({ params: { path: ".env", keys: "A" }, files: { ".env": "A=\n", ".gitignore": ".env\n" } }); - const input = inputOf(root, "A"); - assert.equal(buttonNamed("Save").disabled, true, "nothing to save"); - assert.match(classed(root, "kit-header__state")[0].text, /1 missing/); - input.value = "typed"; - input.oninput(); - assert.equal(inputOf(root, "A"), input, "the same element: the caret stays where it is"); - assert.equal(buttonNamed("Save").disabled, false); - assert.doesNotMatch(classed(root, "kit-header__state")[0].text, /missing/); - assert.equal(classed(root, "kit-chip")[0].text, "changed"); - await buttonNamed("Save").onclick(); - await settle(); - assert.equal(controller.state.saved, true); - assert.match(classed(root, "kit-header__state")[0].text, /Saved/); -}); - -test("one primary action at a time: save, or tell the agent there is nothing to change", async () => { - const { root, controller } = await drawn({ params: { path: ".env" }, caller: { pane: "Asker" }, files: { ".env": "A=1\n", ".gitignore": ".env\n" } }); - const primary = () => classed(root, "kit-btn--primary"); - assert.deepEqual(primary().map((node) => node.text), ["Tell Asker: nothing to change"]); - controller.editRow("A", "2"); - assert.deepEqual(primary().map((node) => node.text), ["Save"]); - await primary()[0].onclick(); - await settle(); - assert.match(root.text, /Asker was told, without any value\./); - assert.equal(root.text.includes("nothing to change"), false); -}); - -test("an agent that could not be told is said, with a way to try again", async () => { - const { root, hangar, buttonNamed } = await drawn({ params: { path: ".env" }, caller: { pane: "Asker" }, files: { ".env": "A=1\n", ".gitignore": ".env\n" }, sendError: "not_found" }); - const input = inputOf(root, "A"); - input.value = "2"; - input.oninput(); - await buttonNamed("Save").onclick(); - await settle(); - assert.match(root.text, /Saved, but Asker could not be told: that pane is gone\. No value was sent\./); - hangar.sendError = null; - await buttonNamed("Tell Asker again").onclick(); - await settle(); - assert.match(root.text, /Asker was told/); -}); - -test("the editor: line numbers, the line asked for marked, and the check above it", async () => { - const body = Array.from({ length: 12 }, (_, i) => `"k${i}": ${i},`).join("\n"); - const { root, controller, state } = await drawn({ params: { path: "conf.json", line: "5", why: "Check the timeout." }, files: { "conf.json": `{\n${body}\n}\n` } }); - const gutter = classed(root, "editor-gutter")[0]; - assert.match(gutter.text, /^1\n2\n3\n4\n5\n6/); - assert.equal(classed(gutter, "editor-gutter__mark")[0].text, "5"); - assert.equal(gutter.attributes["aria-hidden"], "true"); - const area = classed(root, "editor-area")[0]; - assert.equal(area.wrap, "off"); - assert.equal(area.scrollTop, 18, "scrolled to it, three lines above"); - assert.equal(state.text.jump, null); - assert.equal(fakeDocument.activeElement === area, false, "and the keyboard stays where it was"); - assert.match(root.text, /Broken JSON, line \d+/); - assert.match(root.text, /Check the timeout\./); - - area.value = '{"a": 1}\n'; - area.oninput(); - assert.match(root.text, /Valid JSON/); - assert.equal(classed(root, "editor-area")[0], area, "the same element"); - assert.match(gutter.text, /^1\n2\n$/); - assert.ok(controller.isDirty()); -}); - -test("the review: signs as well as colours, then a broken file asks", async () => { - const { root, controller, buttonNamed, hangar } = await drawn({ params: { path: "a.json" }, files: { "a.json": '{"a": 1}\n' } }); - const area = classed(root, "editor-area")[0]; - area.value = '{"a": 2,}\n'; - area.oninput(); - await buttonNamed("Review changes").onclick(); - assert.match(root.text, /− \{"a": 1\}/); - assert.match(root.text, /\+ \{"a": 2,\}/); - assert.equal(classed(root, "kit-log__line--error").length, 1); - assert.equal(classed(root, "editor-add").length, 1); - assert.equal(buttonNamed("Save").disabled, true, "broken, and not said so"); - const toggle = root.find((node) => node.tag === "input" && node.type === "checkbox")[0]; - assert.match(root.text, /I know this file is broken: save it anyway\./); - toggle.checked = true; - toggle.onchange(); - assert.equal(buttonNamed("Save").disabled, false); - await buttonNamed("Save").onclick(); - await settle(); - assert.equal(hangar.store.get("a.json"), '{"a": 2,}\n'); - assert.equal(controller.state.text.stage, "edit"); -}); - -test("the text conflict shows both sides and three ways out", async () => { - const { root, hangar, controller, buttonNamed } = await drawn({ params: { path: "a.txt" }, files: { "a.txt": "base\n" } }); - controller.editText("mine\n"); - controller.review(); - hangar.store.set("a.txt", "theirs\n"); - await controller.saveText(); - await settle(); - assert.match(root.text, /This file changed while you were editing it\. Nothing was written\./); - assert.match(root.text, /− theirs/); - assert.match(root.text, /\+ mine/); - assert.match(classed(root, "kit-state--failure")[0].text, /Changed on disk/); - await buttonNamed("Keep what is on disk").onclick(); - await settle(); - assert.equal(controller.state.text.value, "theirs\n"); - assert.equal(root.text.includes("Replace it with mine"), false); -}); - -test("the dotenv conflict keeps values hidden until asked, on both sides", async () => { - const { root, hangar, controller, buttonNamed, state } = await drawn({ params: { path: ".env" }, files: { ".env": "A=1\n", ".gitignore": ".env\n" } }); - controller.editRow("A", `${SECRET}-mine`); - hangar.store.set(".env", `A=${SECRET}-theirs\nB=2\n`); - await controller.saveForm(); - await settle(); - assert.ok(!root.everything().some((item) => item.includes(SECRET)), "both masked"); - assert.match(root.text, new RegExp(view.MASK)); - assert.match(root.text, /Yours/); - assert.match(root.text, /On disk/); - assert.match(root.text, /1 other key changed on disk/); - - await buttonNamed("Show").onclick(); - assert.match(root.text, new RegExp(`${SECRET}-mine`)); - assert.match(root.text, new RegExp(`${SECRET}-theirs`)); - const radios = root.find((node) => node.tag === "input" && node.type === "radio"); - assert.deepEqual(radios.map((node) => node.checked), [true, false]); - radios[1].onchange(); - assert.equal(state.conflict.rows[0].choice, "theirs"); - await buttonNamed("Save with these choices").onclick(); - await settle(); - assert.equal(hangar.store.get(".env"), `A=${SECRET}-theirs\nB=2\n`); -}); - -test("the picker groups, filters as you type, and opens what is clicked", async () => { - const { root, controller, state } = await drawn({ files: { ".env.local": "A=1\n", "app.yaml": "a: 1\n", "src/x.ts": "", ".gitignore": ".env.local\n" } }); - assert.deepEqual(classed(root, "kit-section__title").map((node) => node.text), ["Environment files", "Configuration files", "Other files"]); - assert.match(root.text, /new/, ".env is offered though it is not there"); - const search = root.find((node) => node.tag === "input" && node.type === "search")[0]; - search.value = "app"; - search.oninput(); - assert.equal(root.find((node) => node.tag === "input" && node.type === "search")[0], search, "the same element"); - assert.deepEqual(classed(root, "kit-section__title").map((node) => node.text), ["Configuration files"]); - search.value = "nothing like it"; - search.oninput(); - assert.match(root.text, /No file matches\./); - search.value = ""; - search.oninput(); - const row = root.find((node) => node.tag === "button" && node.title === ".env.local")[0]; - await row.onclick(); - await settle(); - assert.equal(state.view, "dotenv"); - assert.ok(root.text.includes("← Files")); - assert.ok(controller); -}); - -test("back with edits asks in place, without one it just goes", async () => { - const stay = await drawn({ files: { "a.txt": "x\n" }, confirmAnswer: false }); - await stay.root.find((node) => node.title === "a.txt")[0].onclick(); - await settle(); - stay.controller.editText("changed\n"); - await stay.buttonNamed("← Files").onclick({ currentTarget: "the button" }); - await settle(); - assert.equal(stay.asked[0][0], "the button"); - assert.equal(stay.asked[0][1].message, "Your changes are not saved."); - assert.equal(stay.state.view, "text"); - assert.equal(stay.state.text.value, "changed\n"); - - const leave = await drawn({ files: { "a.txt": "x\n" }, confirmAnswer: true }); - await leave.root.find((node) => node.title === "a.txt")[0].onclick(); - await settle(); - leave.controller.editText("changed\n"); - await leave.buttonNamed("← Files").onclick({ currentTarget: "the button" }); - await settle(); - assert.equal(leave.state.view, "picker"); - - const clean = await drawn({ files: { "a.txt": "x\n" }, confirmAnswer: false }); - await clean.root.find((node) => node.title === "a.txt")[0].onclick(); - await settle(); - await clean.buttonNamed("← Files").onclick(); - await settle(); - assert.equal(clean.state.view, "picker"); - assert.equal(clean.asked.length, 0); -}); - -test("denied and failed are designed states, each saying what to do", async () => { - const denied = await drawn({ params: { path: ".env" }, deny: ["files.read"] }); - assert.match(denied.root.text, /This tab may not read or write here/); - assert.match(denied.root.text, /Accept files\.read and files\.write/); - assert.equal(classed(denied.root, "kit-icon--lock").length, 1); - assert.equal(classed(denied.root, "kit-empty").length, 1); - assert.ok(denied.buttonNamed("Try again")); - - const bad = await drawn({ params: { path: "../x" } }); - assert.match(bad.root.text, /This path cannot be opened/); - assert.equal(bad.buttonNamed("Try again"), undefined, "trying again would change nothing"); - await bad.buttonNamed("Choose a file").onclick(); - await settle(); - assert.equal(bad.state.view, "picker", "the picker is the way on"); -}); - -test("in French, with accents", async () => { - const { root, controller } = await drawn({ - lang: "fr", params: { path: ".env", keys: "A,B" }, caller: { pane: "Asker" }, files: { ".env": "C=1\n", ".gitignore": "x\n" }, - }); - const text = root.text; - assert.match(text, /Dans ce fichier/); - assert.match(text, /Demandées/); - assert.match(text, /manquante/); - assert.match(text, /n'est pas ignoré par git/); - controller.editRow("A", "x"); - assert.match(root.text, /Enregistrer/); - assert.match(root.text, /modifiée/); -}); - -test("every word the page says exists in both languages", () => { - const { en, fr } = logic.STRINGS; - assert.deepEqual(Object.keys(fr).sort(), Object.keys(en).sort()); - const accents = /[àâçéèêëîïôûùüœ]/i; - assert.ok(Object.values(fr).filter((text) => accents.test(text)).length > 60, "written with its accents"); - for (const file of ["view.js", "controller.js"]) { - const source = fs.readFileSync(path.join(TAB, file), "utf8"); - for (const [, key] of source.matchAll(/\bt\("([\w.-]+)"/g)) { - assert.ok(en[key] !== undefined || en[`${key}_one`] !== undefined, `${file}: ${key}`); - } - } - for (const code of ["json", "yaml-tab", "yaml-quote", "yaml-bracket", "yaml-reserved", "toml-trailing", "toml-string", "toml-escape", "toml-key", "toml-equals", "toml-value", "toml-header", "toml-duplicate"]) { - assert.ok(en[`check.${code}`], code); - } - const validateSource = fs.readFileSync(path.join(TAB, "validate.js"), "utf8"); - for (const [, code] of validateSource.matchAll(/["'`](yaml-[a-z]+|toml-[a-z]+)["'`]/g)) assert.ok(en[`check.${code}`], code); - for (const kind of ["denied", "invalid", "bad-path", "failed", "unavailable", "timeout", "error"]) { - assert.ok(en[`err.${kind}.title`] && en[`err.${kind}.hint`], kind); - } -}); - -test("Hangar UI's classes, and no colour of its own", (t) => { - const css = fs.readFileSync(path.join(TAB, "style.css"), "utf8"); - assert.doesNotMatch(css, /#[0-9a-f]{3,8}\b|\brgba?\(|\bhsla?\(|\boklch\(|(?