diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 00000000..6fbd674d --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,3 @@ +# `cargo xtask ` runs the workspace's development tasks (tools/xtask). +[alias] +xtask = "run --package xtask --" diff --git a/.gitignore b/.gitignore index c3ec7d27..a8da30a7 100644 --- a/.gitignore +++ b/.gitignore @@ -22,3 +22,6 @@ rustc-ice-*.txt # and can be added to the global gitignore or merged into this file. For a more nuclear # option (not recommended) you can uncomment the following to ignore the entire idea folder. #.idea/ + +# This repository is used to test origin. +.origin/ diff --git a/AGENTS.md b/AGENTS.md index c7bfc3bf..b6a834bf 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,12 +10,15 @@ review bots read and write at the same time, written in Rust. shared by every component. - `crates/origin-platform`: everything that differs between platforms (durable writes, file locks, copy-on-write clones, positioned reads, - refusing network file systems), behind traits. It is the only place that may depend on the - target OS. + refusing network file systems), behind traits. It is the only place whose + code differs by target OS. `std::os::unix`, which every supported platform + has, may be used anywhere. - `crates/origin-client`: the HTTP client, generated from the server's OpenAPI document. Never edit generated code by hand. - `apps/origin-src`: the `origin` binary, both the command line and the server. +- `tools/xtask`: development tasks, run with `cargo xtask`, such as timing + origin against git (`just bench-git`). ## Testing & Benchmarks @@ -23,6 +26,14 @@ Performance is a primary goal, so benchmarks matter as much as tests. A change to a hot path (hashing, storage, snapshots, transfer) should come with a benchmark, and its numbers in the pull request. +- `just bench`: the divan micro-benchmarks (encoding, store writes, + snapshots). +- `just bench-git`: times origin against git on a 20,000-file tree with + hyperfine, and rewrites `docs/benchmarks.md`. + +End-to-end tests run the `origin` binary with `ORIGIN_CONFIG_DIR` set to a +temporary directory, which holds the user's `config.toml` and node key. + ## Commits & Pull Requests Titles follow conventional commits with a scope, e.g. diff --git a/Cargo.lock b/Cargo.lock index d59d56d8..5aa46da8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,12 +2,62 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + [[package]] name = "anstyle" version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + [[package]] name = "arrayvec" version = "0.7.8" @@ -42,6 +92,16 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "bstr" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f" +dependencies = [ + "memchr", + "serde_core", +] + [[package]] name = "cc" version = "1.8.0" @@ -67,6 +127,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" dependencies = [ "clap_builder", + "clap_derive", ] [[package]] @@ -75,17 +136,37 @@ version = "4.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" dependencies = [ + "anstream", "anstyle", "clap_lex", + "strsim", "terminal_size", ] +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "clap_lex" version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + [[package]] name = "condtype" version = "1.3.0" @@ -200,6 +281,12 @@ dependencies = [ "zeroize", ] +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + [[package]] name = "errno" version = "0.3.14" @@ -239,6 +326,18 @@ dependencies = [ "r-efi", ] +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + [[package]] name = "hybrid-array" version = "0.4.15" @@ -248,6 +347,22 @@ dependencies = [ "typenum", ] +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + [[package]] name = "jobserver" version = "0.1.35" @@ -270,12 +385,24 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + [[package]] name = "once_cell" version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + [[package]] name = "origin-client" version = "0.1.0" @@ -309,11 +436,18 @@ dependencies = [ name = "origin-src" version = "0.1.0" dependencies = [ + "anyhow", + "clap", "divan", + "getrandom", "origin-platform", "origin-shared", + "origin-src", + "serde", + "similar", "tempfile", "thiserror", + "toml", "zstd", ] @@ -393,6 +527,45 @@ version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +[[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 3.0.9", +] + +[[package]] +name = "serde_spanned" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" +dependencies = [ + "serde_core", +] + [[package]] name = "sha2" version = "0.11.1" @@ -416,6 +589,21 @@ version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5" +[[package]] +name = "similar" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f66ca1f7aca2474dc10c942eb22feffc897735f54cd1db90138c2fddb490987" +dependencies = [ + "bstr", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + [[package]] name = "subtle" version = "2.6.1" @@ -487,6 +675,45 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "toml" +version = "1.1.8+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" + [[package]] name = "typenum" version = "1.20.1" @@ -499,6 +726,12 @@ version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + [[package]] name = "windows" version = "0.62.2" @@ -618,6 +851,20 @@ dependencies = [ "windows-link", ] +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" + +[[package]] +name = "xtask" +version = "0.1.0" +dependencies = [ + "anyhow", + "origin-src", +] + [[package]] name = "zeroize" version = "1.9.1" diff --git a/Cargo.toml b/Cargo.toml index fb2066ca..c10d9f61 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,6 +5,7 @@ members = [ "crates/origin-client", "crates/origin-platform", "crates/origin-shared", + "tools/xtask", ] [workspace.package] @@ -21,17 +22,23 @@ repository = "https://github.com/piquel-fr/origin" origin-client = { version = "0.1.0", path = "crates/origin-client" } origin-platform = { version = "0.1.0", path = "crates/origin-platform" } origin-shared = { version = "0.1.0", path = "crates/origin-shared" } +origin-src = { version = "0.1.0", path = "apps/origin-src" } # External +anyhow = "1.0.104" blake3 = "1.8.7" +clap = { version = "4.6.7", features = ["derive"] } divan = "0.1.21" ed25519-dalek = "3.0.0" getrandom = "0.4.3" reflink-copy = "0.1.30" # Only in origin-platform. The version and features reflink-copy uses on Linux. rustix = { version = "1.1.5", default-features = false, features = ["fs", "std"] } +serde = { version = "1.0.229", features = ["derive"] } +similar = "3.2.0" tempfile = "3.27.0" thiserror = "2.0.21" +toml = "1.1.8" zstd = "0.14.3" [workspace.lints.rust] diff --git a/README.md b/README.md index bcf2b28a..8222e7df 100644 --- a/README.md +++ b/README.md @@ -6,11 +6,38 @@ review bots read and write at the same time, written in Rust. See **Status:** early prototype. Nothing here is stable. +## Usage + +There are no commits or branches. The working copy is always on a revision +of the current change. Commands that only read it show your edits as a +draft, and those that build on the change, such as `describe` or `new`, +record them first. + +```sh +origin init # a repository with the targets `policy` and `main` +origin describe "Add retries" # say what the current change is for +origin new "Parse the config" # finish it, and start the next change on top +origin status | diff | show [] +origin log [] # your changes, then the target's acceptances +origin evolog # every revision of a change +origin edit # switch the working copy to another change +origin abandon --reason "Too slow" # give a change up, keeping it for others to see +origin converge # end a change's divergence +origin index rebuild # rebuild the record index from the store +``` + +Changes are named by a unique prefix of their id, or `@` for the working +copy's. Your name and node key live in `$ORIGIN_CONFIG_DIR`, or else +`origin` in `$XDG_CONFIG_HOME` or `~/.config`: set `user = ""` in +its `config.toml` if `$USER` isn't the name you want. See +[the design](docs/design.md) for the model. + ## Development ```sh -just # format, lint, test, and audit dependencies -just bench # micro-benchmarks +just # format, lint, test, and audit dependencies +just bench # micro-benchmarks +just bench-git # origin against git, with hyperfine (docs/benchmarks.md) ``` rustup installs the toolchain `rust-toolchain.toml` pins. The minimum diff --git a/apps/origin-src/Cargo.toml b/apps/origin-src/Cargo.toml index 7ceae869..7b6da227 100644 --- a/apps/origin-src/Cargo.toml +++ b/apps/origin-src/Cargo.toml @@ -11,16 +11,32 @@ repository.workspace = true name = "origin" path = "src/main.rs" +[features] +# Synthetic working trees for benchmarks. Never part of a release build. +fixture = [] + [dependencies] +anyhow.workspace = true +clap.workspace = true +getrandom.workspace = true origin-platform.workspace = true origin-shared.workspace = true +serde.workspace = true +similar.workspace = true thiserror.workspace = true +toml.workspace = true zstd.workspace = true [dev-dependencies] divan.workspace = true +# The benchmarks build their working trees with the fixtures. +origin-src = { workspace = true, features = ["fixture"] } tempfile.workspace = true +[[bench]] +name = "snapshot" +harness = false + [[bench]] name = "store" harness = false diff --git a/apps/origin-src/benches/snapshot.rs b/apps/origin-src/benches/snapshot.rs new file mode 100644 index 00000000..3a19b625 --- /dev/null +++ b/apps/origin-src/benches/snapshot.rs @@ -0,0 +1,82 @@ +//! Snapshotting a working copy: the cost behind every command that reads it. +//! Objects are written durably, as the commands write them. + +use std::sync::atomic::{AtomicU64, Ordering}; + +use divan::Bencher; +use divan::counter::ItemsCount; +use origin_platform::Native; +use origin_src::fixture::FixtureTree; +use origin_src::store::Store; +use origin_src::worktree::{StatCache, Worktree}; + +fn main() { + divan::main(); +} + +const TREE: FixtureTree = FixtureTree { + files: 5_000, + ..FixtureTree::LARGE +}; + +/// An empty store in `dir`. +fn store(dir: &tempfile::TempDir) -> Store { + let store = Store::new(dir.path().join(".origin"), Native::default()); + store.init().unwrap(); + store +} + +/// A fixture working copy with a store inside it. +fn working_copy() -> (tempfile::TempDir, Store) { + let dir = tempfile::tempdir().unwrap(); + TREE.write(dir.path()).unwrap(); + let store = store(&dir); + (dir, store) +} + +/// The first snapshot: every file is read, hashed, compressed, and written. +#[divan::bench(sample_count = 10, sample_size = 1)] +fn cold(bencher: Bencher<'_, '_>) { + let (dir, _) = working_copy(); + bencher + .counter(ItemsCount::new(TREE.files)) + .with_inputs(|| { + let objects = tempfile::tempdir().unwrap(); + let store = store(&objects); + (objects, store) + }) + .bench_local_refs(|(_, store)| { + Worktree::new(dir.path(), store) + .snapshot(&StatCache::default()) + .unwrap() + }); +} + +/// Nothing changed: every file is answered by the stat cache. +#[divan::bench(sample_count = 20, sample_size = 1)] +fn unchanged(bencher: Bencher<'_, '_>) { + let (dir, store) = working_copy(); + let worktree = Worktree::new(dir.path(), &store); + let (_, cache) = worktree.snapshot(&StatCache::default()).unwrap(); + let cache = cache.unwrap(); + bencher + .counter(ItemsCount::new(TREE.files)) + .bench_local(|| worktree.snapshot(&cache).unwrap()); +} + +/// A typical edit: 100 files changed since the last snapshot. +#[divan::bench(sample_count = 20, sample_size = 1)] +fn edited_100(bencher: Bencher<'_, '_>) { + let (dir, store) = working_copy(); + let worktree = Worktree::new(dir.path(), &store); + let (_, cache) = worktree.snapshot(&StatCache::default()).unwrap(); + let cache = cache.unwrap(); + let version = AtomicU64::new(1); + bencher + .counter(ItemsCount::new(TREE.files)) + .with_inputs(|| { + TREE.edit(dir.path(), 100, version.fetch_add(1, Ordering::Relaxed)) + .unwrap(); + }) + .bench_local_values(|()| worktree.snapshot(&cache).unwrap()); +} diff --git a/apps/origin-src/src/cli.rs b/apps/origin-src/src/cli.rs new file mode 100644 index 00000000..83af2f5a --- /dev/null +++ b/apps/origin-src/src/cli.rs @@ -0,0 +1,140 @@ +//! The `origin` command line: argument parsing. The commands themselves are +//! methods of [`Workspace`], which print their output. + +use std::env; +use std::path::PathBuf; + +use anyhow::{Context, Result}; +use clap::{Parser, Subcommand}; +use origin_shared::TargetName; + +use crate::config::UserConfig; +use crate::workspace::Workspace; + +/// A modern, git-compatible source control system. +#[derive(Debug, Parser)] +#[command(version)] +pub struct Cli { + #[command(subcommand)] + command: Command, +} + +#[derive(Debug, Subcommand)] +enum Command { + /// Create a repository, with the targets `policy` and `main`. + Init { + /// Where to create it. + #[arg(default_value = ".")] + path: PathBuf, + }, + #[command(flatten)] + Workspace(WorkspaceCommand), +} + +/// Commands run in the repository containing the current directory. Those +/// that read the working copy snapshot it first. Changes are named by a +/// unique prefix of their id, or `@` for the working copy's. +#[derive(Debug, Subcommand)] +enum WorkspaceCommand { + /// Show the working copy's change and the files it changes. + Status, + /// Show the working copy's changes, line by line. + Diff, + /// Show a change and its diff: the working copy's by default. + Show { + /// The change. + change: Option, + }, + /// Finish the current change, and start a new one on top of it. + New { + /// What the new change is for. + #[arg(default_value = "")] + description: String, + }, + /// Describe what the current change is for. + Describe { + /// The description. + description: String, + }, + /// Switch the working copy to a change. + Edit { + /// The change. + change: String, + }, + /// Give a change up, keeping it and the reason for others to see. + Abandon { + /// The change: the working copy's by default, which then starts a + /// new change where it started. + change: Option, + /// Why it was given up. + #[arg(long)] + reason: String, + }, + /// End a change's divergence, with a revision evolving from every head. + Converge { + /// The change. + change: String, + }, + /// Show the working copy's changes and the target they're on. + Log { + /// Show this target's history instead. + target: Option, + /// Show at most this many acceptances. + #[arg(short = 'n', long)] + limit: Option, + }, + /// Show every revision of a change. + Evolog { + /// The change. + #[arg(default_value = "@")] + change: String, + }, + /// Manage the record index. + #[command(subcommand)] + Index(IndexCommand), +} + +#[derive(Debug, Subcommand)] +enum IndexCommand { + /// Rebuild the index from the store. + Rebuild, +} + +impl Cli { + /// Runs the command, printing its output. + /// + /// # Errors + /// + /// Fails if the command fails; the error is meant for the user. + pub fn run(self) -> Result<()> { + let config = UserConfig::load()?; + match self.command { + Command::Init { path } => { + Workspace::init(&path, config)?; + } + Command::Workspace(command) => command.run(config)?, + } + Ok(()) + } +} + +impl WorkspaceCommand { + fn run(self, config: UserConfig) -> Result<()> { + let cwd = env::current_dir().context("cannot read the current directory")?; + let mut workspace = Workspace::discover(&cwd, config)?; + match self { + Self::Status => workspace.status()?, + Self::Diff => workspace.diff()?, + Self::Show { change } => workspace.show(change.as_deref())?, + Self::New { description } => workspace.new_change(&description)?, + Self::Describe { description } => workspace.describe(&description)?, + Self::Edit { change } => workspace.edit(&change)?, + Self::Abandon { change, reason } => workspace.abandon(change.as_deref(), &reason)?, + Self::Converge { change } => workspace.converge(&change)?, + Self::Log { target, limit } => workspace.log(target, limit)?, + Self::Evolog { change } => workspace.evolog(&change)?, + Self::Index(IndexCommand::Rebuild) => workspace.rebuild_index()?, + } + Ok(()) + } +} diff --git a/apps/origin-src/src/config.rs b/apps/origin-src/src/config.rs new file mode 100644 index 00000000..b88ced74 --- /dev/null +++ b/apps/origin-src/src/config.rs @@ -0,0 +1,222 @@ +//! The user's configuration, kept outside every repository in +//! `$ORIGIN_CONFIG_DIR`, or else `origin` in `$XDG_CONFIG_HOME` or +//! `~/.config`: +//! +//! - `config.toml`: `user = "alice"`, who authors revisions (by default +//! `$USER`), and `node = "laptop"`, this node's name (by default the +//! user's). +//! - `node.key`: this node's secret ed25519 key, created by the first +//! `origin init`, readable only by its owner. + +use std::env; +use std::fs::{self, OpenOptions}; +use std::io::{self, Write}; +use std::os::unix::fs::OpenOptionsExt; +use std::path::{Path, PathBuf}; +use std::process; + +use origin_platform::{Durability, Native}; +use origin_shared::{InvalidName, NodeKey, Principal, PrincipalName}; +use serde::Deserialize; + +/// The user's configuration. +#[derive(Debug)] +pub struct UserConfig { + dir: PathBuf, + user: PrincipalName, + node: PrincipalName, +} + +/// `config.toml`. +#[derive(Debug, Default, Deserialize)] +#[serde(deny_unknown_fields)] +struct ConfigFile { + user: Option, + node: Option, +} + +impl UserConfig { + /// The length of `node.key`: the raw secret key. + const KEY_LEN: usize = 32; + + /// Loads the configuration from its directory. + /// + /// # Errors + /// + /// Fails if there's no configuration directory, `config.toml` cannot be + /// read or is invalid, or no user name is set. + pub fn load() -> Result { + let dir = env::var_os("ORIGIN_CONFIG_DIR") + .map(PathBuf::from) + .or_else(|| env::var_os("XDG_CONFIG_HOME").map(|dir| Path::new(&dir).join("origin"))) + .or_else(|| env::var_os("HOME").map(|home| Path::new(&home).join(".config/origin"))) + .ok_or(ConfigError::NoDir)?; + let path = dir.join("config.toml"); + let file: ConfigFile = match fs::read_to_string(&path) { + Ok(content) => toml::from_str(&content).map_err(|source| ConfigError::Toml { + path: path.clone(), + source, + })?, + Err(error) if error.kind() == io::ErrorKind::NotFound => ConfigFile::default(), + Err(source) => return Err(ConfigError::Io { path, source }), + }; + let name = |name: String| { + PrincipalName::new(name).map_err(|source| ConfigError::InvalidName { + path: path.clone(), + source, + }) + }; + let user = file + .user + .or_else(|| env::var("USER").ok()) + .ok_or_else(|| ConfigError::NoUser(path.clone())) + .and_then(name)?; + let node = file + .node + .map(name) + .transpose()? + .unwrap_or_else(|| user.clone()); + Ok(Self { dir, user, node }) + } + + /// The user, who authors revisions and issues statements. + #[must_use] + pub fn user(&self) -> Principal { + Principal::User(self.user.clone()) + } + + /// This node's name. + #[must_use] + pub fn node(&self) -> &PrincipalName { + &self.node + } + + fn key_path(&self) -> PathBuf { + self.dir.join("node.key") + } + + /// This node's key, generated and saved durably the first time. + /// + /// # Errors + /// + /// Fails if the key cannot be read, is malformed, or cannot be + /// generated and saved. + pub fn node_key(&self) -> Result { + match self.read_key() { + Err(ConfigError::Io { source, .. }) if source.kind() == io::ErrorKind::NotFound => { + self.create_key() + } + result => result, + } + } + + fn read_key(&self) -> Result { + let path = self.key_path(); + let bytes = fs::read(&path).map_err(|source| ConfigError::Io { + path: path.clone(), + source, + })?; + let secret: [u8; Self::KEY_LEN] = bytes + .try_into() + .map_err(|_| ConfigError::MalformedKey(path))?; + Ok(NodeKey::from_bytes(&secret)) + } + + /// Generates a key and saves it: written and synced under a temporary + /// name, then linked into place, which fails if another process saved + /// one first. That one is used instead. + fn create_key(&self) -> Result { + let io_error = |path: &Path| { + let path = path.to_owned(); + move |source| ConfigError::Io { path, source } + }; + fs::create_dir_all(&self.dir).map_err(io_error(&self.dir))?; + let key = NodeKey::generate().map_err(ConfigError::Random)?; + let temp = self.dir.join(format!(".node.key-{}", process::id())); + // A crash can leave one behind, under a pid that a reboot hands out + // again. Only this process uses the name. + let _ = fs::remove_file(&temp); + let written = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(&temp) + .and_then(|mut file| { + file.write_all(&key.to_bytes())?; + Native::default().sync_file(&file) + }) + .and_then(|()| fs::hard_link(&temp, self.key_path())); + // Best effort: a leftover is never read. + let _ = fs::remove_file(&temp); + match written { + Ok(()) => {} + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => return self.read_key(), + Err(source) => return Err(io_error(&temp)(source)), + } + Native::default() + .sync_dir(&self.dir) + .map_err(io_error(&self.dir))?; + Ok(key) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_leftover_temporary_key_is_replaced() { + let dir = tempfile::tempdir().unwrap(); + let name = PrincipalName::new("ada".to_owned()).unwrap(); + let config = UserConfig { + dir: dir.path().to_owned(), + user: name.clone(), + node: name, + }; + fs::write(dir.path().join(format!(".node.key-{}", process::id())), b"").unwrap(); + + let key = config.node_key().unwrap(); + assert_eq!(config.read_key().unwrap().to_bytes(), key.to_bytes()); + } +} + +/// A failure to load the user's configuration. +#[derive(Debug, thiserror::Error)] +pub enum ConfigError { + /// Neither `ORIGIN_CONFIG_DIR`, `XDG_CONFIG_HOME` nor `HOME` is set. + #[error("cannot find the configuration directory: set ORIGIN_CONFIG_DIR or HOME")] + NoDir, + /// No user name is configured. + #[error("who are you? Add `user = \"\"` to {}", .0.display())] + NoUser(PathBuf), + /// A file cannot be read or written. + #[error("cannot access {}", path.display())] + Io { + /// The file. + path: PathBuf, + /// The underlying error. + source: io::Error, + }, + /// `config.toml` is invalid. + #[error("invalid configuration in {}", path.display())] + Toml { + /// The file. + path: PathBuf, + /// What is wrong. + source: toml::de::Error, + }, + /// A configured name is invalid. + #[error("invalid configuration in {}", path.display())] + InvalidName { + /// The file. + path: PathBuf, + /// What is wrong. + source: InvalidName, + }, + /// `node.key` isn't a key. + #[error("{} is not a node key", .0.display())] + MalformedKey(PathBuf), + /// The operating system has no randomness to generate a key with. + #[error("cannot generate a node key")] + Random(#[source] getrandom::Error), +} diff --git a/apps/origin-src/src/fixture.rs b/apps/origin-src/src/fixture.rs new file mode 100644 index 00000000..9be4ccb7 --- /dev/null +++ b/apps/origin-src/src/fixture.rs @@ -0,0 +1,90 @@ +//! Deterministic synthetic working trees, for benchmarks and tests. The same +//! shape always produces byte-identical files, so results are comparable +//! across runs and machines. +//! +//! Behind the `fixture` feature, so the `origin` binary never contains them. + +use std::fmt::Write as _; +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; + +/// The shape of a synthetic tree: `files` files of about `file_size` bytes, +/// `files_per_dir` per directory, in directories nested two levels deep. +#[derive(Clone, Copy, Debug)] +pub struct FixtureTree { + /// Number of files. + pub files: usize, + /// Files in each directory. + pub files_per_dir: usize, + /// Approximate size of each file in bytes. + pub file_size: usize, +} + +impl FixtureTree { + /// Roughly the shape of a large application repository. + pub const LARGE: Self = Self { + files: 20_000, + files_per_dir: 20, + file_size: 4 * 1024, + }; + + fn dir(&self, root: &Path, index: usize) -> PathBuf { + let dir = index / self.files_per_dir; + root.join(format!("dir{}/sub{}", dir / 32, dir % 32)) + } + + fn path(&self, root: &Path, index: usize) -> PathBuf { + self.dir(root, index).join(format!("file{index}.rs")) + } + + /// Source-code-like content: unique per file and per `version`. + fn content(&self, index: usize, version: u64) -> String { + let mut state = (index as u64 + 1).wrapping_mul(0x9e37_79b9_7f4a_7c15) ^ version; + let mut content = String::with_capacity(self.file_size + 64); + while content.len() < self.file_size { + // xorshift64: cheap, deterministic variety. + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + writeln!( + content, + " let value_{:x} = compute({}, {});", + state >> 40, + state % 977, + state % 13 + ) + .expect("writing to a String cannot fail"); + } + content + } + + /// Writes the tree under `root`. + /// + /// # Errors + /// + /// Fails if a file cannot be written. + pub fn write(&self, root: &Path) -> io::Result<()> { + for index in 0..self.files { + if index % self.files_per_dir == 0 { + fs::create_dir_all(self.dir(root, index))?; + } + fs::write(self.path(root, index), self.content(index, 0))?; + } + Ok(()) + } + + /// Rewrites `count` files spread across the tree with new content, + /// numbered by `version` so successive edits differ. + /// + /// # Errors + /// + /// Fails if a file cannot be written. + pub fn edit(&self, root: &Path, count: usize, version: u64) -> io::Result<()> { + let step = (self.files / count.max(1)).max(1); + for index in (0..self.files).step_by(step).take(count) { + fs::write(self.path(root, index), self.content(index, version))?; + } + Ok(()) + } +} diff --git a/apps/origin-src/src/index.rs b/apps/origin-src/src/index.rs index 050522cf..4837ecc4 100644 --- a/apps/origin-src/src/index.rs +++ b/apps/origin-src/src/index.rs @@ -261,6 +261,55 @@ impl Index { pub fn statements(&self, subject: RecordId) -> &[StatementId] { self.statements.get(&subject).map_or(&[], Vec::as_slice) } + + /// The one change whose id starts with `prefix`, a few hex digits. + /// + /// # Errors + /// + /// Fails if no change, or more than one, has an id starting with + /// `prefix`. + pub fn find_change(&self, prefix: &str) -> Result { + let prefix = prefix.to_ascii_lowercase(); + if prefix.is_empty() || !prefix.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return Err(FindChangeError::Invalid(prefix)); + } + let mut matches: Vec = self + .changes + .keys() + .filter(|change| change.to_hex().starts_with(&prefix)) + .copied() + .collect(); + match matches.len() { + 0 => Err(FindChangeError::NotFound(prefix)), + 1 => Ok(matches[0]), + _ => { + matches.sort_unstable(); + Err(FindChangeError::Ambiguous { prefix, matches }) + } + } + } +} + +/// A change id prefix that doesn't name exactly one change. +#[derive(Debug, PartialEq, Eq, thiserror::Error)] +pub enum FindChangeError { + /// It isn't hex digits. + #[error("`{0}` is not a change id")] + Invalid(String), + /// No change has an id starting with it. + #[error("no change has an id starting with `{0}`")] + NotFound(String), + /// Several changes do. + #[error( + "`{prefix}` could be any of the changes {}", + matches.iter().map(ChangeId::to_hex).collect::>().join(", ") + )] + Ambiguous { + /// The prefix. + prefix: String, + /// The changes whose ids start with it. + matches: Vec, + }, } /// What the index keeps of one record: its id, and the fields it's looked @@ -788,6 +837,38 @@ mod tests { assert_eq!(index.heads(change(2)), [], "unknown changes have none"); } + #[test] + fn finds_changes_by_unique_prefix() { + let (_dir, store) = store(); + let ab = ChangeId::from_bytes([0xab; 16]); + let ac = ChangeId::from_bytes([0xac; 16]); + store + .write_all(&[revision(ab, &[], "ab"), revision(ac, &[], "ac")]) + .unwrap(); + let index = Index::open(&store).unwrap(); + + assert_eq!(index.find_change("ab"), Ok(ab)); + assert_eq!(index.find_change("AC"), Ok(ac), "either case"); + assert_eq!(index.find_change(&ab.to_hex()), Ok(ab)); + assert_eq!( + index.find_change("a"), + Err(FindChangeError::Ambiguous { + prefix: "a".to_owned(), + matches: vec![ab, ac] + }) + ); + assert!(matches!( + index.find_change("ff"), + Err(FindChangeError::NotFound(_)) + )); + for invalid in ["", "xyz"] { + assert!(matches!( + index.find_change(invalid), + Err(FindChangeError::Invalid(_)) + )); + } + } + /// Records arriving in several batches, out of order and some twice. fn write_history(store: &Store) { let (a, b) = (change(1), change(2)); diff --git a/apps/origin-src/src/lib.rs b/apps/origin-src/src/lib.rs index b8d99c80..77dfe32d 100644 --- a/apps/origin-src/src/lib.rs +++ b/apps/origin-src/src/lib.rs @@ -1,6 +1,14 @@ //! The origin command line and server. Both share the repository logic in //! this library; `main.rs` only parses arguments and dispatches. +pub mod cli; +pub mod config; +#[cfg(feature = "fixture")] +pub mod fixture; pub mod index; +pub mod output; pub mod store; pub mod targets; +pub mod tree; +pub mod workspace; +pub mod worktree; diff --git a/apps/origin-src/src/main.rs b/apps/origin-src/src/main.rs index b6eab293..237f82e3 100644 --- a/apps/origin-src/src/main.rs +++ b/apps/origin-src/src/main.rs @@ -1,5 +1,18 @@ //! The `origin` binary. -fn main() { - println!("origin {}", env!("CARGO_PKG_VERSION")); +use std::process::ExitCode; + +use clap::Parser; +use origin_src::cli::Cli; +use origin_src::output; + +fn main() -> ExitCode { + output::exit_quietly_on_broken_pipe(); + match Cli::parse().run() { + Ok(()) => ExitCode::SUCCESS, + Err(error) => { + eprintln!("error: {error:#}"); + ExitCode::FAILURE + } + } } diff --git a/apps/origin-src/src/output.rs b/apps/origin-src/src/output.rs new file mode 100644 index 00000000..dea01e86 --- /dev/null +++ b/apps/origin-src/src/output.rs @@ -0,0 +1,122 @@ +//! How commands present what they print. + +use std::fmt; +use std::io; +use std::panic; +use std::process; + +use origin_platform::Platform; +use origin_shared::TreeEntry; +use similar::TextDiff; + +use crate::store::{Store, StoreError}; +use crate::tree::FileChange; + +/// `EPIPE`: writing to a pipe whose reader closed it. It is 32 on every +/// platform origin supports. +const EPIPE: i32 = 32; + +/// Makes the process exit quietly, and successfully, once the reader of its +/// standard output closes it, as in `origin log | head`. Rust ignores +/// `SIGPIPE`, so `println!` panics instead, and every command prints with +/// it. Records are written to survive a crash, so stopping mid-command +/// leaves the repository as a kill would. Other panics report as usual. +pub fn exit_quietly_on_broken_pipe() { + let report = panic::take_hook(); + let broken = format!( + "failed printing to stdout: {}", + io::Error::from_raw_os_error(EPIPE) + ); + panic::set_hook(Box::new(move |info| { + if info.payload_as_str() == Some(broken.as_str()) { + process::exit(0); + } + report(info); + })); +} + +/// The unified diff of one changed file. +pub struct FileDiff<'a> { + change: &'a FileChange, + old: Vec, + new: Vec, +} + +impl<'a> FileDiff<'a> { + /// Reads both sides of a change. + /// + /// # Errors + /// + /// Fails if either side cannot be read or is not a blob. + pub fn new(store: &Store, change: &'a FileChange) -> Result { + let content = |entry: Option| -> Result, StoreError> { + let Some(entry) = entry else { + return Ok(Vec::new()); + }; + let blob = store.read(entry.id)?; + let content = blob.blob_content().map_err(|source| StoreError::Decode { + id: entry.id, + source, + })?; + Ok(content.to_vec()) + }; + Ok(Self { + change, + old: content(change.old)?, + new: content(change.new)?, + }) + } + + /// The content as text, or `None` if it is binary: not valid UTF-8, or + /// holding a NUL byte, which text never contains. + fn text(content: &[u8]) -> Option<&str> { + str::from_utf8(content) + .ok() + .filter(|text| !text.contains('\0')) + } +} + +impl fmt::Display for FileDiff<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let path = &self.change.path; + + let label = |entry: Option, side: &str| { + entry.map_or_else(|| "/dev/null".to_owned(), |_| format!("{side}/{path}")) + }; + let old_label = label(self.change.old, "a"); + let new_label = label(self.change.new, "b"); + + let kind = |entry: Option| entry.map(|entry| entry.kind); + if let (Some(old), Some(new)) = (kind(self.change.old), kind(self.change.new)) + && old != new + { + writeln!(f, "{path}: {old} -> {new}")?; + } + if self.old == self.new { + return Ok(()); + } + let (Some(old), Some(new)) = (Self::text(&self.old), Self::text(&self.new)) else { + return writeln!(f, "Binary file {path} differs"); + }; + write!( + f, + "{}", + TextDiff::from_lines(old, new) + .unified_diff() + .header(&old_label, &new_label) + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn text_is_utf8_without_nul() { + assert_eq!(FileDiff::text("héllo\n".as_bytes()), Some("héllo\n")); + // The PNG signature has no NUL byte, but is not UTF-8. + assert_eq!(FileDiff::text(b"\x89PNG\r\n\x1a\n"), None); + assert_eq!(FileDiff::text(b"a\0b"), None); + } +} diff --git a/apps/origin-src/src/store/mod.rs b/apps/origin-src/src/store/mod.rs index fbb1bf75..7e035276 100644 --- a/apps/origin-src/src/store/mod.rs +++ b/apps/origin-src/src/store/mod.rs @@ -99,10 +99,10 @@ impl Store

{ } /// Removes the temporary files that crashed writes left behind: those - /// older than [`Store::STALE_TEMP`]. It walks every loose object, so - /// only garbage collection calls it. It leaves the packs directory to - /// the compactor, which removes what crashed compactions left there - /// under its lock, so a long compaction never loses its pack. + /// older than an hour. It walks every loose object, so only garbage + /// collection calls it. It leaves the packs directory to the compactor, + /// which removes what crashed compactions left there under its lock, so + /// a long compaction never loses its pack. /// /// # Errors /// diff --git a/apps/origin-src/src/tree.rs b/apps/origin-src/src/tree.rs new file mode 100644 index 00000000..30d5547a --- /dev/null +++ b/apps/origin-src/src/tree.rs @@ -0,0 +1,208 @@ +//! Comparing trees. + +use origin_platform::Platform; +use origin_shared::{EntryName, RepoPath, Tree, TreeEntry, TreeId}; + +use crate::store::{Store, StoreError}; + +/// A file that differs between two trees. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct FileChange { + /// Where the file is. + pub path: RepoPath, + /// The file before, if it existed. + pub old: Option, + /// The file after, if it exists. + pub new: Option, +} + +impl Store

{ + /// Lists the files that differ between two trees, sorted by path. + /// Subtrees with equal ids are skipped without being read, so the cost + /// follows the size of the change. + /// + /// # Errors + /// + /// Fails if a tree that differs cannot be read. + pub fn diff(&self, old: TreeId, new: TreeId) -> Result, StoreError> { + let mut changes = Vec::new(); + self.diff_dir(&RepoPath::root(), Some(old), Some(new), &mut changes)?; + Ok(changes) + } + + /// Diffs two directories, `None` standing for one that doesn't exist. + fn diff_dir( + &self, + dir: &RepoPath, + old: Option, + new: Option, + changes: &mut Vec, + ) -> Result<(), StoreError> { + if old == new { + return Ok(()); + } + let read = |id: Option| id.map(|id| self.get(id)).transpose(); + let (old, new): (Tree, Tree) = ( + read(old)?.unwrap_or_default(), + read(new)?.unwrap_or_default(), + ); + let mut names: Vec<&EntryName> = + old.iter().chain(new.iter()).map(|(name, _)| name).collect(); + names.sort_unstable(); + names.dedup(); + for name in names { + let (old, new) = ( + old.get(name.as_str()).copied(), + new.get(name.as_str()).copied(), + ); + if old == new { + continue; + } + let path = dir.join(name); + // A name can hold a file on one side and a directory on the + // other: the file part is a change, the directory part is + // diffed against an empty tree. + let old_file = old.and_then(TreeEntry::file); + let new_file = new.and_then(TreeEntry::file); + if old_file.is_some() || new_file.is_some() { + changes.push(FileChange { + path: path.clone(), + old: old_file, + new: new_file, + }); + } + let old_tree = old.and_then(TreeEntry::subtree); + let new_tree = new.and_then(TreeEntry::subtree); + self.diff_dir(&path, old_tree, new_tree, changes)?; + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use std::collections::BTreeMap; + + use origin_platform::Native; + use origin_shared::{EncodedObject, EntryKind, Record}; + + use super::*; + + /// Builds nested trees from files inserted by path. + #[derive(Debug, Default)] + struct TreeBuilder { + entries: BTreeMap, + } + + #[derive(Debug)] + enum Node { + File(TreeEntry), + Dir(TreeBuilder), + } + + impl TreeBuilder { + /// Adds a file at `path`, creating parent directories. + fn insert(&mut self, path: &str, entry: TreeEntry) { + let (dir, name) = match path.rsplit_once('/') { + Some((dir, name)) => (Some(dir), name), + None => (None, path), + }; + let mut builder = self; + for component in dir.into_iter().flat_map(|dir| dir.split('/')) { + let node = builder + .entries + .entry(EntryName::new(component).unwrap()) + .or_insert_with(|| Node::Dir(Self::default())); + let Node::Dir(child) = node else { + panic!("{component} is a file") + }; + builder = child; + } + builder + .entries + .insert(EntryName::new(name).unwrap(), Node::File(entry)); + } + + /// Writes every tree to the store and returns the root's id. + fn write(self, store: &Store) -> TreeId { + let tree: Tree = self + .entries + .into_iter() + .map(|(name, node)| { + let entry = match node { + Node::File(entry) => entry, + Node::Dir(dir) => TreeEntry { + kind: EntryKind::Tree, + id: dir.write(store).into(), + }, + }; + (name, entry) + }) + .collect(); + let encoded = tree.encode(); + store.write_all(std::slice::from_ref(&encoded)).unwrap(); + encoded.id().into() + } + } + + fn file(content: &str) -> TreeEntry { + TreeEntry { + kind: EntryKind::File, + id: EncodedObject::blob(content.as_bytes()).id(), + } + } + + fn build(store: &Store, files: &[(&str, &str)]) -> TreeId { + let mut builder = TreeBuilder::default(); + for (path, content) in files { + builder.insert(path, file(content)); + } + builder.write(store) + } + + #[test] + fn diffs_files_across_directories() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::new(dir.path().join(".origin"), Native::default()); + store.init().unwrap(); + let old = build( + &store, + &[ + ("same", "s"), + ("edit", "1"), + ("gone", "g"), + ("dir/inner", "i"), + ("swap", "f"), + ], + ); + let new = build( + &store, + &[ + ("same", "s"), + ("edit", "2"), + ("added/deep", "d"), + ("swap/now-dir", "n"), + ], + ); + + let changes = store.diff(old, new).unwrap(); + let summary: Vec<_> = changes + .iter() + .map(|c| (c.path.as_str(), c.old.is_some(), c.new.is_some())) + .collect(); + assert_eq!( + summary, + [ + ("added/deep", false, true), + ("dir/inner", true, false), + ("edit", true, true), + ("gone", true, false), + ("swap", true, false), + ("swap/now-dir", false, true), + ] + ); + assert_eq!(store.diff(old, old).unwrap(), []); + let empty = build(&store, &[]); + assert_eq!(store.diff(empty, old).unwrap().len(), 5); + } +} diff --git a/apps/origin-src/src/workspace.rs b/apps/origin-src/src/workspace.rs new file mode 100644 index 00000000..ca92e94b --- /dev/null +++ b/apps/origin-src/src/workspace.rs @@ -0,0 +1,882 @@ +//! A working copy and its repository in `.origin/`. +//! +//! ```text +//! .origin/ +//! objects/ targets/ index/ the store, see `store`, `targets` and `index` +//! workspace the revision the working copy is +//! state the stat cache of the last snapshot +//! ``` +//! +//! The working copy is always on a revision of the current change. Every +//! command that reads it snapshots it first. The files the snapshot finds +//! are a draft, which the commands that only read the working copy show +//! without recording. Those that build on it record the draft first: when +//! the files changed, they become a new revision of the change, which +//! evolves from the previous one. Records are written before anything +//! refers to them: the snapshot's objects, then the revision, then the +//! `workspace` file naming it. + +use std::fs; +use std::io; +use std::path::{self, Path, PathBuf}; + +use origin_platform::Native; +use origin_shared::{ + AcceptanceBody, AcceptanceId, Base, BlobId, ChangeId, EncodedObject, EntryKind, EntryName, + Kind, NodePublicKey, Principal, Record, RecordId, Revision, RevisionId, Source, Statement, + TargetId, TargetName, Tree, TreeEntry, TreeId, +}; + +use crate::config::{ConfigError, UserConfig}; +use crate::index::{FindChangeError, Index}; +use crate::output::FileDiff; +use crate::store::{Store, StoreError}; +use crate::worktree::{SnapshotError, StatCache, Worktree}; + +/// A working copy and its repository. +#[derive(Debug)] +pub struct Workspace { + root: PathBuf, + store: Store, + config: UserConfig, + /// The revision the working copy was last recorded as. + revision: RevisionId, +} + +/// The working copy as of a snapshot. +struct WorkingCopy { + id: RevisionId, + revision: Revision, + /// The files as the snapshot found them: the draft, which is the + /// revision's snapshot once recorded. + files: TreeId, + /// The revision's record, if recording the draft made a new revision, + /// which is not written yet. + unsaved: Option, +} + +impl WorkingCopy { + /// The change `prefix` names: `@` for the working copy's, or a unique + /// prefix of its id. + fn find_change(&self, index: &Index, prefix: &str) -> Result { + if prefix == "@" { + return Ok(self.revision.change); + } + index.find_change(prefix) + } +} + +impl Workspace { + /// The metadata directory at the root of every working copy. + pub const META_DIR: &str = ".origin"; + + /// `origin init`: creates a repository in `root`, with the `policy` + /// target naming this node the authority of `policy` and `main`, an + /// empty `main`, and a first change on top of it. + /// + /// # Errors + /// + /// Fails if `root` already has a repository, the node key cannot be + /// loaded, or the repository cannot be written. + pub fn init(root: &Path, config: UserConfig) -> Result { + let root = path::absolute(root).map_err(|source| WorkspaceError::io(root, source))?; + let meta = root.join(Self::META_DIR); + if meta.exists() { + return Err(WorkspaceError::AlreadyInitialized(root)); + } + // First, so a key that cannot be loaded leaves no repository behind. + let key = config.node_key()?; + let store = Store::new(meta, Native::default()); + store.init()?; + + let (policy, policy_tree) = Self::policy(&config, &key.public()); + let empty_tree = Tree::default().encode(); + let empty_description = EncodedObject::blob(b""); + let genesis = |target: &TargetName, state: &EncodedObject, policy| AcceptanceBody { + target: target.id(), + seq: 0, + prev: None, + state: state.id().into(), + landed: Vec::new(), + evidence: Vec::new(), + policy, + }; + store.write_all(&[ + policy, + policy_tree.clone(), + empty_tree.clone(), + empty_description.clone(), + ])?; + let policy = store.append( + &TargetName::POLICY, + &genesis(&TargetName::POLICY, &policy_tree, None).sign(&key), + )?; + let main = store.append( + &TargetName::MAIN, + &genesis(&TargetName::MAIN, &empty_tree, Some(policy)).sign(&key), + )?; + + let revision = Revision { + change: ChangeId::random().map_err(WorkspaceError::Random)?, + predecessors: Vec::new(), + base: Base::Acceptance(main), + deps: Vec::new(), + snapshot: empty_tree.id().into(), + description: empty_description.id().into(), + author: config.user(), + }; + let encoded = revision.encode(); + let mut workspace = Self { + root, + store, + config, + revision: encoded.id().into(), + }; + workspace.save(&[vec![encoded]], workspace.revision)?; + println!( + "Initialized a repository in {}: node:{} is the authority of `policy` and `main`", + workspace.root.display(), + workspace.config.node() + ); + println!("Working copy: {}", workspace.headline(&revision)?); + Ok(workspace) + } + + /// The first `policy.toml`, and the snapshot holding it: this node is + /// the authority of `policy` and `main`, and neither requires anything, + /// so a solo project lands instantly. + fn policy(config: &UserConfig, key: &NodePublicKey) -> (EncodedObject, EncodedObject) { + let node = config.node(); + let policy = format!( + "# Who may land what. Changing it is a landing on `policy`.\n\ + \n\ + [nodes]\n\ + \"{node}\" = \"{key}\"\n\ + \n\ + [targets.policy]\n\ + authority = \"node:{node}\"\n\ + \n\ + [targets.main]\n\ + authority = \"node:{node}\"\n" + ); + let policy = EncodedObject::blob(policy.as_bytes()); + let tree: Tree = [( + EntryName::new("policy.toml").expect("a valid name"), + TreeEntry { + kind: EntryKind::File, + id: policy.id(), + }, + )] + .into_iter() + .collect(); + (policy, tree.encode()) + } + + /// Opens the working copy containing `start`. + /// + /// # Errors + /// + /// Fails if neither `start` nor any parent has a repository, it is on a + /// network file system, or its working copy file is unreadable. + pub fn discover(start: &Path, config: UserConfig) -> Result { + let root = start + .ancestors() + .find(|dir| dir.join(Self::META_DIR).is_dir()) + .ok_or_else(|| WorkspaceError::NotFound(start.to_owned()))?; + let meta = root.join(Self::META_DIR); + let path = meta.join("workspace"); + let revision = fs::read_to_string(&path) + .map_err(|source| WorkspaceError::io(&path, source))? + .trim_end() + .parse() + .map_err(|_| WorkspaceError::Malformed(path))?; + Ok(Self { + root: root.to_owned(), + store: Store::open_writable(meta, Native::default())?, + config, + revision, + }) + } + + fn meta(&self, name: &str) -> PathBuf { + self.root.join(Self::META_DIR).join(name) + } + + /// The root of the working copy. + #[must_use] + pub fn root(&self) -> &Path { + &self.root + } + + /// Snapshots the working copy into a draft, recording nothing, for the + /// commands that only read it. + fn snapshot(&self) -> Result { + let revision: Revision = self.store.get(self.revision)?; + let path = self.meta("state"); + let (files, cache) = + Worktree::new(&self.root, &self.store).snapshot(&StatCache::load(&path))?; + if let Some(cache) = cache { + cache + .save(&path) + .map_err(|source| WorkspaceError::io(&path, source))?; + } + Ok(WorkingCopy { + id: self.revision, + revision, + files, + unsaved: None, + }) + } + + /// Snapshots the working copy and records its draft: a new revision if + /// the files changed, which still has to be saved. + fn record(&self) -> Result { + let working_copy = self.snapshot()?; + if working_copy.files == working_copy.revision.snapshot { + return Ok(working_copy); + } + let revision = Revision { + predecessors: vec![working_copy.id], + snapshot: working_copy.files, + author: self.config.user(), + ..working_copy.revision + }; + let encoded = revision.encode(); + Ok(WorkingCopy { + id: encoded.id().into(), + revision, + files: working_copy.files, + unsaved: Some(encoded), + }) + } + + /// Snapshots the working copy and saves its draft as a new revision if + /// the files changed, for the commands that build on it. + fn refresh(&mut self) -> Result { + let mut working_copy = self.record()?; + if let Some(unsaved) = working_copy.unsaved.take() { + self.save(&[vec![unsaved]], working_copy.id)?; + } + Ok(working_copy) + } + + /// Writes `layers` of objects, then makes `revision` the working copy. + fn save( + &mut self, + layers: &[Vec], + revision: RevisionId, + ) -> Result<(), WorkspaceError> { + self.write(layers)?; + self.point_at(revision) + } + + /// Writes `layers` of objects in order, each durable before the next, + /// so objects may refer to those of earlier layers. + fn write(&self, layers: &[Vec]) -> Result<(), WorkspaceError> { + for layer in layers.iter().filter(|layer| !layer.is_empty()) { + self.store.write_all(layer)?; + } + Ok(()) + } + + /// Durably records that the working copy is `revision`. + fn point_at(&mut self, revision: RevisionId) -> Result<(), WorkspaceError> { + let write = self.store.durable_write(); + write + .stage(self.meta("workspace"), format!("{revision}\n").as_bytes()) + .and_then(|()| write.commit()) + .map_err(StoreError::from)?; + self.revision = revision; + Ok(()) + } + + /// Makes the files match `to`, given that they match `from`. + fn checkout(&self, from: TreeId, to: TreeId) -> Result<(), WorkspaceError> { + let changes = self.store.diff(from, to)?; + Ok(Worktree::new(&self.root, &self.store).checkout(&changes)?) + } + + /// `origin status`: prints the working copy's change, what it is on + /// top of, whether it diverged, and the files it changes. + /// + /// # Errors + /// + /// Fails if the working copy cannot be snapshotted, or the records it + /// refers to cannot be read. + pub fn status(&mut self) -> Result<(), WorkspaceError> { + let working_copy = self.snapshot()?; + let revision = &working_copy.revision; + let index = Index::open(&self.store)?; + println!( + "Working copy: {}{}", + self.headline(revision)?, + self.flags(&index, revision.change)? + ); + println!("On top of: {}", self.describe_base(revision.base)?); + Self::print_divergence(&index, revision.change); + let changes = self + .store + .diff(self.base_tree(revision.base)?, working_copy.files)?; + if changes.is_empty() { + println!("No changes."); + } + for change in changes { + let marker = match (change.old, change.new) { + (None, _) => 'A', + (_, None) => 'D', + _ => 'M', + }; + println!("{marker} {}", change.path); + } + Ok(()) + } + + /// `origin diff`: prints the working copy's changes, line by line. + /// + /// # Errors + /// + /// Fails like [`Workspace::status`], or if a changed file's content + /// cannot be read. + pub fn diff(&mut self) -> Result<(), WorkspaceError> { + let working_copy = self.snapshot()?; + self.print_diff(working_copy.revision.base, working_copy.files) + } + + /// `origin show []`: prints a change's head, or each of them if + /// it diverged, and its diff. Shows the working copy by default. + /// + /// # Errors + /// + /// Fails if the change cannot be found, or like [`Workspace::diff`]. + pub fn show(&mut self, change: Option<&str>) -> Result<(), WorkspaceError> { + let working_copy = self.snapshot()?; + let index = Index::open(&self.store)?; + // Each revision, with the files to show: the working copy's draft. + let revisions = match change { + None => vec![(working_copy.id, Some(working_copy.files))], + Some(change) => index + .heads(working_copy.find_change(&index, change)?) + .into_iter() + .map(|head| (head, None)) + .collect(), + }; + for (position, (id, files)) in revisions.into_iter().enumerate() { + if position > 0 { + println!(); + } + let revision: Revision = self.store.get(id)?; + let files = files.unwrap_or(revision.snapshot); + println!( + "Change {}{}", + revision.change.short(), + self.flags(&index, revision.change)? + ); + let edited = if files == revision.snapshot { + "" + } else { + ", with unrecorded edits" + }; + println!("Revision {} by {}{edited}", id.short(), revision.author); + println!("On top of: {}", self.describe_base(revision.base)?); + for (issuer, reason) in self.abandonments(&index, id)? { + println!("Abandoned by {issuer}: {reason}"); + } + println!(); + let description = self.description(&revision)?; + if description.trim().is_empty() { + println!(" (no description)"); + } + for line in description.lines() { + println!(" {line}"); + } + println!(); + self.print_diff(revision.base, files)?; + } + Ok(()) + } + + /// Prints the changes `files` make to the snapshot of `base`. + fn print_diff(&self, base: Base, files: TreeId) -> Result<(), WorkspaceError> { + let base = self.base_tree(base)?; + for change in self.store.diff(base, files)? { + print!("{}", FileDiff::new(&self.store, &change)?); + } + Ok(()) + } + + /// `origin new [description]`: finishes the current change, and starts + /// a new one on top of it. + /// + /// # Errors + /// + /// Fails if the working copy cannot be snapshotted or the new change + /// cannot be written. + pub fn new_change(&mut self, description: &str) -> Result<(), WorkspaceError> { + let working_copy = self.record()?; + let description = EncodedObject::blob(description.as_bytes()); + let revision = Revision { + change: ChangeId::random().map_err(WorkspaceError::Random)?, + predecessors: Vec::new(), + base: Base::Revision(working_copy.id), + deps: Vec::new(), + snapshot: working_copy.revision.snapshot, + description: description.id().into(), + author: self.config.user(), + }; + let encoded = revision.encode(); + let id = encoded.id().into(); + let first = working_copy.unsaved.into_iter().chain([description]); + self.save(&[first.collect(), vec![encoded]], id)?; + println!("Working copy: {}", self.headline(&revision)?); + println!("On top of: {}", self.headline(&working_copy.revision)?); + Ok(()) + } + + /// `origin describe `: replaces the current change's + /// description, with a new revision. + /// + /// # Errors + /// + /// Fails if the working copy cannot be snapshotted or the revision + /// cannot be written. + pub fn describe(&mut self, description: &str) -> Result<(), WorkspaceError> { + let working_copy = self.record()?; + let description = EncodedObject::blob(description.as_bytes()); + let revision = Revision { + predecessors: vec![working_copy.id], + description: description.id().into(), + author: self.config.user(), + ..working_copy.revision + }; + let encoded = revision.encode(); + let id = encoded.id().into(); + let first = working_copy.unsaved.into_iter().chain([description]); + self.save(&[first.collect(), vec![encoded]], id)?; + println!("Working copy: {}", self.headline(&revision)?); + Ok(()) + } + + /// `origin edit `: switches the working copy to the change's + /// head. + /// + /// # Errors + /// + /// Fails if the change cannot be found or diverged, or the working copy + /// cannot be snapshotted or checked out. + pub fn edit(&mut self, change: &str) -> Result<(), WorkspaceError> { + let working_copy = self.refresh()?; + let index = Index::open(&self.store)?; + let change = working_copy.find_change(&index, change)?; + let head = Self::single_head(&index, change)?; + let revision: Revision = self.store.get(head)?; + if head != working_copy.id { + self.checkout(working_copy.revision.snapshot, revision.snapshot)?; + self.point_at(head)?; + } + println!("Working copy: {}", self.headline(&revision)?); + Ok(()) + } + + /// `origin abandon [] --reason `: records that the + /// change was given up, and why, with a `core.abandon` statement on its + /// head. Abandoning the current change starts a new one where it + /// started, and restores those files. + /// + /// # Errors + /// + /// Fails if the change cannot be found or diverged, or the records + /// cannot be written. + pub fn abandon(&mut self, change: Option<&str>, reason: &str) -> Result<(), WorkspaceError> { + let working_copy = self.refresh()?; + let index = Index::open(&self.store)?; + let change = match change { + Some(change) => working_copy.find_change(&index, change)?, + None => working_copy.revision.change, + }; + let head = Self::single_head(&index, change)?; + let reason = EncodedObject::blob(reason.as_bytes()); + let statement = Statement { + subject: RecordId::Revision(head), + kind: Kind::ABANDON, + verdict: None, + issuer: self.config.user(), + inputs: None, + payload: Some(reason.id().into()), + supersedes: None, + } + .encode(); + if change != working_copy.revision.change { + self.write(&[vec![reason], vec![statement]])?; + println!("Abandoned change {}", change.short()); + return Ok(()); + } + + let abandoned: Revision = self.store.get(head)?; + let empty = EncodedObject::blob(b""); + let revision = Revision { + change: ChangeId::random().map_err(WorkspaceError::Random)?, + predecessors: Vec::new(), + base: abandoned.base, + deps: abandoned.deps, + snapshot: self.base_tree(abandoned.base)?, + description: empty.id().into(), + author: self.config.user(), + }; + let encoded = revision.encode(); + self.write(&[vec![reason, empty], vec![statement, encoded.clone()]])?; + self.checkout(working_copy.revision.snapshot, revision.snapshot)?; + self.point_at(encoded.id().into())?; + println!("Abandoned change {}", change.short()); + println!("Working copy: {}", self.headline(&revision)?); + println!("On top of: {}", self.describe_base(revision.base)?); + Ok(()) + } + + /// `origin converge `: ends a change's divergence with a + /// revision evolving from all its heads. It keeps the files and + /// description of the working copy, if it is one of the heads, or else + /// of the newest head. + /// + /// # Errors + /// + /// Fails if the change cannot be found or didn't diverge, or the + /// revision cannot be written. + pub fn converge(&mut self, change: &str) -> Result<(), WorkspaceError> { + let working_copy = self.refresh()?; + let index = Index::open(&self.store)?; + let change = working_copy.find_change(&index, change)?; + let heads = index.heads(change); + if heads.len() < 2 { + return Err(WorkspaceError::NotDivergent(change)); + } + let kept = if heads.contains(&working_copy.id) { + working_copy.id + } else { + heads[heads.len() - 1] + }; + let revision = Revision { + predecessors: heads.clone(), + author: self.config.user(), + ..self.store.get(kept)? + }; + let encoded = revision.encode(); + let id = encoded.id().into(); + self.write(&[vec![encoded]])?; + if change == working_copy.revision.change { + self.checkout(working_copy.revision.snapshot, revision.snapshot)?; + self.point_at(id)?; + } + println!( + "Converged change {}: revision {} evolves from {}, with the files of {}", + change.short(), + id.short(), + Self::list(&heads), + kept.short() + ); + Ok(()) + } + + /// `origin log []`: prints the working copy's stack of changes + /// down to the target it's on, then the target's acceptances, newest + /// first. With a target, prints that target's acceptances instead, + /// under the stack if it's on that target. + /// + /// # Errors + /// + /// Fails if the target doesn't exist, or a record cannot be read. + pub fn log( + &mut self, + target: Option, + limit: Option, + ) -> Result<(), WorkspaceError> { + let working_copy = self.snapshot()?; + let index = Index::open(&self.store)?; + let mut next = working_copy.revision.base; + let mut stack = vec![(working_copy.id, working_copy.revision)]; + let acceptance = loop { + match next { + Base::Revision(id) => { + let revision: Revision = self.store.get(id)?; + next = revision.base; + stack.push((id, revision)); + } + Base::Acceptance(id) => break id, + } + }; + let on = self.store.get(acceptance)?.body().target; + let target = match target { + Some(target) => target, + None => self.target_name(on)?, + }; + let log = self.store.log(&target)?; + if log.is_empty() { + return Err(WorkspaceError::UnknownTarget(target)); + } + if target.id() == on { + for (id, revision) in &stack { + let marker = if *id == working_copy.id { '@' } else { '○' }; + println!( + "{marker} {}{}", + self.headline(revision)?, + self.flags(&index, revision.change)? + ); + } + } + let shown = log + .iter() + .enumerate() + .rev() + .take(limit.unwrap_or(usize::MAX)); + for (seq, &id) in shown { + println!("◆ {target} #{seq} {}", id.short()); + for source in &self.store.get(id)?.body().landed { + match *source { + Source::Revision(id) => { + let revision = self.store.get(id)?; + println!( + " {}{}", + self.headline(&revision)?, + self.flags(&index, revision.change)? + ); + } + Source::Target(id) => { + println!(" {}", self.describe_acceptance(id)?); + } + } + } + } + Ok(()) + } + + /// `origin evolog `: prints every revision of a change, newest + /// first, marking its heads. + /// + /// # Errors + /// + /// Fails if the change cannot be found, or a record cannot be read. + pub fn evolog(&mut self, change: &str) -> Result<(), WorkspaceError> { + let working_copy = self.snapshot()?; + let index = Index::open(&self.store)?; + let change = working_copy.find_change(&index, change)?; + let heads = index.heads(change); + println!("Change {}{}", change.short(), self.flags(&index, change)?); + for &id in index.revisions(change).iter().rev() { + let revision: Revision = self.store.get(id)?; + let marker = if id == working_copy.id { '@' } else { '○' }; + let head = if heads.contains(&id) { " (head)" } else { "" }; + println!("{marker} {} {}{head}", id.short(), self.summary(&revision)?); + if revision.predecessors.len() > 1 { + println!(" converges {}", Self::list(&revision.predecessors)); + } + } + Ok(()) + } + + /// `origin index rebuild`: reconstructs the index from the store. + /// + /// # Errors + /// + /// Fails if the store cannot be read or the index written. + pub fn rebuild_index(&self) -> Result<(), WorkspaceError> { + let index = Index::rebuild(&self.store)?.index; + println!("Rebuilt the index of {} records", index.arrivals().len()); + Ok(()) + } + + /// The head of a change that didn't diverge. + fn single_head(index: &Index, change: ChangeId) -> Result { + match index.heads(change)[..] { + [head] => Ok(head), + ref heads => Err(WorkspaceError::Divergent { + change, + heads: heads.to_vec(), + }), + } + } + + /// The description of a revision. + fn description(&self, revision: &Revision) -> Result { + self.text(revision.description) + } + + /// A blob's content, as text. + fn text(&self, blob: BlobId) -> Result { + let id = blob.into(); + let blob = self.store.read(id)?; + let content = blob + .blob_content() + .map_err(|source| StoreError::Decode { id, source })?; + Ok(String::from_utf8_lossy(content).into_owned()) + } + + /// The first line of a revision's description. + fn summary(&self, revision: &Revision) -> Result { + let description = self.description(revision)?; + Ok(match description.lines().next() { + Some(line) if !line.trim().is_empty() => line.to_owned(), + _ => "(no description)".to_owned(), + }) + } + + /// A revision's change and summary. + fn headline(&self, revision: &Revision) -> Result { + Ok(format!( + "{} {}", + revision.change.short(), + self.summary(revision)? + )) + } + + /// Marks a divergent or abandoned change. + fn flags(&self, index: &Index, change: ChangeId) -> Result { + let heads = index.heads(change); + let mut flags = String::new(); + if heads.len() > 1 { + flags.push_str(" (divergent)"); + } + for head in heads { + if !self.abandonments(index, head)?.is_empty() { + flags.push_str(" (abandoned)"); + break; + } + } + Ok(flags) + } + + /// Who abandoned a revision, and why. + fn abandonments( + &self, + index: &Index, + revision: RevisionId, + ) -> Result, WorkspaceError> { + let mut abandonments = Vec::new(); + for &id in index.statements(RecordId::Revision(revision)) { + let statement = self.store.get(id)?; + if statement.kind == Kind::ABANDON { + let reason = match statement.payload { + Some(payload) => self.text(payload)?, + None => String::new(), + }; + abandonments.push((statement.issuer, reason)); + } + } + Ok(abandonments) + } + + /// Explains a divergent change's heads, and how to converge them. + fn print_divergence(index: &Index, change: ChangeId) { + let heads = index.heads(change); + if heads.len() > 1 { + println!( + "Divergent: change {} has {} heads, {}. Run `origin converge {}`.", + change.short(), + heads.len(), + Self::list(&heads), + change.short() + ); + } + } + + fn list(revisions: &[RevisionId]) -> String { + let shorts: Vec<_> = revisions.iter().map(RevisionId::short).collect(); + shorts.join(", ") + } + + /// The snapshot a revision was made on top of. + fn base_tree(&self, base: Base) -> Result { + Ok(match base { + Base::Acceptance(id) => self.store.get(id)?.body().state, + Base::Revision(id) => self.store.get(id)?.snapshot, + }) + } + + fn describe_base(&self, base: Base) -> Result { + match base { + Base::Acceptance(id) => self.describe_acceptance(id), + Base::Revision(id) => self.headline(&self.store.get(id)?), + } + } + + /// A target and position, such as `main #3`. + fn describe_acceptance(&self, id: AcceptanceId) -> Result { + let acceptance = self.store.get(id)?; + let body = acceptance.body(); + Ok(format!("{} #{}", self.target_name(body.target)?, body.seq)) + } + + fn target_name(&self, id: TargetId) -> Result { + self.store + .targets()? + .into_iter() + .find(|target| target.id() == id) + .ok_or(WorkspaceError::UnknownTargetId(id)) + } +} + +/// A failure to operate on a working copy. +#[derive(Debug, thiserror::Error)] +pub enum WorkspaceError { + /// No repository was found. + #[error("not in an origin repository: {} or its parents have no `.origin` directory", .0.display())] + NotFound(PathBuf), + /// `init` found an existing repository. + #[error("{} already has a repository", .0.display())] + AlreadyInitialized(PathBuf), + /// The change has several heads, and the command needs one. + #[error( + "change {} is divergent: its heads are {}. Run `origin converge {}` first", + change.short(), + Workspace::list(heads), + change.short() + )] + Divergent { + /// The change. + change: ChangeId, + /// Its heads. + heads: Vec, + }, + /// `converge` was given a change with a single head. + #[error("change {} is not divergent", .0.short())] + NotDivergent(ChangeId), + /// No target has this name. + #[error("no target is named `{0}`")] + UnknownTarget(TargetName), + /// An acceptance belongs to a target this repository doesn't have. + #[error("no target has the id {0}")] + UnknownTargetId(TargetId), + /// A change id prefix doesn't name one change. + #[error(transparent)] + FindChange(#[from] FindChangeError), + /// The working copy file isn't a revision id. + #[error("{} is not a revision id", .0.display())] + Malformed(PathBuf), + /// A metadata file cannot be accessed. + #[error("cannot access {}", path.display())] + Io { + /// The file. + path: PathBuf, + /// The underlying error. + source: io::Error, + }, + /// The operating system has no randomness for a change id. + #[error("cannot generate a change id")] + Random(#[source] getrandom::Error), + /// The user's configuration is unusable. + #[error(transparent)] + Config(#[from] ConfigError), + /// Objects cannot be read or written. + #[error(transparent)] + Store(#[from] StoreError), + /// The working copy cannot be snapshotted or checked out. + #[error(transparent)] + Snapshot(#[from] SnapshotError), +} + +impl WorkspaceError { + fn io(path: &Path, source: io::Error) -> Self { + Self::Io { + path: path.to_owned(), + source, + } + } +} diff --git a/apps/origin-src/src/worktree.rs b/apps/origin-src/src/worktree.rs new file mode 100644 index 00000000..96889fe6 --- /dev/null +++ b/apps/origin-src/src/worktree.rs @@ -0,0 +1,826 @@ +//! The files of a working copy: snapshotting them into trees, and checking +//! trees out into them. +//! +//! There is no staging area: a snapshot records every file in the working +//! copy. To keep that fast, a stat cache remembers each file's metadata and +//! blob id, so only files whose metadata changed are read and hashed, and +//! every phase runs in parallel. + +use std::collections::HashMap; +use std::ffi::OsStr; +use std::fs::{self, File}; +use std::io; +use std::ops::Range; +use std::os::unix::ffi::OsStrExt; +use std::os::unix::fs::{MetadataExt, PermissionsExt, symlink}; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::thread; +use std::time::{SystemTime, UNIX_EPOCH}; + +use origin_platform::Platform; +use origin_shared::object::{DecodeError, Reader}; +use origin_shared::{ + EncodedObject, EntryKind, EntryName, ObjectId, Record, RepoPath, Tree, TreeEntry, TreeId, +}; + +use crate::store::{Store, StoreError}; +use crate::tree::FileChange; + +/// File metadata that changes whenever the content might have. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Stat { + kind: EntryKind, + size: u64, + /// Modification time in nanoseconds since the Unix epoch. Tools can set + /// it back, so it does not prove a file is unchanged on its own. + mtime: i64, + /// Status change time in nanoseconds since the Unix epoch. Every write + /// moves it forward, and nothing can set it back. + ctime: i64, + inode: u64, +} + +impl Stat { + fn new(kind: EntryKind, metadata: &fs::Metadata) -> Self { + Self { + kind, + size: metadata.size(), + mtime: metadata.mtime() * 1_000_000_000 + metadata.mtime_nsec(), + ctime: metadata.ctime() * 1_000_000_000 + metadata.ctime_nsec(), + inode: metadata.ino(), + } + } +} + +/// The stat cache: what each file looked like when it was last hashed, and +/// the snapshot those files made. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct StatCache { + /// When the scan that produced the cache started, in nanoseconds since + /// the Unix epoch. + scanned_at: i64, + /// The root tree of that scan. A scan that finds the same files, all + /// vouched for by the cache, finds this tree without building it. + root: Option, + /// Keyed by path. Paths are only looked up, never turned into trees, so + /// they are not validated when loaded. + files: HashMap, +} + +impl StatCache { + /// Identifies the binary format. + const MAGIC: &[u8; 4] = b"OST3"; + + /// How long before a scan a file must have been modified for its cache + /// entry to be trusted, in nanoseconds. Filesystems record modification + /// times in ticks of up to 2 seconds (FAT), and a file edited again + /// within the tick of its last modification keeps the same metadata. + const RACY_MARGIN: i64 = 2_000_000_000; + + /// Looks up a file whose metadata has not changed. + /// + /// Files modified shortly before the previous scan started ("racy" + /// files) are never trusted, since they may have changed again without + /// their metadata changing. They are rehashed until they settle. + fn get(&self, path: &RepoPath, stat: &Stat) -> Option { + let (cached, id) = self.files.get(path.as_str())?; + let settled = + stat.mtime.max(stat.ctime) < self.scanned_at.saturating_sub(Self::RACY_MARGIN); + (cached == stat && settled).then_some(*id) + } + + /// Loads the cache, treating a missing or unreadable one as empty: the + /// cache only saves work, so the next scan just rehashes everything. + #[must_use] + pub fn load(path: &Path) -> Self { + fs::read(path) + .ok() + .and_then(|bytes| Self::decode(&bytes).ok()) + .unwrap_or_default() + } + + /// Saves the cache atomically, but not durably: losing it only costs + /// rehashing. Every object it names is already durable. + /// + /// # Errors + /// + /// Fails if the file cannot be written. + pub fn save(&self, path: &Path) -> io::Result<()> { + let temp = path.with_extension("tmp"); + fs::write(&temp, self.encode())?; + fs::rename(temp, path) + } + + /// `magic scanned_at:i64 has_root:u8 [root:[u8; 32]]` then, per file, + /// `path_len:u32 path kind:u8 size:u64 mtime:i64 ctime:i64 inode:u64 + /// id:[u8; 32]`. + fn encode(&self) -> Vec { + let mut out = Vec::with_capacity(48 + self.files.len() * 96); + out.extend_from_slice(Self::MAGIC); + out.extend_from_slice(&self.scanned_at.to_le_bytes()); + match self.root { + Some(root) => { + out.push(1); + out.extend_from_slice(root.as_bytes()); + } + None => out.push(0), + } + for (path, (stat, id)) in &self.files { + let path_len = u32::try_from(path.len()).expect("paths are shorter than 4 GiB"); + out.extend_from_slice(&path_len.to_le_bytes()); + out.extend_from_slice(path.as_bytes()); + out.push(stat.kind as u8); + out.extend_from_slice(&stat.size.to_le_bytes()); + out.extend_from_slice(&stat.mtime.to_le_bytes()); + out.extend_from_slice(&stat.ctime.to_le_bytes()); + out.extend_from_slice(&stat.inode.to_le_bytes()); + out.extend_from_slice(id.as_bytes()); + } + out + } + + /// Reads what [`StatCache::encode`] wrote. + fn decode(bytes: &[u8]) -> Result { + let mut reader = Reader::new(bytes); + if reader.take(Self::MAGIC.len())? != Self::MAGIC { + // Another format, or another version of this one. + return Err(DecodeError::NonCanonical("stat cache header")); + } + let scanned_at = i64::from_le_bytes(reader.array()?); + let root = reader.option(|reader| reader.array().map(TreeId::from_bytes))?; + let mut files = HashMap::new(); + while reader.remaining() > 0 { + let path = reader.prefixed_str()?.to_owned(); + let kind = EntryKind::from_byte(reader.u8()?)?; + if kind.is_tree() { + return Err(DecodeError::UnknownTag { + field: "file kind", + tag: kind as u8, + }); + } + let stat = Stat { + kind, + size: reader.u64()?, + mtime: i64::from_le_bytes(reader.array()?), + ctime: i64::from_le_bytes(reader.array()?), + inode: reader.u64()?, + }; + let id = ObjectId::from_bytes(reader.array()?); + files.insert(path, (stat, id)); + } + Ok(Self { + scanned_at, + root, + files, + }) + } +} + +/// Everything the walk found. +struct Walk { + /// Every directory, root first, each depth after the previous one. + dirs: Vec, + /// The range of `dirs` at each depth. + depths: Vec>, + files: Vec, +} + +/// A directory found by the walk. +struct FoundDir { + path: RepoPath, + absolute: PathBuf, + entries: Vec<(EntryName, Child)>, +} + +/// An entry of a [`FoundDir`], indexing the walk's directories or files. +enum Child { + Dir(usize), + File(usize), +} + +/// What listing a directory says an entry is. +enum Listed { + Dir, + File { symlink: bool }, +} + +/// A file found by the walk, not yet examined. +struct FoundFile { + path: RepoPath, + absolute: PathBuf, + symlink: bool, +} + +/// What examining a file found. +struct Examined { + stat: Stat, + id: ObjectId, + /// The file's blob, if it had to be read because the cache could not + /// vouch for it. + blob: Option, +} + +/// The files of the working copy rooted at `root`, whose snapshots go to +/// `store`. +pub struct Worktree<'a, P> { + root: &'a Path, + store: &'a Store

, +} + +impl<'a, P: Platform> Worktree<'a, P> { + /// Below this many items, threads cost more than they save. + const PARALLEL_THRESHOLD: usize = 64; + + /// The working copy rooted at `root`. + #[must_use] + pub fn new(root: &'a Path, store: &'a Store

) -> Self { + Self { root, store } + } + + /// Records every file into the store and returns the root tree, with the + /// updated stat cache if it changed. + /// + /// Three phases, each parallel: list directories one depth at a time, + /// examine every file (one `lstat`, plus reading and hashing the files + /// the cache cannot vouch for), and build trees one depth at a time from + /// the deepest. Then the new blobs and trees are written in one batch. + /// A tree may be published before a blob it names, if a crash cuts the + /// batch short, but nothing refers to the tree until the batch commits, + /// and the next snapshot rewrites the blob: the stat cache that would + /// vouch for it is only saved after the commit. + /// + /// # Errors + /// + /// Fails if the working copy cannot be read, contains a file name that + /// cannot be tracked, or objects cannot be written. + pub fn snapshot( + &self, + cache: &StatCache, + ) -> Result<(TreeId, Option), SnapshotError> { + let scanned_at = Self::now_nanos(); + let Walk { + dirs, + depths, + files, + } = self.walk()?; + let mut examined = Self::par_map(&files, |file| Self::examine(file, cache))?; + let unchanged = + files.len() == cache.files.len() && examined.iter().all(|file| file.blob.is_none()); + if let Some(root) = cache.root.filter(|_| unchanged) { + return Ok((root, None)); + } + + let mut objects: Vec = examined + .iter_mut() + .filter_map(|file| file.blob.take()) + .collect(); + let mut trees = vec![None; dirs.len()]; + for depth in depths.into_iter().rev() { + let built = Self::par_map(&dirs[depth.clone()], |dir| { + Ok(Self::build_tree(dir, &trees, &examined)) + })?; + for (slot, tree) in trees[depth].iter_mut().zip(built) { + *slot = tree.map(|tree| { + let id = tree.id().into(); + objects.push(tree); + id + }); + } + } + let root = trees[0].unwrap_or_else(|| { + let empty = Tree::default().encode(); + let id = empty.id().into(); + objects.push(empty); + id + }); + self.store.write_all(&objects)?; + + let next = StatCache { + scanned_at, + root: Some(root), + files: files + .into_iter() + .zip(examined) + .map(|(file, Examined { stat, id, .. })| { + (file.path.as_str().to_owned(), (stat, id)) + }) + .collect(), + }; + Ok((root, Some(next))) + } + + /// Lists the working copy one depth at a time, listing each depth's + /// directories in parallel. + fn walk(&self) -> Result { + let mut dirs = vec![FoundDir { + path: RepoPath::root(), + absolute: self.root.to_owned(), + entries: Vec::new(), + }]; + let (mut depths, mut files) = (Vec::new(), Vec::new()); + let mut depth = 0..1; + while !depth.is_empty() { + let listings = Self::par_map(&dirs[depth.clone()], |dir| Self::list(&dir.absolute))?; + let next = dirs.len(); + for (parent, listing) in depth.clone().zip(listings) { + for (name, listed) in listing { + let path = dirs[parent].path.join(&name); + let absolute = dirs[parent].absolute.join(name.as_str()); + let child = match listed { + Listed::Dir => { + dirs.push(FoundDir { + path, + absolute, + entries: Vec::new(), + }); + Child::Dir(dirs.len() - 1) + } + Listed::File { symlink } => { + files.push(FoundFile { + path, + absolute, + symlink, + }); + Child::File(files.len() - 1) + } + }; + dirs[parent].entries.push((name, child)); + } + } + depths.push(depth); + depth = next..dirs.len(); + } + Ok(Walk { + dirs, + depths, + files, + }) + } + + /// Lists one directory, skipping repository metadata. + fn list(dir: &Path) -> Result, SnapshotError> { + let io_error = |source| SnapshotError::Io { + path: dir.to_owned(), + source, + }; + let mut listing = Vec::new(); + for entry in fs::read_dir(dir).map_err(io_error)? { + let entry = entry.map_err(io_error)?; + let Some(name) = entry.file_name().to_str().map(str::to_owned) else { + return Err(SnapshotError::NonUtf8Name(entry.path())); + }; + if EntryName::is_reserved(&name) { + continue; + } + let name = + EntryName::new(name).map_err(|_| SnapshotError::UntrackableName(entry.path()))?; + // On most filesystems the type comes with the listing, without a + // `stat` call. + let file_type = entry.file_type().map_err(io_error)?; + let listed = if file_type.is_dir() { + Listed::Dir + } else if file_type.is_file() || file_type.is_symlink() { + Listed::File { + symlink: file_type.is_symlink(), + } + } else { + // Sockets, FIFOs and devices have no content to track. + continue; + }; + listing.push((name, listed)); + } + Ok(listing) + } + + /// Stats a file, and reads and hashes it unless the cache vouches for it. + fn examine(file: &FoundFile, cache: &StatCache) -> Result { + let io_error = |source| SnapshotError::Io { + path: file.absolute.clone(), + source, + }; + let metadata = fs::symlink_metadata(&file.absolute).map_err(io_error)?; + let kind = if file.symlink { + EntryKind::Symlink + } else if metadata.mode() & 0o111 != 0 { + EntryKind::Executable + } else { + EntryKind::File + }; + let stat = Stat::new(kind, &metadata); + if let Some(id) = cache.get(&file.path, &stat) { + return Ok(Examined { + stat, + id, + blob: None, + }); + } + let blob = if file.symlink { + let target = fs::read_link(&file.absolute).map_err(io_error)?; + EncodedObject::blob(target.as_os_str().as_bytes()) + } else { + let size = usize::try_from(stat.size).unwrap_or(0); + EncodedObject::read_blob(File::open(&file.absolute).map_err(io_error)?, size) + .map_err(io_error)? + }; + Ok(Examined { + stat, + id: blob.id(), + blob: Some(blob), + }) + } + + /// Builds a directory's tree, given the trees of every deeper directory. + /// Returns `None` for a directory without files, which is not tracked. + fn build_tree( + dir: &FoundDir, + trees: &[Option], + examined: &[Examined], + ) -> Option { + let tree: Tree = dir + .entries + .iter() + .filter_map(|(name, child)| { + let entry = match *child { + Child::Dir(index) => TreeEntry { + kind: EntryKind::Tree, + id: trees[index]?.into(), + }, + Child::File(index) => TreeEntry { + kind: examined[index].stat.kind, + id: examined[index].id, + }, + }; + Some((name.clone(), entry)) + }) + .collect(); + (!tree.is_empty()).then(|| tree.encode()) + } + + /// Makes the files match a snapshot, given how they differ from it: + /// removes the files `changes` remove, then writes the ones they add or + /// modify. Directories left empty are removed. + /// + /// # Errors + /// + /// Fails if a file's content cannot be read from the store, or a file + /// cannot be removed or written. + pub fn checkout(&self, changes: &[FileChange]) -> Result<(), SnapshotError> { + // Removing first frees the paths of files that become directories, + // and of directories that become files. + for change in changes.iter().filter(|change| change.new.is_none()) { + let path = self.absolute(&change.path); + Self::remove(&path)?; + for dir in path.ancestors().skip(1) { + // Stops at the first directory that isn't empty, or the root. + if dir == self.root || fs::remove_dir(dir).is_err() { + break; + } + } + } + for change in changes { + if let Some(entry) = change.new { + self.write_file(&change.path, entry)?; + } + } + Ok(()) + } + + fn absolute(&self, path: &RepoPath) -> PathBuf { + self.root.join(path.as_str()) + } + + /// Removes a file, if it's there. + fn remove(path: &Path) -> Result<(), SnapshotError> { + match fs::remove_file(path) { + Err(error) if error.kind() != io::ErrorKind::NotFound => Err(SnapshotError::Io { + path: path.to_owned(), + source: error, + }), + _ => Ok(()), + } + } + + /// Writes the file `entry` describes at `path`, replacing any file + /// there. + fn write_file(&self, path: &RepoPath, entry: TreeEntry) -> Result<(), SnapshotError> { + let blob = self.store.read(entry.id)?; + let content = blob.blob_content().map_err(|source| StoreError::Decode { + id: entry.id, + source, + })?; + let path = self.absolute(path); + let io_error = |source| SnapshotError::Io { + path: path.clone(), + source, + }; + // Never write through a symlink, or keep the old file's mode. + Self::remove(&path)?; + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).map_err(io_error)?; + } + match entry.kind { + EntryKind::Symlink => symlink(OsStr::from_bytes(content), &path).map_err(io_error), + EntryKind::Executable => fs::write(&path, content) + .and_then(|()| fs::set_permissions(&path, fs::Permissions::from_mode(0o755))) + .map_err(io_error), + EntryKind::File | EntryKind::Tree => fs::write(&path, content).map_err(io_error), + } + } + + /// Maps `items` in order, on as many threads as there are cores when + /// there are enough items. Threads take the next item as they finish + /// one, since some files take much longer than others. + fn par_map( + items: &[T], + map: impl Fn(&T) -> Result + Sync, + ) -> Result, SnapshotError> { + if items.len() < Self::PARALLEL_THRESHOLD { + return items.iter().map(map).collect(); + } + let workers = thread::available_parallelism().map_or(4, usize::from); + let next = AtomicUsize::new(0); + let results = Mutex::new(Vec::with_capacity(items.len())); + thread::scope(|scope| { + let handles: Vec<_> = (0..workers) + .map(|_| { + scope.spawn(|| -> Result<(), SnapshotError> { + let mut local = Vec::new(); + loop { + let index = next.fetch_add(1, Ordering::Relaxed); + let Some(item) = items.get(index) else { + break; + }; + local.push((index, map(item)?)); + } + results + .lock() + .expect("no worker panics holding the lock") + .extend(local); + Ok(()) + }) + }) + .collect(); + handles + .into_iter() + .try_for_each(|handle| handle.join().expect("snapshot threads do not panic")) + })?; + let mut results = results + .into_inner() + .expect("no worker panics holding the lock"); + results.sort_unstable_by_key(|(index, _)| *index); + Ok(results.into_iter().map(|(_, result)| result).collect()) + } + + fn now_nanos() -> i64 { + let since_epoch = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default(); + i64::try_from(since_epoch.as_nanos()).unwrap_or(i64::MAX) + } +} + +/// A failure to snapshot or check out the working copy. +#[derive(Debug, thiserror::Error)] +pub enum SnapshotError { + /// A file or directory cannot be read or written. + #[error("cannot access {}", path.display())] + Io { + /// The file or directory. + path: PathBuf, + /// The underlying error. + source: io::Error, + }, + /// A file name is not UTF-8. + #[error("cannot track {}: its name is not UTF-8", .0.display())] + NonUtf8Name(PathBuf), + /// A file name cannot appear in a tree. + #[error("cannot track {}: invalid file name", .0.display())] + UntrackableName(PathBuf), + /// Objects cannot be read or stored. + #[error(transparent)] + Store(#[from] StoreError), +} + +#[cfg(test)] +mod tests { + use origin_platform::Native; + + use super::*; + + struct Fixture { + dir: tempfile::TempDir, + store: Store, + } + + impl Fixture { + fn new() -> Self { + let dir = tempfile::tempdir().unwrap(); + let store = Store::new(dir.path().join(".origin"), Native::default()); + store.init().unwrap(); + Self { dir, store } + } + + fn worktree(&self) -> Worktree<'_, Native> { + Worktree::new(self.dir.path(), &self.store) + } + + fn write(&self, path: &str, content: &str) { + let path = self.dir.path().join(path); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, content).unwrap(); + } + + /// Takes a snapshot, returning the cache to use next. + fn snapshot(&self, cache: &StatCache) -> (TreeId, StatCache) { + let (root, next) = self.worktree().snapshot(cache).unwrap(); + (root, next.unwrap_or_else(|| cache.clone())) + } + + fn entry(&self, root: TreeId, path: &str) -> TreeEntry { + let mut entry = TreeEntry { + kind: EntryKind::Tree, + id: root.into(), + }; + for component in path.split('/') { + let tree = self.store.get(TreeId::from(entry.id)).unwrap(); + entry = *tree.get(component).unwrap(); + } + entry + } + } + + #[test] + fn records_files_kinds_and_skips_metadata() { + let fixture = Fixture::new(); + fixture.write("src/lib.rs", "lib"); + fixture.write("run.sh", "#!/bin/sh"); + fixture.write(".git/HEAD", "ignored"); + let run = fixture.dir.path().join("run.sh"); + fs::set_permissions(&run, fs::Permissions::from_mode(0o755)).unwrap(); + symlink("src/lib.rs", fixture.dir.path().join("link")).unwrap(); + + let (root, cache) = fixture.snapshot(&StatCache::default()); + let tree = fixture.store.get(root).unwrap(); + let names: Vec<_> = tree.iter().map(|(name, _)| name.as_str()).collect(); + assert_eq!(names, ["link", "run.sh", "src"]); + assert_eq!(fixture.entry(root, "run.sh").kind, EntryKind::Executable); + let link = fixture.entry(root, "link"); + assert_eq!(link.kind, EntryKind::Symlink); + assert_eq!( + fixture.store.read(link.id).unwrap().blob_content().unwrap(), + b"src/lib.rs" + ); + assert_eq!( + fixture.entry(root, "src/lib.rs").id, + EncodedObject::blob(b"lib").id() + ); + assert_eq!(cache.files.len(), 3); + } + + #[test] + fn empty_working_copies_are_empty_trees() { + let fixture = Fixture::new(); + let (root, _) = fixture.snapshot(&StatCache::default()); + assert_eq!(fixture.store.get(root).unwrap(), Tree::default()); + } + + #[test] + fn same_size_rewrites_are_detected() { + let fixture = Fixture::new(); + fixture.write("file", "aaaa"); + let (first, cache) = fixture.snapshot(&StatCache::default()); + // Rewritten right away, possibly within the same mtime tick. + fixture.write("file", "bbbb"); + let (second, _) = fixture.snapshot(&cache); + assert_ne!(first, second); + } + + #[test] + fn restored_modification_times_do_not_hide_changes() { + let fixture = Fixture::new(); + fixture.write("file", "aaaa"); + let path = fixture.dir.path().join("file"); + let mtime = fs::metadata(&path).unwrap().modified().unwrap(); + let (first, mut cache) = fixture.snapshot(&StatCache::default()); + // Trust every entry, as if the file had settled long ago. + cache.scanned_at = i64::MAX; + fixture.write("file", "bbbb"); + File::options() + .write(true) + .open(&path) + .unwrap() + .set_modified(mtime) + .unwrap(); + let (second, _) = fixture.snapshot(&cache); + assert_ne!(first, second); + } + + #[test] + fn cache_hits_skip_reading() { + let fixture = Fixture::new(); + fixture.write("file", "content"); + fixture.write("other", "content"); + let (root, mut cache) = fixture.snapshot(&StatCache::default()); + // Pretend the scan happened long after the write, so the entries are + // trusted, and point one at a different blob: a hit returns the + // cached id without reading the file. + cache.scanned_at = i64::MAX; + cache.root = None; + let fake = EncodedObject::blob(b"cached"); + fixture + .store + .write_all(std::slice::from_ref(&fake)) + .unwrap(); + cache.files.get_mut("file").unwrap().1 = fake.id(); + + let (cached_root, _) = fixture.snapshot(&cache); + assert_ne!(cached_root, root); + assert_eq!(fixture.entry(cached_root, "file").id, fake.id()); + } + + #[test] + fn unchanged_files_reuse_the_cached_root() { + let fixture = Fixture::new(); + fixture.write("file", "content"); + let (root, mut cache) = fixture.snapshot(&StatCache::default()); + cache.scanned_at = i64::MAX; + let worktree = fixture.worktree(); + assert_eq!(worktree.snapshot(&cache).unwrap(), (root, None)); + + fixture.write("other", "new file"); + let (changed, next) = worktree.snapshot(&cache).unwrap(); + assert_ne!(changed, root); + assert_eq!(next.unwrap().root, Some(changed)); + } + + #[test] + fn hashes_many_files_in_parallel() { + let fixture = Fixture::new(); + let count = Worktree::::PARALLEL_THRESHOLD * 2; + for i in 0..count { + fixture.write(&format!("dir{}/file{i}", i % 7), &i.to_string()); + } + let (root, cache) = fixture.snapshot(&StatCache::default()); + assert_eq!(cache.files.len(), count); + assert_eq!( + fixture.entry(root, "dir3/file10").id, + EncodedObject::blob(b"10").id() + ); + } + + #[test] + fn cache_round_trips() { + let fixture = Fixture::new(); + fixture.write("a", "1"); + fixture.write("b/c", "2"); + let (_, cache) = fixture.snapshot(&StatCache::default()); + let path = fixture.dir.path().join(".origin/state"); + cache.save(&path).unwrap(); + assert_eq!(StatCache::load(&path), cache); + assert_eq!( + StatCache::decode(b"garbage"), + Err(DecodeError::NonCanonical("stat cache header")) + ); + } + + #[test] + fn checkouts_reproduce_snapshots() { + let fixture = Fixture::new(); + fixture.write("keep", "same"); + fixture.write("edit", "old"); + fixture.write("gone/deep/file", "removed"); + fixture.write("swap", "a file that becomes a directory"); + fixture.write("dir/inner", "a directory that becomes a file"); + let (old, cache) = fixture.snapshot(&StatCache::default()); + + for path in ["edit", "swap", "gone/deep/file", "dir/inner"] { + fs::remove_file(fixture.dir.path().join(path)).unwrap(); + } + fs::remove_dir_all(fixture.dir.path().join("gone")).unwrap(); + fs::remove_dir(fixture.dir.path().join("dir")).unwrap(); + fixture.write("edit", "new"); + fixture.write("swap/inner", "now inside"); + fixture.write("dir", "now a file"); + fixture.write("run.sh", "#!/bin/sh"); + let run = fixture.dir.path().join("run.sh"); + fs::set_permissions(&run, fs::Permissions::from_mode(0o755)).unwrap(); + symlink("keep", fixture.dir.path().join("link")).unwrap(); + let (new, cache) = fixture.snapshot(&cache); + + // Back to the old snapshot, then forward to the new one. + let worktree = fixture.worktree(); + worktree + .checkout(&fixture.store.diff(new, old).unwrap()) + .unwrap(); + assert!(!fixture.dir.path().join("swap/inner").exists()); + let (back, cache) = fixture.snapshot(&cache); + assert_eq!(back, old); + worktree + .checkout(&fixture.store.diff(old, new).unwrap()) + .unwrap(); + assert!(!fixture.dir.path().join("gone").exists(), "emptied dirs go"); + assert_eq!(fixture.snapshot(&cache).0, new); + } +} diff --git a/apps/origin-src/tests/cli.rs b/apps/origin-src/tests/cli.rs new file mode 100644 index 00000000..7db8cc2c --- /dev/null +++ b/apps/origin-src/tests/cli.rs @@ -0,0 +1,360 @@ +//! End-to-end tests of the change workflow, driving the real `origin` binary. + +use std::fs; +use std::os::unix::fs::PermissionsExt; +use std::path::Path; +use std::process::{Command, Output}; + +/// A temporary working copy, and a user configuration of its own. +struct Repo { + dir: tempfile::TempDir, + config: tempfile::TempDir, +} + +impl Repo { + fn new() -> Self { + let config = tempfile::tempdir().unwrap(); + fs::write(config.path().join("config.toml"), "user = \"ada\"\n").unwrap(); + let repo = Self { + dir: tempfile::tempdir().unwrap(), + config, + }; + repo.ok(&["init"]); + repo + } + + /// Runs `origin` in `cwd` as the configured user. + fn run(&self, cwd: &Path, args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_origin")) + .args(args) + .current_dir(cwd) + .env("ORIGIN_CONFIG_DIR", self.config.path()) + .output() + .unwrap() + } + + /// Runs a command that must succeed, returning its output. + fn ok(&self, args: &[&str]) -> String { + let output = self.run(self.dir.path(), args); + assert!( + output.status.success(), + "`origin {}` failed: {}", + args.join(" "), + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout).unwrap() + } + + /// Runs a command that must fail, returning its error. + fn fails(&self, args: &[&str]) -> String { + let output = self.run(self.dir.path(), args); + assert!( + !output.status.success(), + "`origin {}` succeeded", + args.join(" ") + ); + String::from_utf8(output.stderr).unwrap() + } + + fn path(&self, path: &str) -> std::path::PathBuf { + self.dir.path().join(path) + } + + fn write(&self, path: &str, content: &str) { + let path = self.path(path); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, content).unwrap(); + } + + fn read(&self, path: &str) -> String { + fs::read_to_string(self.path(path)).unwrap() + } + + /// The short id of the working copy's change. + fn change(&self) -> String { + let status = self.ok(&["status"]); + let line = status.lines().next().unwrap(); + let headline = line.strip_prefix("Working copy: ").unwrap(); + headline.split(' ').next().unwrap().to_owned() + } +} + +#[test] +fn the_working_copy_is_a_revision_of_the_current_change() { + let repo = Repo::new(); + let first = repo.change(); + assert_eq!( + repo.ok(&["status"]), + format!("Working copy: {first} (no description)\nOn top of: main #0\nNo changes.\n") + ); + + repo.write("README.md", "hello\n"); + repo.write("src/lib.rs", "fn a() {}\n"); + repo.write("src/old.rs", "old\n"); + repo.ok(&["describe", "Add the library"]); + assert_eq!( + repo.ok(&["status"]), + format!( + "Working copy: {first} Add the library\nOn top of: main #0\n\ + A README.md\nA src/lib.rs\nA src/old.rs\n" + ) + ); + + let new = repo.ok(&["new", "Rework it"]); + let second = repo.change(); + assert_ne!(second, first); + assert_eq!( + new, + format!("Working copy: {second} Rework it\nOn top of: {first} Add the library\n") + ); + repo.write("README.md", "hello, world\n"); + fs::remove_file(repo.path("src/old.rs")).unwrap(); + repo.write("src/new.rs", "new\n"); + assert!( + repo.ok(&["status"]) + .ends_with("M README.md\nA src/new.rs\nD src/old.rs\n") + ); + + let log = repo.ok(&["log"]); + assert!( + log.starts_with(&format!( + "@ {second} Rework it\n○ {first} Add the library\n◆ main #0 " + )), + "{log}" + ); + // Created empty, its draft recorded, described: the first change has + // three revisions, of which the newest is its head. + let evolog = repo.ok(&["evolog", &first]); + let revisions: Vec<_> = evolog.lines().skip(1).collect(); + assert_eq!(revisions.len(), 3, "{evolog}"); + assert!( + revisions[0].ends_with(" Add the library (head)"), + "{evolog}" + ); + assert!(revisions[2].ends_with(" (no description)"), "{evolog}"); +} + +#[test] +fn diff_shows_line_changes() { + let repo = Repo::new(); + repo.write("file.txt", "one\ntwo\nthree\n"); + repo.ok(&["new"]); + repo.write("file.txt", "one\n2\nthree\n"); + repo.write("binary", "\0\u{1}"); + + let diff = repo.ok(&["diff"]); + assert!(diff.contains("Binary file binary differs\n"), "{diff}"); + assert!(diff.contains("--- a/file.txt\n+++ b/file.txt\n"), "{diff}"); + assert!(diff.contains("-two\n+2\n"), "{diff}"); + assert!(repo.ok(&["show"]).ends_with(&diff)); +} + +#[test] +fn only_commands_that_build_on_the_working_copy_record_it() { + let repo = Repo::new(); + let change = repo.change(); + let revisions = || repo.ok(&["evolog", &change]).lines().count() - 1; + repo.write("file", "draft\n"); + + // Reading the working copy shows the draft, and records nothing. + assert!(repo.ok(&["status"]).ends_with("A file\n")); + assert!(repo.ok(&["diff"]).contains("+draft\n")); + assert!(repo.ok(&["show"]).contains(", with unrecorded edits\n")); + assert_eq!(revisions(), 1); + + // Starting the next change records it first. + repo.ok(&["new"]); + assert_eq!(revisions(), 2); + assert!(repo.ok(&["show", &change]).contains("+draft\n")); +} + +#[test] +fn edit_switches_the_files_to_another_change() { + let repo = Repo::new(); + repo.write("shared", "first\n"); + repo.write("run.sh", "#!/bin/sh\n"); + fs::set_permissions(repo.path("run.sh"), fs::Permissions::from_mode(0o755)).unwrap(); + let first = repo.change(); + repo.ok(&["new"]); + let second = repo.change(); + repo.write("shared", "second\n"); + repo.write("dir/added", "added\n"); + fs::remove_file(repo.path("run.sh")).unwrap(); + + // A unique prefix is enough. + repo.ok(&["edit", &first[..6]]); + assert_eq!(repo.read("shared"), "first\n"); + assert!(!repo.path("dir").exists()); + let mode = fs::metadata(repo.path("run.sh")) + .unwrap() + .permissions() + .mode(); + assert_eq!(mode & 0o111, 0o111, "still executable"); + assert!(repo.ok(&["status"]).ends_with("A run.sh\nA shared\n")); + + repo.ok(&["edit", &second]); + assert_eq!(repo.read("dir/added"), "added\n"); + assert!(!repo.path("run.sh").exists()); + assert!( + repo.ok(&["status"]) + .ends_with("A dir/added\nD run.sh\nM shared\n") + ); + assert!(repo.fails(&["edit", "zz"]).contains("is not a change id")); +} + +#[test] +fn divergence_shows_until_converged() { + let repo = Repo::new(); + repo.write("file", "base\n"); + repo.ok(&["describe", "Shared work"]); + let change = repo.change(); + // Two agents revise the same revision: one, then the other from the + // revision the first started from. + let pointer = repo.path(".origin/workspace"); + let started = fs::read_to_string(&pointer).unwrap(); + repo.write("file", "left\n"); + repo.ok(&["describe", "Shared work"]); + fs::write(&pointer, started).unwrap(); + repo.write("file", "right\n"); + repo.ok(&["describe", "Shared work"]); + + let status = repo.ok(&["status"]); + assert!( + status.starts_with(&format!("Working copy: {change} Shared work (divergent)\n")), + "{status}" + ); + assert!( + status.contains(&format!("Run `origin converge {change}`")), + "{status}" + ); + assert!( + repo.ok(&["log"]) + .starts_with(&format!("@ {change} Shared work (divergent)\n")) + ); + assert!(repo.fails(&["edit", &change]).contains("is divergent")); + assert_eq!(repo.ok(&["show", &change]).matches("Revision ").count(), 2); + + let converged = repo.ok(&["converge", &change]); + assert!( + converged.starts_with(&format!("Converged change {change}")), + "{converged}" + ); + assert_eq!( + repo.read("file"), + "right\n", + "the working copy's files are kept" + ); + assert!(!repo.ok(&["status"]).contains("divergent")); + assert!(repo.ok(&["evolog"]).contains(" converges ")); + assert!( + repo.fails(&["converge", &change]) + .contains("is not divergent") + ); +} + +#[test] +fn abandoning_the_current_change_restores_its_base() { + let repo = Repo::new(); + repo.write("kept", "kept\n"); + repo.ok(&["new", "Try a cache"]); + let abandoned = repo.change(); + repo.write("kept", "changed\n"); + repo.write("cache.rs", "cache\n"); + + let output = repo.ok(&["abandon", "--reason", "Too slow"]); + assert!( + output.starts_with(&format!("Abandoned change {abandoned}\n")), + "{output}" + ); + assert_eq!(repo.read("kept"), "kept\n"); + assert!(!repo.path("cache.rs").exists()); + assert_ne!(repo.change(), abandoned); + assert!(repo.ok(&["status"]).ends_with("No changes.\n")); + + let show = repo.ok(&["show", &abandoned]); + assert!(show.contains(" (abandoned)\n"), "{show}"); + assert!(show.contains("Abandoned by user:ada: Too slow\n"), "{show}"); + assert!(show.contains("+cache\n"), "the attempt is kept: {show}"); +} + +#[test] +fn init_with_a_malformed_key_leaves_no_repository() { + let repo = Repo::new(); + fs::write(repo.config.path().join("node.key"), b"short").unwrap(); + let other = tempfile::tempdir().unwrap(); + assert!(!repo.run(other.path(), &["init"]).status.success()); + assert!(!other.path().join(".origin").exists()); +} + +#[test] +fn init_creates_policy_and_main_with_one_node_key() { + let repo = Repo::new(); + let policy = repo.ok(&["log", "policy"]); + assert!(policy.starts_with("◆ policy #0 "), "{policy}"); + assert_eq!(policy.lines().count(), 1, "the stack is on main: {policy}"); + assert!( + repo.fails(&["log", "nope"]) + .contains("no target is named `nope`") + ); + assert!(repo.fails(&["init"]).contains("already has a repository")); + + let key = repo.config.path().join("node.key"); + let mode = fs::metadata(&key).unwrap().permissions().mode(); + assert_eq!(mode & 0o777, 0o600); + let before = fs::read(&key).unwrap(); + let other = tempfile::tempdir().unwrap(); + assert!(repo.run(other.path(), &["init"]).status.success()); + assert_eq!( + fs::read(&key).unwrap(), + before, + "every repository shares it" + ); +} + +#[test] +fn a_lost_index_is_rebuilt() { + let repo = Repo::new(); + repo.write("file", "content\n"); + let change = repo.change(); + repo.ok(&["new"]); + fs::remove_file(repo.path(".origin/index/log")).unwrap(); + assert_eq!(repo.ok(&["evolog", &change]).lines().count(), 3); + assert!( + repo.ok(&["index", "rebuild"]) + .starts_with("Rebuilt the index of ") + ); +} + +#[test] +fn commands_find_the_repository_from_subdirectories() { + let repo = Repo::new(); + repo.write("deep/nested/file", "content"); + let output = repo.run(&repo.path("deep/nested"), &["status"]); + let status = String::from_utf8(output.stdout).unwrap(); + assert!(status.ends_with("A deep/nested/file\n"), "{status}"); +} + +#[test] +fn commands_outside_a_repository_fail() { + let repo = Repo::new(); + let outside = tempfile::tempdir().unwrap(); + let output = repo.run(outside.path(), &["status"]); + assert!(!output.status.success()); + assert!(String::from_utf8_lossy(&output.stderr).contains("not in an origin repository")); +} + +#[test] +fn a_closed_output_pipe_ends_quietly() { + let repo = Repo::new(); + let (reader, writer) = std::io::pipe().unwrap(); + drop(reader); + let output = Command::new(env!("CARGO_BIN_EXE_origin")) + .arg("status") + .current_dir(repo.dir.path()) + .env("ORIGIN_CONFIG_DIR", repo.config.path()) + .stdout(writer) + .output() + .unwrap(); + assert!(output.status.success(), "{output:?}"); + assert_eq!(String::from_utf8_lossy(&output.stderr), ""); +} diff --git a/crates/origin-shared/src/id.rs b/crates/origin-shared/src/id.rs index 1bcfec31..6cd50313 100644 --- a/crates/origin-shared/src/id.rs +++ b/crates/origin-shared/src/id.rs @@ -29,9 +29,7 @@ macro_rules! ids { /// The full id as lowercase hex. #[must_use] pub fn to_hex(&self) -> String { - let mut hex = [0; 2 * $len]; - hex::encode(&self.0, &mut hex); - String::from_utf8(hex.to_vec()).expect("hex digits are ASCII") + hex::string(&self.0) } /// An abbreviated id for display to humans. @@ -192,13 +190,20 @@ pub struct ParseIdError { pub input: String, } -/// Lowercase hex, without allocating. -mod hex { +/// Lowercase hex. +pub(crate) mod hex { const DIGITS: &[u8; 16] = b"0123456789abcdef"; /// Number of hex digits a short id has. pub const SHORT_LEN: usize = 12; + /// `bytes` as a string of lowercase hex. + pub fn string(bytes: &[u8]) -> String { + let mut hex = vec![0; 2 * bytes.len()]; + encode(bytes, &mut hex); + String::from_utf8(hex).expect("hex digits are ASCII") + } + /// Writes the two digits of each byte of `bytes` to `out`, which is /// twice as long. pub fn encode(bytes: &[u8], out: &mut [u8]) { diff --git a/crates/origin-shared/src/object/acceptance.rs b/crates/origin-shared/src/object/acceptance.rs index cdf06afb..95ef6464 100644 --- a/crates/origin-shared/src/object/acceptance.rs +++ b/crates/origin-shared/src/object/acceptance.rs @@ -3,6 +3,7 @@ use std::fmt; use ed25519_dalek::{Signer, SigningKey, VerifyingKey}; use super::{DecodeError, Field, ObjectKind, Reader, Record, fields, tagged}; +use crate::id::hex; use crate::{AcceptanceId, RevisionId, StatementId, TargetId, TreeId}; pub use ed25519_dalek::Signature; @@ -147,6 +148,12 @@ impl NodeKey { Self(SigningKey::from_bytes(secret)) } + /// The secret key, to keep the key pair somewhere safe. + #[must_use] + pub fn to_bytes(&self) -> [u8; ed25519_dalek::SECRET_KEY_LENGTH] { + self.0.to_bytes() + } + /// The public half, which verifies the node's signatures. #[must_use] pub fn public(&self) -> NodePublicKey { @@ -161,10 +168,16 @@ impl fmt::Debug for NodeKey { } } -/// A node's public key. +/// A node's public key, displayed as lowercase hex. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct NodePublicKey(VerifyingKey); +impl fmt::Display for NodePublicKey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&hex::string(self.0.as_bytes())) + } +} + /// A signature that the claimed signer did not make. #[derive(Debug, thiserror::Error)] #[error("the signature does not match the signer's key")] diff --git a/crates/origin-shared/src/object/tree.rs b/crates/origin-shared/src/object/tree.rs index 08762172..5a1ea5f6 100644 --- a/crates/origin-shared/src/object/tree.rs +++ b/crates/origin-shared/src/object/tree.rs @@ -1,9 +1,10 @@ use std::collections::BTreeMap; use std::collections::btree_map; +use std::fmt; use super::{DecodeError, Field, ObjectKind, Reader, Record}; -use crate::ObjectId; use crate::name::names; +use crate::{ObjectId, TreeId}; names! { /// The name of an entry in a tree: one path component. It isn't empty, @@ -21,9 +22,16 @@ impl EntryName { && name != "." && name != ".." && !name.contains(['/', '\0']) - && !Self::RESERVED - .iter() - .any(|reserved| name.eq_ignore_ascii_case(reserved)) + && !Self::is_reserved(name) + } + + /// Whether a name belongs to repository metadata, which working copies + /// skip and trees cannot contain. + #[must_use] + pub fn is_reserved(name: &str) -> bool { + Self::RESERVED + .iter() + .any(|reserved| name.eq_ignore_ascii_case(reserved)) } } @@ -42,7 +50,12 @@ pub enum EntryKind { } impl EntryKind { - fn from_byte(tag: u8) -> Result { + /// The kind a tag byte encodes, as in tree encodings. + /// + /// # Errors + /// + /// Fails if the byte encodes no kind. + pub fn from_byte(tag: u8) -> Result { match tag { 1 => Ok(Self::File), 2 => Ok(Self::Executable), @@ -62,6 +75,17 @@ impl EntryKind { } } +impl fmt::Display for EntryKind { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::File => "file", + Self::Executable => "executable", + Self::Symlink => "symlink", + Self::Tree => "directory", + }) + } +} + /// One entry of a tree. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct TreeEntry { @@ -71,6 +95,20 @@ pub struct TreeEntry { pub id: ObjectId, } +impl TreeEntry { + /// The entry, if it is a file (regular, executable or symlink). + #[must_use] + pub fn file(self) -> Option { + (!self.kind.is_tree()).then_some(self) + } + + /// The tree the entry points to, if it is a directory. + #[must_use] + pub fn subtree(self) -> Option { + self.kind.is_tree().then_some(self.id.into()) + } +} + /// A directory listing, sorted by name. /// /// Encoded as its entries in order, each `kind:u8 name 0x00 id:[u8; 32]`, diff --git a/docs/benchmarks.md b/docs/benchmarks.md new file mode 100644 index 00000000..a4c6a1d3 --- /dev/null +++ b/docs/benchmarks.md @@ -0,0 +1,38 @@ +# Benchmarks: origin vs git + +Generated by `just bench-git` on a synthetic tree of 20000 files. + +- CPU: AMD Ryzen 7 5700G with Radeon Graphics +- git version 2.55.0 + +## First commit of the whole tree (`origin new`) + +| Command | Mean Wall Time [ms] | Change | Factor | +|:---|---:|---:|:---| +| `origin` | 398.8 ± 16.7 | | | +| `git` | 1471.4 ± 24.3 | +269.0% | (3.7x slower) | + + +## Status, nothing changed + +| Command | Mean Wall Time [ms] | Change | Factor | +|:---|---:|---:|:---| +| `origin` | 31.2 ± 8.6 | | | +| `git` | 23.0 ± 1.0 | -26.4% | | + + +## Status, 100 files edited + +| Command | Mean Wall Time [ms] | Change | Factor | +|:---|---:|---:|:---| +| `origin` | 71.5 ± 2.6 | | | +| `git` | 24.3 ± 1.2 | -66.1% | (2.9x faster) | + + +## Commit, 100 files edited (`origin new`) + +| Command | Mean Wall Time [ms] | Change | Factor | +|:---|---:|---:|:---| +| `origin` | 74.4 ± 3.2 | | | +| `git` | 65.3 ± 1.6 | -12.3% | | + diff --git a/justfile b/justfile index f36de0df..dd2d87fa 100644 --- a/justfile +++ b/justfile @@ -28,6 +28,12 @@ doc-test: deny: @cargo deny check -# Micro-benchmarks of the hot paths (hashing, storage). +# Micro-benchmarks of the hot paths (hashing, storage, snapshots). bench *ARGS: @cargo bench --locked --workspace -- {{ARGS}} + +# Times origin against git with hyperfine, which must be installed, and +# rewrites docs/benchmarks.md. +# Pass `--tree PATH` to benchmark a copy of a real working tree. +bench-git *ARGS: + @cargo xtask bench-git {{ARGS}} diff --git a/tools/xtask/Cargo.toml b/tools/xtask/Cargo.toml new file mode 100644 index 00000000..f93a0d73 --- /dev/null +++ b/tools/xtask/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "xtask" +description = "Development tasks for the origin workspace" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish = false + +[dependencies] +anyhow.workspace = true +origin-src = { workspace = true, features = ["fixture"] } + +[lints] +workspace = true diff --git a/tools/xtask/src/main.rs b/tools/xtask/src/main.rs new file mode 100644 index 00000000..99c27f8f --- /dev/null +++ b/tools/xtask/src/main.rs @@ -0,0 +1,282 @@ +//! Development tasks, run with `cargo xtask `: +//! +//! - `bench-git [--files N] [--tree PATH]`: times origin against git on the +//! same working tree with hyperfine, and writes `docs/benchmarks.md`. The +//! tree is a synthetic fixture of N files, or a copy of PATH. +//! - `edit DIR COUNT`: appends a line to COUNT files spread across DIR. The +//! benchmarks use it to change files between runs. + +use std::fmt::Write as _; +use std::fs::{self, OpenOptions}; +use std::io::{self, Write as _}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::time::{SystemTime, UNIX_EPOCH}; +use std::{env, iter}; + +use anyhow::{Context, Result, bail, ensure}; +use origin_src::fixture::FixtureTree; + +fn main() -> Result<()> { + let mut args = env::args().skip(1); + match args.next().as_deref() { + Some("bench-git") => BenchGit::parse(args)?.run(), + Some("edit") => { + let (Some(dir), Some(count)) = (args.next(), args.next()) else { + bail!("usage: cargo xtask edit DIR COUNT"); + }; + edit( + Path::new(&dir), + count.parse().context("COUNT must be a number")?, + ) + } + _ => bail!("usage: cargo xtask "), + } +} + +/// Appends a line to `count` files spread evenly across `dir`, so that both +/// tools see real content changes. +fn edit(dir: &Path, count: usize) -> Result<()> { + fn walk(dir: &Path, files: &mut Vec) -> Result<()> { + let mut entries = fs::read_dir(dir)?.collect::, _>>()?; + entries.sort_by_key(fs::DirEntry::file_name); + for entry in entries { + let name = entry.file_name(); + if name == ".git" || name == ".origin" { + continue; + } + let file_type = entry.file_type()?; + if file_type.is_dir() { + walk(&entry.path(), files)?; + } else if file_type.is_file() { + files.push(entry.path()); + } + } + Ok(()) + } + + let mut files = Vec::new(); + walk(dir, &mut files)?; + let step = (files.len() / count.max(1)).max(1); + let stamp = SystemTime::now().duration_since(UNIX_EPOCH)?.as_nanos(); + for file in files.iter().step_by(step).take(count) { + let mut file = OpenOptions::new().append(true).open(file)?; + writeln!(file, "// edited {stamp}")?; + } + Ok(()) +} + +/// Times origin against git with hyperfine. +struct BenchGit { + files: usize, + tree: Option, +} + +impl BenchGit { + /// `path` as one `sh` word, whatever it holds: single-quoted, with each + /// `'` closing the quote, escaped, and reopening it. + fn quote(path: &Path) -> String { + format!("'{}'", path.display().to_string().replace('\'', "'\\''")) + } + + fn parse(mut args: impl Iterator) -> Result { + let mut task = Self { + files: FixtureTree::LARGE.files, + tree: None, + }; + while let Some(arg) = args.next() { + let mut value = || args.next().with_context(|| format!("{arg} needs a value")); + match arg.as_str() { + "--files" => task.files = value()?.parse().context("--files must be a number")?, + "--tree" => task.tree = Some(value()?.into()), + _ => bail!("unknown option {arg}, expected --files N or --tree PATH"), + } + } + Ok(task) + } + + fn run(&self) -> Result<()> { + // Fail before the slow build and setup if hyperfine is missing. + run(Command::new("hyperfine") + .arg("--version") + .stdout(Stdio::null()))?; + let workspace = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + run(Command::new(env!("CARGO")) + .args([ + "build", + "--release", + "--package", + "origin-src", + "--bin", + "origin", + ]) + .current_dir(&workspace))?; + // Cargo resolves a relative target directory from where it runs. + let target = workspace.join(env::var_os("CARGO_TARGET_DIR").unwrap_or("target".into())); + let origin = target.join("release/origin").canonicalize()?; + let xtask = env::current_exe()?; + + let base = target.join("bench-git"); + if base.exists() { + fs::remove_dir_all(&base)?; + } + let config = base.join("config"); + fs::create_dir_all(&config)?; + fs::write(config.join("config.toml"), "user = \"bench\"\n")?; + let (origin_dir, git_dir) = (base.join("origin"), base.join("git")); + for dir in [&origin_dir, &git_dir] { + self.populate(dir)?; + } + let (origin_dir, git_dir) = (origin_dir.canonicalize()?, git_dir.canonicalize()?); + let shell = |dir: &Path, command: &str| format!("cd {} && {command}", Self::quote(dir)); + let origin_cmd = + |command: &str| shell(&origin_dir, &format!("{} {command}", Self::quote(&origin))); + let git_cmd = |command: &str| shell(&git_dir, command); + let edit_cmd = + |dir: &Path| format!("{} edit {} 100", Self::quote(&xtask), Self::quote(dir)); + + let mut report = self.report_header()?; + let mut scenario = |title: &str, + runs: &[&str], + origin: (Option, String), + git: (Option, String)| { + let markdown = base.join("scenario.md"); + let mut hyperfine = Command::new("hyperfine"); + // The commands are shell syntax, which hyperfine 2 makes explicit. + hyperfine + .args(runs) + .arg("--shell=sh") + .arg("--export-markdown") + .arg(&markdown); + for (name, (prepare, command)) in [("origin", origin), ("git", git)] { + if let Some(prepare) = prepare { + hyperfine.arg("--prepare").arg(prepare); + } + hyperfine.arg("--command-name").arg(name).arg(command); + } + run(hyperfine + .envs(Self::environment()) + .env("ORIGIN_CONFIG_DIR", &config))?; + writeln!(report, "\n## {title}\n\n{}", fs::read_to_string(&markdown)?)?; + anyhow::Ok(()) + }; + + // Origin has no commit: `new` records the working copy into the + // current change and starts the next one, the closest operation. + scenario( + "First commit of the whole tree (`origin new`)", + &["--runs", "5"], + ( + Some(shell( + &origin_dir, + &format!("rm -rf .origin && {} init", Self::quote(&origin)), + )), + origin_cmd("new bench"), + ), + ( + Some(git_cmd("rm -rf .git && git init -q")), + git_cmd("git add -A && git commit -qm bench"), + ), + )?; + scenario( + "Status, nothing changed", + &["--warmup", "3"], + (None, origin_cmd("status")), + (None, git_cmd("git status --porcelain")), + )?; + scenario( + "Status, 100 files edited", + &["--warmup", "1"], + (Some(edit_cmd(&origin_dir)), origin_cmd("status")), + (Some(edit_cmd(&git_dir)), git_cmd("git status --porcelain")), + )?; + scenario( + "Commit, 100 files edited (`origin new`)", + &["--warmup", "1"], + (Some(edit_cmd(&origin_dir)), origin_cmd("new bench")), + ( + Some(edit_cmd(&git_dir)), + git_cmd("git add -A && git commit -qm bench"), + ), + )?; + + let path = workspace.join("docs/benchmarks.md"); + fs::create_dir_all(path.parent().context("docs has a parent")?)?; + fs::write(&path, report)?; + println!("Wrote {}", path.canonicalize()?.display()); + Ok(()) + } + + /// Fills `dir` with the working tree under test. + fn populate(&self, dir: &Path) -> Result<()> { + fs::create_dir_all(dir)?; + match &self.tree { + Some(tree) => { + run(Command::new("cp").arg("-a").arg(tree.join(".")).arg(dir))?; + for metadata in [".git", ".origin"] { + let path = dir.join(metadata); + if path.exists() { + fs::remove_dir_all(path)?; + } + } + } + None => FixtureTree { + files: self.files, + ..FixtureTree::LARGE + } + .write(dir)?, + } + Ok(()) + } + + /// A git identity, and no user git configuration (hooks, fsmonitor) + /// skewing results. Origin's identity is in its configuration directory. + fn environment() -> impl Iterator { + iter::empty() + .chain([ + ("GIT_AUTHOR_NAME", "Bench"), + ("GIT_AUTHOR_EMAIL", "bench@example.com"), + ]) + .chain([ + ("GIT_COMMITTER_NAME", "Bench"), + ("GIT_COMMITTER_EMAIL", "bench@example.com"), + ]) + .chain([ + ("GIT_CONFIG_GLOBAL", "/dev/null"), + ("GIT_CONFIG_NOSYSTEM", "1"), + ]) + } + + fn report_header(&self) -> Result { + let cpu = fs::read_to_string("/proc/cpuinfo") + .ok() + .and_then(|info| { + info.lines() + .find_map(|line| line.strip_prefix("model name")) + .map(|name| name.trim_start_matches([' ', '\t', ':']).to_owned()) + }) + .unwrap_or_else(|| "unknown".to_owned()); + let git = String::from_utf8(Command::new("git").arg("--version").output()?.stdout)?; + let tree = match &self.tree { + Some(tree) => format!("a copy of `{}`", tree.display()), + None => format!("a synthetic tree of {} files", self.files), + }; + Ok(format!( + "# Benchmarks: origin vs git\n\n\ + Generated by `just bench-git` on {tree}.\n\n\ + - CPU: {cpu}\n- {}\n", + git.trim() + )) + } +} + +fn run(command: &mut Command) -> Result<()> { + let status = match command.status() { + Err(error) if error.kind() == io::ErrorKind::NotFound => { + bail!("{} is not installed", command.get_program().display()) + } + status => status.with_context(|| format!("cannot run {command:?}"))?, + }; + ensure!(status.success(), "{command:?} failed with {status}"); + Ok(()) +}