diff --git a/apps/origin-src/src/cli.rs b/apps/origin-src/src/cli.rs index 0418f2f8..b175673b 100644 --- a/apps/origin-src/src/cli.rs +++ b/apps/origin-src/src/cli.rs @@ -1,5 +1,5 @@ -//! The `origin` command line: argument parsing. The commands themselves are -//! methods of [`Workspace`], which print their output. +//! The `origin` command line: parses the arguments and runs the command. +//! Each command is a method of [`Workspace`], which prints its output. use std::convert::Infallible; use std::env; @@ -26,7 +26,7 @@ pub struct Cli { enum Command { /// Create a repository, with the targets `policy` and `main`. Init { - /// Where to create it. + /// The directory to create it in. #[arg(default_value = ".")] path: PathBuf, }, @@ -34,16 +34,16 @@ enum Command { 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. +/// Commands that run in the repository containing the current directory. +/// Commands that read the working copy snapshot it first. A change is +/// named by a unique prefix of its id, or by `@` 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 a change and its diff (the working copy's change by default). Show { /// The change. change: Option, @@ -54,7 +54,7 @@ enum WorkspaceCommand { #[arg(default_value = "")] description: String, }, - /// Describe what the current change is for. + /// Set the description of the current change. Describe { /// The description. description: String, @@ -64,16 +64,17 @@ enum WorkspaceCommand { /// The change. change: String, }, - /// Give a change up, keeping it and the reason for others to see. + /// Abandon a change, recording why. The change stays visible to others. Abandon { - /// The change: the working copy's by default, which then starts a - /// new change where it started. + /// The change (the working copy's by default). Abandoning the working + /// copy's change starts a new change on the same base. change: Option, - /// Why it was given up. + /// Why the change was abandoned. #[arg(long)] reason: String, }, - /// End a change's divergence, with a revision evolving from every head. + /// End a change's divergence with a new revision that evolves from all + /// its heads. Converge { /// The change. change: String, @@ -84,7 +85,8 @@ enum WorkspaceCommand { #[arg(required = true)] paths: Vec, }, - /// Show the working copy's changes and the target they're on. + /// Show the working copy's stack of changes and the history of the + /// target it's on. Log { /// Show this target's history instead. target: Option, @@ -103,8 +105,9 @@ enum WorkspaceCommand { Index(IndexCommand), /// Issue a statement about a revision, such as a check result or a /// review, or with `--on`, about another statement, such as a `flaky` - /// mark on a failed check, superseding your previous one of the same - /// kind about it, or withdraw that one. + /// mark on a failed check. It supersedes your previous statement of the + /// same kind about the same subject. `--withdraw` takes that one back + /// instead. #[command( override_usage = "origin annotate [OPTIONS] <--pass|--fail|--neutral|--withdraw> \ \n origin annotate [OPTIONS] \ @@ -118,8 +121,7 @@ enum WorkspaceCommand { #[arg(default_value = "@")] rev: String, }, - /// Carry results over to a revision from the records with the same - /// input digest. + /// Copy results to a revision from records with the same input digest. Promote { /// The revision: `@`, a change for its head, or a revision. #[arg(default_value = "@")] @@ -129,16 +131,17 @@ enum WorkspaceCommand { #[derive(Debug, Args)] struct AnnotateArgs { - /// The revision, `@`, a change for its head, or a revision; with - /// `--on`, the kind instead. + /// The revision (`@`, a change for its head, or a revision), or with + /// `--on`, the kind. #[arg(value_name = "REV|KIND")] first: String, - /// What kind of statement, such as `ci.test` or `review`, after a - /// revision. + /// The kind of statement, such as `ci.test` or `review`, when the first + /// argument is a revision. #[arg(value_name = "KIND")] kind: Option, - /// The statement it's about instead of a revision, by a unique prefix - /// of its id. It's never promoted, so it declares no inputs. + /// The statement to annotate instead of a revision, by a unique prefix + /// of its id. A statement about a statement is never promoted, so it + /// takes no inputs. #[arg( long, value_name = "STATEMENT", @@ -147,27 +150,26 @@ struct AnnotateArgs { on: Option, #[command(flatten)] verdict: VerdictArgs, - /// Instead of a verdict, take back your current statement of this kind - /// about the revision or statement: the details may say why. + /// Take back your current statement of this kind about the subject + /// instead of giving a verdict. The details may say why. #[arg( long, group = "VerdictArgs", conflicts_with_all = ["inputs", "definition", "toolchain", "external"] )] withdraw: bool, - /// The files and directories the claim depended on, which lets it be - /// promoted to revisions where they're the same. + /// The files and directories the result depended on. The statement can + /// then be promoted to revisions where they are the same. #[arg(long, num_args = 1..)] inputs: Vec, - /// The check's command and configuration: text, or the hex digest of - /// it. + /// The check's command and configuration, as text or as its hex digest. #[arg(long, requires = "inputs")] definition: Option, - /// The tools that ran it, such as the output of `rustc -V`: text, or the - /// hex digest of it. + /// The tools that ran the check, such as the output of `rustc -V`, as + /// text or as its hex digest. #[arg(long, requires = "inputs")] toolchain: Option, - /// The claim also depended on things outside the inputs, such as the + /// The result also depended on things outside the inputs, such as the /// network, so it is never promoted. #[arg(long, requires = "inputs")] external: bool, @@ -175,14 +177,14 @@ struct AnnotateArgs { payload: PayloadArgs, } -/// At most one source of details. +/// The statement's details, from at most one source. #[derive(Debug, Args)] #[group(multiple = false)] struct PayloadArgs { /// Details as text, such as a review's message. #[arg(short, long)] message: Option, - /// A file holding details, such as a log, or `-` to read them from + /// A file holding the details, such as a log, or `-` to read them from /// standard input. #[arg(long)] payload: Option, @@ -195,7 +197,7 @@ impl PayloadArgs { } } -/// Exactly one verdict. +/// The statement's verdict: exactly one is required. #[derive(Debug, Args)] #[group(required = true, multiple = false)] struct VerdictArgs { @@ -205,7 +207,7 @@ struct VerdictArgs { /// The check failed, or you object. #[arg(long)] fail: bool, - /// Neither: informational. + /// Neither: the statement is informational. #[arg(long)] neutral: bool, } @@ -221,13 +223,13 @@ impl VerdictArgs { } impl AnnotateArgs { - /// What the statement is about, and its kind: the revision, then the - /// kind, or with `--on`, the kind alone. + /// Returns what the statement is about and its kind. Without `--on`, the + /// arguments are the revision, then the kind; with `--on`, just the kind. /// /// # Errors /// - /// Fails, as parsing does, if the arguments aren't one of those, or the - /// kind isn't a valid one. + /// Returns a clap error if the arguments match neither form, or the kind + /// is invalid. fn subject(&self) -> Result<(Annotated<'_>, Kind), clap::Error> { let (annotated, kind) = match (&self.on, &self.kind) { (Some(on), None) => (Annotated::Statement(on), &self.first), @@ -251,13 +253,13 @@ impl AnnotateArgs { Ok((annotated, kind)) } - /// The verdict, or `None` to withdraw. + /// The verdict, or `None` for `--withdraw`. fn verdict(&self) -> Option { (!self.withdraw).then(|| self.verdict.verdict()) } - /// The inputs declared, if any. Without a definition or toolchain, they - /// are the digest of nothing. + /// The declared inputs, or `None` without `--inputs`. A missing + /// definition or toolchain is the digest of empty input. fn inputs(&self) -> Option { let digest = |arg: &Option| arg.map_or_else(|| Digest::of(b""), |arg| arg.0); (!self.inputs.is_empty()).then(|| Inputs { @@ -269,7 +271,8 @@ impl AnnotateArgs { } } -/// A digest given as its hex, or as the text it's the digest of. +/// A digest argument: valid hex is parsed as a digest, and any other +/// text is hashed. #[derive(Clone, Copy, Debug)] struct DigestArg(Digest); @@ -290,13 +293,13 @@ enum IndexCommand { } impl Cli { - /// Parses the command line, then checks what parsing can't: an - /// `annotate`'s arguments, whose meaning depends on `--on`. Exits as a - /// parse error does on either, with the usage. + /// Parses the command line, then checks the `annotate` arguments, which + /// clap can't check because their meaning depends on `--on`. On an + /// error, prints it with the usage and exits, as clap does. /// /// # Panics /// - /// Never: `annotate` is a subcommand. + /// Never: `annotate` is always a subcommand. #[must_use] pub fn parse_checked() -> Self { let cli = Self::parse(); @@ -316,7 +319,8 @@ impl Cli { /// /// # Errors /// - /// Fails if the command fails; the error is meant for the user. + /// Fails if the configuration cannot be loaded or the command fails. The + /// error is meant for the user. pub fn run(self) -> Result<()> { let config = UserConfig::load()?; match self.command { diff --git a/apps/origin-src/src/config.rs b/apps/origin-src/src/config.rs index b88ced74..f8db82f5 100644 --- a/apps/origin-src/src/config.rs +++ b/apps/origin-src/src/config.rs @@ -1,12 +1,12 @@ -//! The user's configuration, kept outside every repository in -//! `$ORIGIN_CONFIG_DIR`, or else `origin` in `$XDG_CONFIG_HOME` or -//! `~/.config`: +//! The user's configuration. It lives outside every repository, in +//! `$ORIGIN_CONFIG_DIR`, or else in `origin` under `$XDG_CONFIG_HOME` or +//! `~/.config`. It holds: //! -//! - `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. +//! - `config.toml`: `user = "alice"`, the user who authors revisions +//! (`$USER` by default), and `node = "laptop"`, this node's name (the +//! user name by default). +//! - `node.key`: this node's secret ed25519 key. The first `origin init` +//! creates it, readable only by its owner. use std::env; use std::fs::{self, OpenOptions}; @@ -27,7 +27,7 @@ pub struct UserConfig { node: PrincipalName, } -/// `config.toml`. +/// The contents of `config.toml`. #[derive(Debug, Default, Deserialize)] #[serde(deny_unknown_fields)] struct ConfigFile { @@ -36,7 +36,7 @@ struct ConfigFile { } impl UserConfig { - /// The length of `node.key`: the raw secret key. + /// The length of `node.key`, which holds the raw secret key. const KEY_LEN: usize = 32; /// Loads the configuration from its directory. @@ -95,12 +95,13 @@ impl UserConfig { self.dir.join("node.key") } - /// This node's key, generated and saved durably the first time. + /// Returns this node's key, generating it and saving it durably the + /// first time. /// /// # Errors /// - /// Fails if the key cannot be read, is malformed, or cannot be - /// generated and saved. + /// 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 => { @@ -122,9 +123,9 @@ impl UserConfig { 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. + /// Generates a key and saves it. The key is written and synced under a + /// temporary name, then linked into place. If another process saved a + /// key first, the link fails and that key is returned instead. fn create_key(&self) -> Result { let io_error = |path: &Path| { let path = path.to_owned(); @@ -213,10 +214,10 @@ pub enum ConfigError { /// What is wrong. source: InvalidName, }, - /// `node.key` isn't a key. + /// `node.key` doesn't hold a valid key. #[error("{} is not a node key", .0.display())] MalformedKey(PathBuf), - /// The operating system has no randomness to generate a key with. + /// The operating system cannot supply randomness to generate a key. #[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 index 9be4ccb7..f1d812c4 100644 --- a/apps/origin-src/src/fixture.rs +++ b/apps/origin-src/src/fixture.rs @@ -1,23 +1,25 @@ -//! Deterministic synthetic working trees, for benchmarks and tests. The same -//! shape always produces byte-identical files, so results are comparable -//! across runs and machines. +//! 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. +//! Only built with the `fixture` feature, so the `origin` binary doesn't +//! include it. 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. +/// The shape of a synthetic tree: `files` files of about `file_size` +/// bytes each, `files_per_dir` per directory, in directories nested two +/// levels deep. #[derive(Clone, Copy, Debug)] pub struct FixtureTree { - /// Number of files. + /// The number of files. pub files: usize, - /// Files in each directory. + /// The number of files in each directory. pub files_per_dir: usize, - /// Approximate size of each file in bytes. + /// The approximate size of each file, in bytes. pub file_size: usize, } @@ -38,7 +40,8 @@ impl FixtureTree { self.dir(root, index).join(format!("file{index}.rs")) } - /// Source-code-like content: unique per file and per `version`. + /// Returns source-code-like content for file `index`, different for each + /// file and each `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); @@ -74,8 +77,8 @@ impl FixtureTree { Ok(()) } - /// Rewrites `count` files spread across the tree with new content, - /// numbered by `version` so successive edits differ. + /// Rewrites `count` files, spread across the tree, with new content for + /// `version`, so successive edits differ. /// /// # Errors /// diff --git a/apps/origin-src/src/lib.rs b/apps/origin-src/src/lib.rs index f00f28fc..2639db29 100644 --- a/apps/origin-src/src/lib.rs +++ b/apps/origin-src/src/lib.rs @@ -1,5 +1,5 @@ -//! The origin command line and server. Both share the repository logic in -//! this library; `main.rs` only parses arguments and dispatches. +//! The origin command line and server. Both use the repository logic in +//! this library; `main.rs` only parses arguments and runs the command. pub mod ancestry; pub mod annotations; diff --git a/apps/origin-src/src/output.rs b/apps/origin-src/src/output.rs index dea01e86..3fec1693 100644 --- a/apps/origin-src/src/output.rs +++ b/apps/origin-src/src/output.rs @@ -1,4 +1,5 @@ -//! How commands present what they print. +//! Helpers for what commands print: file diffs, and exiting quietly when +//! standard output is closed. use std::fmt; use std::io; @@ -12,15 +13,15 @@ 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. +/// The `EPIPE` error code, returned when 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. +/// Makes the process exit quietly, with success, when the reader of its +/// standard output closes it, as in `origin log | head`. Without this, +/// `println!` panics, because Rust ignores `SIGPIPE`. Records are written +/// to survive a crash, so exiting mid-command is safe. Other panics are +/// reported as usual. pub fn exit_quietly_on_broken_pipe() { let report = panic::take_hook(); let broken = format!( @@ -43,7 +44,7 @@ pub struct FileDiff<'a> { } impl<'a> FileDiff<'a> { - /// Reads both sides of a change. + /// Reads both sides of `change`. /// /// # Errors /// @@ -67,8 +68,8 @@ impl<'a> FileDiff<'a> { }) } - /// The content as text, or `None` if it is binary: not valid UTF-8, or - /// holding a NUL byte, which text never contains. + /// Returns the content as text, or `None` if it is binary: not valid + /// UTF-8, or containing a NUL byte. fn text(content: &[u8]) -> Option<&str> { str::from_utf8(content) .ok() diff --git a/apps/origin-src/src/workspace/annotate.rs b/apps/origin-src/src/workspace/annotate.rs index 4f0f19e3..89819900 100644 --- a/apps/origin-src/src/workspace/annotate.rs +++ b/apps/origin-src/src/workspace/annotate.rs @@ -1,5 +1,5 @@ -//! The statement commands: `annotate`, `statements` and `promote`, -//! and flagging divergence when a revision is saved. +//! The statement commands, `annotate`, `statements` and `promote`, and +//! flagging a change as divergent when a revision is saved. use std::collections::HashSet; use std::fs::File; @@ -18,10 +18,10 @@ use crate::store::StoreError; use crate::tree::Snapshots; impl WorkingCopy { - /// The revision `rev` names: `@` for the working copy's own, or by a - /// unique prefix of its id, a change for its head, or a revision. A - /// prefix naming a change and another revision than its head is - /// ambiguous. + /// Finds the revision `rev` names. `@` is the working copy's revision. + /// Otherwise `rev` is a unique prefix of a change's id, naming its head, + /// or of a revision's id. A prefix that names both a change and a + /// revision other than its head is ambiguous. fn find_revision(&self, index: &Index, rev: &str) -> Result { if rev == "@" { return Ok(self.id); @@ -40,8 +40,9 @@ impl WorkingCopy { } } - /// The record `annotated` names, as [`WorkingCopy::find_revision`] - /// finds a revision, or a statement by a unique prefix of its id. + /// Finds the record `annotated` names: a revision, as + /// [`WorkingCopy::find_revision`] finds it, or a statement by a unique + /// prefix of its id. fn find_record( &self, index: &Index, @@ -54,7 +55,7 @@ impl WorkingCopy { } } -/// What a statement is about, as the command line names it. +/// What a statement is about, as named on the command line. #[derive(Clone, Copy, Debug)] pub enum Annotated<'a> { /// A revision: `@`, a change for its head, or a revision. @@ -68,12 +69,12 @@ pub enum Annotated<'a> { pub enum Payload { /// Text given inline, such as a review's message. Text(String), - /// A file's content, such as a log: standard input's for `-`. + /// The content of a file, such as a log, or of standard input for `-`. File(PathBuf), } impl Payload { - /// The blob holding the details. + /// Reads the details into a blob. fn blob(&self) -> Result { match self { Self::Text(text) => Ok(EncodedObject::blob(text.as_bytes())), @@ -92,14 +93,15 @@ impl Payload { } impl Workspace { - /// This node, which issues the statements core makes. + /// Returns this node as a principal. The node issues the statements + /// origin makes itself, such as `core.divergent`. pub(super) fn node_principal(&self) -> Principal { Principal::Node(self.config.node().clone()) } - /// Issues `core.divergent` if `revision`, just saved, made its change - /// diverge. The statement is the same for the same heads, so checking - /// again writes nothing. + /// Issues a `core.divergent` statement if saving `revision` made its + /// change diverge. The statement is the same for the same heads, so + /// calling this again writes nothing. pub(super) fn flag_divergence(&self, revision: RevisionId) -> Result<(), WorkspaceError> { let revision: Revision = self.store.get(revision)?; // A new change has a single revision. @@ -110,16 +112,15 @@ impl Workspace { Ok(()) } - /// `origin annotate --pass|--fail|--neutral|--withdraw`: - /// issues a statement about a revision as the user, superseding the - /// user's latest one of the same kind about it, as - /// [`Annotations::supersede`] does. Without a `verdict`, it withdraws - /// that one: see [`Statement::withdraws`]. + /// `origin annotate`: issues a statement as the user about a revision or + /// a statement. It supersedes the user's latest statement of the same + /// kind about the same subject. With no `verdict`, it withdraws that + /// statement instead. /// /// # Errors /// - /// Fails if the kind is reserved, the revision cannot be found, there - /// is nothing to withdraw, the payload cannot be read, or the records + /// Fails if the kind is reserved, the subject cannot be found, there is + /// nothing to withdraw, the payload cannot be read, or the records /// cannot be written. pub fn annotate( &mut self, @@ -181,9 +182,9 @@ impl Workspace { Ok(()) } - /// Why the user has no `kind` statement about `subject` to withdraw: - /// none holds there, or about a revision, only a promotion of one of - /// theirs about another revision, which is where they withdraw it. + /// Builds the error for a withdrawal that found nothing to withdraw. If + /// the subject is a revision holding a promotion of the user's `kind` + /// statement from another revision, the error says to withdraw it there. /// /// # Errors /// @@ -221,9 +222,9 @@ impl Workspace { }) } - /// `origin statements []`: prints the statements about a revision, - /// the working copy by default, in the order they arrived, each with the - /// statements about it indented under it. + /// `origin statements []`: prints the statements about a revision + /// in the order they arrived. Each is followed by the statements about + /// it, indented. /// /// # Errors /// @@ -239,10 +240,10 @@ impl Workspace { self.print_statements(&annotations, subject, "", &mut HashSet::new()) } - /// Prints the statements about `subject`, each one's lines after - /// `indent`, then the statements about it, indented further. `shown` - /// keeps a statement from printing twice, so a malformed store's cycle - /// ends. + /// Prints the statements about `subject`, each prefixed by `indent`, and + /// under each one, the statements about it, indented further. `shown` + /// holds the statements already printed, so none prints twice and a + /// cycle in a malformed store ends. fn print_statements( &self, annotations: &Annotations, @@ -299,8 +300,8 @@ impl Workspace { Ok(()) } - /// A payload's first line if it's text, its size otherwise, or that - /// this repository doesn't have it. + /// Summarizes a payload: its first line if it is text, its size + /// otherwise, or that this repository doesn't have it. fn payload_summary(&self, payload: BlobId) -> Result { let Some(content) = self.store.try_blob(payload.into())? else { return Ok("not in this repository".to_owned()); @@ -313,9 +314,9 @@ impl Workspace { ) } - /// `origin promote []`: carries promotable results over to a - /// revision, the working copy by default, from the records with the - /// same input digest, as statements this node issues. + /// `origin promote []`: copies promotable results to a revision + /// from records with the same input digest. This node issues the + /// copies. /// /// # Errors /// diff --git a/apps/origin-src/src/workspace/mod.rs b/apps/origin-src/src/workspace/mod.rs index be212bac..533a3a0b 100644 --- a/apps/origin-src/src/workspace/mod.rs +++ b/apps/origin-src/src/workspace/mod.rs @@ -53,23 +53,23 @@ pub struct Workspace { revision: RevisionId, } -/// The working copy as of a snapshot. +/// The working copy as found by 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. + /// The files the snapshot found: the draft. Once recorded, this is the + /// revision's snapshot. files: TreeId, - /// The revision's record, if recording the draft made a new revision, - /// which is not written yet. + /// The encoded new revision, if recording the draft made one and it is + /// not written yet. unsaved: Option, /// The revision's unresolved conflicts that the files still have. conflicts: Conflicts, } impl WorkingCopy { - /// The change `prefix` names: `@` for the working copy's, or a unique - /// prefix of its id. + /// Finds the change `prefix` names: `@` for the working copy's change, + /// or a unique prefix of its id. fn find_change(&self, index: &Index, prefix: &str) -> Result { if prefix == "@" { return Ok(self.revision.change); @@ -82,9 +82,9 @@ 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. + /// `origin init`: creates a repository in `root` with a `policy` target + /// that makes this node the authority of `policy` and `main`, an empty + /// `main`, and a first change on top of `main`. /// /// # Errors /// @@ -165,8 +165,9 @@ impl Workspace { /// /// # 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. + /// Fails if neither `start` nor any parent has a repository, the + /// repository is on a network file system, or its `workspace` file is + /// unreadable. pub fn discover(start: &Path, config: UserConfig) -> Result { let root = start .ancestors() @@ -197,8 +198,8 @@ impl Workspace { &self.root } - /// Snapshots the working copy into a draft, recording nothing, for the - /// commands that only read it. + /// Snapshots the working copy into a draft without recording it, for + /// commands that only read the working copy. fn snapshot(&self) -> Result { let revision: Revision = self.store.get(self.revision)?; let path = self.meta("state"); @@ -221,8 +222,9 @@ impl Workspace { }) } - /// Snapshots the working copy and records its draft: a new revision if - /// the files changed, which still has to be saved. + /// Snapshots the working copy and records the draft. If the files + /// changed, the result holds a new revision in `unsaved`, which the + /// caller must save. fn record(&self) -> Result { let working_copy = self.snapshot()?; if working_copy.files == working_copy.revision.snapshot { @@ -286,8 +288,8 @@ impl Workspace { vec![first, statements, vec![revision.clone()]] } - /// Snapshots the working copy and saves its draft as a new revision if - /// the files changed, for the commands that build on it. + /// Snapshots the working copy and saves the draft as a new revision if + /// the files changed. Used by commands that build on the working copy. fn refresh(&mut self) -> Result { let mut working_copy = self.record()?; if let Some(unsaved) = working_copy.unsaved.take() { @@ -296,8 +298,8 @@ impl Workspace { Ok(working_copy) } - /// Writes `layers` of objects, then makes `revision` the working copy, - /// flagging its change if that made it diverge. + /// Writes `layers` of objects, makes `revision` the working copy, and + /// flags its change if that made it diverge. fn save( &mut self, layers: &[Vec], @@ -308,8 +310,8 @@ impl Workspace { self.flag_divergence(revision) } - /// Writes `layers` of objects in order, each durable before the next, - /// so objects may refer to those of earlier layers. + /// Writes `layers` of objects in order, each layer durable before the + /// next, so objects may refer to objects in earlier layers. fn write(&self, layers: &[Vec]) -> Result<(), WorkspaceError> { for layer in layers.iter().filter(|layer| !layer.is_empty()) { self.store.write_all(layer)?; @@ -317,7 +319,8 @@ impl Workspace { Ok(()) } - /// Durably records that the working copy is `revision`. + /// Durably writes `revision` to the `workspace` file, making it the + /// working copy. fn point_at(&mut self, revision: RevisionId) -> Result<(), WorkspaceError> { let write = self.store.durable_write(); write @@ -383,8 +386,8 @@ impl Workspace { 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. + /// `origin show []`: prints a change's head (or each head, if it + /// diverged) and its diff. Shows the working copy's change by default. /// /// # Errors /// @@ -436,7 +439,7 @@ impl Workspace { Ok(()) } - /// Prints the changes `files` make to the snapshot of `base`. + /// Prints the diff from the snapshot of `base` to `files`. fn print_diff(&self, base: Base, files: TreeId) -> Result<(), WorkspaceError> { let base = self.base_tree(base)?; for change in self.store.diff(base, files)? { @@ -482,7 +485,7 @@ impl Workspace { } /// `origin describe `: replaces the current change's - /// description, with a new revision. + /// description by saving a new revision. /// /// # Errors /// @@ -559,16 +562,15 @@ impl Workspace { } /// `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. + /// change was abandoned, and why, with a `core.abandon` statement on its + /// head. If it is the current change, starts a new change on the same + /// base and restores the base's files. /// /// # Errors /// /// Fails if the change cannot be found or diverged, the user didn't - /// create it, so readers would ignore the statement, or the records - /// cannot be written. Then no abandonment is written and nothing is - /// checked out. + /// create it (readers would ignore the statement), or the records cannot + /// be written. On these errors, nothing is written or checked out. pub fn abandon(&mut self, change: Option<&str>, reason: &str) -> Result<(), WorkspaceError> { let working_copy = self.refresh()?; let index = Index::open(&self.store)?; @@ -737,13 +739,14 @@ impl Workspace { } /// `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. + /// down to the target it's on, then that target's acceptances, newest + /// first. Given a target, prints that target's acceptances instead, + /// under the stack only if the stack is on that target. `limit` caps + /// the number of acceptances. /// /// # Errors /// - /// Fails if the target doesn't exist, or a record cannot be read. + /// Fails if the target doesn't exist or a record cannot be read. pub fn log( &mut self, target: Option, @@ -832,7 +835,7 @@ impl Workspace { Ok(()) } - /// `origin index rebuild`: reconstructs the index from the store. + /// `origin index rebuild`: rebuilds the index from the store. /// /// # Errors /// @@ -843,7 +846,7 @@ impl Workspace { Ok(()) } - /// The head of a change that didn't diverge. + /// Returns the head of a change, or an error if the change diverged. fn single_head(index: &Index, change: ChangeId) -> Result { match index.heads(change)[..] { [head] => Ok(head), @@ -859,7 +862,7 @@ impl Workspace { self.text(revision.description) } - /// A blob's content, as text. + /// Reads a blob's content as text, replacing invalid UTF-8. fn text(&self, blob: BlobId) -> Result { let id = blob.into(); let blob = self.store.read(id)?; @@ -878,7 +881,7 @@ impl Workspace { }) } - /// A revision's change and summary. + /// A revision's change and summary, on one line. fn headline(&self, revision: &Revision) -> Result { Ok(format!( "{} {}", @@ -887,7 +890,8 @@ impl Workspace { )) } - /// Marks a divergent or abandoned change. + /// Returns the marks for a change, ` (divergent)` and ` (abandoned)`, + /// or an empty string if neither applies. fn flags(&self, index: &Index, change: ChangeId) -> Result { let heads = index.heads(change); let mut flags = String::new(); @@ -903,8 +907,8 @@ impl Workspace { Ok(flags) } - /// Who abandoned a revision, and why: only those who may, as - /// [`Store::authorizes`] says. + /// Lists who abandoned a revision, and why. Only abandonments by someone + /// allowed to abandon it count, as [`Store::authorizes`] decides. fn abandonments( &self, index: &Index, @@ -924,7 +928,8 @@ impl Workspace { Ok(abandonments) } - /// Explains a divergent change's heads, and how to converge them. + /// Prints a divergent change's heads and how to converge them. Prints + /// nothing if the change has one head. fn print_divergence(index: &Index, change: ChangeId) { let heads = index.heads(change); if heads.len() > 1 { @@ -943,7 +948,8 @@ impl Workspace { shorts.join(", ") } - /// The snapshot a revision was made on top of. + /// Returns the snapshot of `base`: the tree 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, @@ -958,7 +964,7 @@ impl Workspace { } } - /// A target and position, such as `main #3`. + /// Describes an acceptance by its target and position, such as `main #3`. fn describe_acceptance(&self, id: AcceptanceId) -> Result { let acceptance = self.store.get(id)?; let body = acceptance.body(); @@ -993,7 +999,7 @@ pub enum WorkspaceError { Divergent { /// The change. change: ChangeId, - /// Its heads. + /// The change's heads. heads: Vec, }, /// `converge` was given a change with a single head. @@ -1008,7 +1014,7 @@ pub enum WorkspaceError { /// A change id prefix doesn't name one change. #[error(transparent)] FindChange(#[from] FindChangeError), - /// The working copy file isn't a revision id. + /// The `workspace` file doesn't hold a revision id. #[error("{} is not a revision id", .0.display())] Malformed(PathBuf), /// A metadata file cannot be accessed. @@ -1019,7 +1025,7 @@ pub enum WorkspaceError { /// The underlying error. source: io::Error, }, - /// The operating system has no randomness for a change id. + /// The operating system cannot supply randomness for a change id. #[error("cannot generate a change id")] Random(#[source] getrandom::Error), /// The user's configuration is unusable. @@ -1037,7 +1043,8 @@ pub enum WorkspaceError { /// A statement id prefix doesn't name one statement. #[error(transparent)] FindStatement(#[from] FindError), - /// A prefix names a change and another revision than its head. + /// A prefix names both a change and a revision other than the change's + /// head. #[error( "`{prefix}` names both change {} and revision {}: give more of either id", change.short(), @@ -1051,8 +1058,8 @@ pub enum WorkspaceError { /// The revision it names. revision: RevisionId, }, - /// `annotate --withdraw` found only a promotion of the user's - /// statement, which they withdraw about the revision it's about. + /// `annotate --withdraw` found only a promotion of the user's statement. + /// The user must withdraw the original, on the revision it is about. #[error( "your `{kind}` result about revision {} is promoted from statement {}, about revision {}: \ withdraw it there, with `origin annotate {} {kind} --withdraw`", @@ -1064,14 +1071,14 @@ pub enum WorkspaceError { WithdrawPromoted { /// The kind. kind: Kind, - /// The revision it's promoted to. + /// The revision the statement was promoted to. revision: RevisionId, - /// The user's statement it promotes. + /// The user's original statement. original: StatementId, - /// The revision that one is about. + /// The revision the original statement is about. from: RevisionId, }, - /// Only origin itself issues statements of `core.` kinds. + /// Statements of `core.` kinds are issued only by origin itself. #[error("`{0}` is a reserved kind: only origin itself issues `core.` statements")] ReservedKind(Kind), /// A statement cannot be issued. diff --git a/apps/origin-src/src/worktree.rs b/apps/origin-src/src/worktree.rs index 96889fe6..becb2958 100644 --- a/apps/origin-src/src/worktree.rs +++ b/apps/origin-src/src/worktree.rs @@ -1,10 +1,10 @@ -//! The files of a working copy: snapshotting them into trees, and checking -//! trees out into them. +//! 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. +//! A snapshot records every file; there is no staging area. A stat cache +//! keeps it fast: it remembers each file's metadata and blob id, so only +//! files whose metadata changed are read and hashed. Every phase runs in +//! parallel. use std::collections::HashMap; use std::ffi::OsStr; @@ -28,15 +28,15 @@ use origin_shared::{ use crate::store::{Store, StoreError}; use crate::tree::FileChange; -/// File metadata that changes whenever the content might have. +/// File metadata that changes whenever the content might have changed. #[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. + /// Modification time, in nanoseconds since the Unix epoch. Tools can set + /// it back, so on its own it doesn't prove a file is unchanged. mtime: i64, - /// Status change time in nanoseconds since the Unix epoch. Every write + /// Status change time, in nanoseconds since the Unix epoch. Every write /// moves it forward, and nothing can set it back. ctime: i64, inode: u64, @@ -54,36 +54,38 @@ impl Stat { } } -/// The stat cache: what each file looked like when it was last hashed, and -/// the snapshot those files made. +/// The stat cache: each file's metadata when it was last hashed, and the +/// root tree of that snapshot. #[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. + /// The root tree of that scan. A later scan that finds the same files, + /// all vouched for by the cache, reuses this tree instead of building + /// it. root: Option, - /// Keyed by path. Paths are only looked up, never turned into trees, so - /// they are not validated when loaded. + /// Each file's metadata and object id, by path. Paths are not validated + /// when loaded, since they are only looked up. files: HashMap, } impl StatCache { - /// Identifies the binary format. + /// Identifies the cache's 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. + /// How long before a scan a file must have last changed for its cache + /// entry to be trusted, in nanoseconds. Some filesystems (FAT) record + /// times in 2-second ticks, so a file edited again within the same tick + /// keeps the same metadata. const RACY_MARGIN: i64 = 2_000_000_000; - /// Looks up a file whose metadata has not changed. + /// Returns the cached id of the file at `path` if its metadata still + /// matches `stat`. /// - /// 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. + /// A file that changed shortly before the cached scan started is never + /// trusted: it may have changed again without its metadata changing. + /// Such "racy" files are rehashed until they settle. fn get(&self, path: &RepoPath, stat: &Stat) -> Option { let (cached, id) = self.files.get(path.as_str())?; let settled = @@ -91,8 +93,8 @@ impl StatCache { (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. + /// Loads the cache from `path`. A missing or unreadable cache loads as + /// empty, which only means the next scan rehashes every file. #[must_use] pub fn load(path: &Path) -> Self { fs::read(path) @@ -101,8 +103,8 @@ impl StatCache { .unwrap_or_default() } - /// Saves the cache atomically, but not durably: losing it only costs - /// rehashing. Every object it names is already durable. + /// Saves the cache to `path` atomically, but not durably: losing it + /// only costs rehashing. Every object it names is already durable. /// /// # Errors /// @@ -113,9 +115,9 @@ impl StatCache { 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]`. + /// Encodes the cache as `magic scanned_at:i64 has_root:u8 + /// [root:[u8; 32]]`, then, for each 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); @@ -141,7 +143,7 @@ impl StatCache { out } - /// Reads what [`StatCache::encode`] wrote. + /// Decodes what [`StatCache::encode`] wrote. fn decode(bytes: &[u8]) -> Result { let mut reader = Reader::new(bytes); if reader.take(Self::MAGIC.len())? != Self::MAGIC { @@ -180,7 +182,7 @@ impl StatCache { /// Everything the walk found. struct Walk { - /// Every directory, root first, each depth after the previous one. + /// Every directory, root first, ordered by depth. dirs: Vec, /// The range of `dirs` at each depth. depths: Vec>, @@ -194,13 +196,14 @@ struct FoundDir { entries: Vec<(EntryName, Child)>, } -/// An entry of a [`FoundDir`], indexing the walk's directories or files. +/// An entry of a [`FoundDir`]: an index into the walk's directories or +/// files. enum Child { Dir(usize), File(usize), } -/// What listing a directory says an entry is. +/// What a directory listing says an entry is. enum Listed { Dir, File { symlink: bool }, @@ -217,39 +220,42 @@ struct FoundFile { struct Examined { stat: Stat, id: ObjectId, - /// The file's blob, if it had to be read because the cache could not - /// vouch for it. + /// The file's blob, if the file 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`. +/// The files of the working copy rooted at `root`. Snapshots are written +/// 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. + /// Below this many items, work runs on one thread, since threads would + /// cost more than they save. const PARALLEL_THRESHOLD: usize = 64; - /// The working copy rooted at `root`. + /// Returns the working copy rooted at `root`, storing snapshots in + /// `store`. #[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 + /// Snapshots every file into the store. Returns the root tree, and the /// updated stat cache if it changed. /// - /// Three phases, each parallel: list directories one depth at a time, + /// It runs three parallel phases: 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. + /// the cache can't vouch for); and build trees one depth at a time, + /// deepest first. Then it writes the new blobs and trees in one batch. + /// + /// If a crash cuts the batch short, a tree may be stored without a blob + /// it names. Nothing refers to that tree yet, and the next snapshot + /// rewrites the blob, because the updated stat cache is only returned + /// once the batch commits. /// /// # Errors /// @@ -431,8 +437,9 @@ impl<'a, P: Platform> Worktree<'a, P> { }) } - /// Builds a directory's tree, given the trees of every deeper directory. - /// Returns `None` for a directory without files, which is not tracked. + /// Builds a directory's tree from the already built trees of its + /// subdirectories. Returns `None` for a directory with no files, which + /// is not tracked. fn build_tree( dir: &FoundDir, trees: &[Option], @@ -458,9 +465,9 @@ impl<'a, P: Platform> Worktree<'a, P> { (!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. + /// Makes the files match a snapshot, given `changes`, how they differ + /// from it: removes the files `changes` remove, then writes the ones + /// they add or modify. Removes directories left empty. /// /// # Errors /// @@ -491,7 +498,7 @@ impl<'a, P: Platform> Worktree<'a, P> { self.root.join(path.as_str()) } - /// Removes a file, if it's there. + /// Removes a file, if it exists. fn remove(path: &Path) -> Result<(), SnapshotError> { match fs::remove_file(path) { Err(error) if error.kind() != io::ErrorKind::NotFound => Err(SnapshotError::Io { @@ -529,9 +536,9 @@ impl<'a, P: Platform> Worktree<'a, P> { } } - /// 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. + /// Maps `items` in order, on one thread per core when there are at least + /// `PARALLEL_THRESHOLD` items. Each thread takes the next item when it + /// finishes one, since some files take much longer than others. fn par_map( items: &[T], map: impl Fn(&T) -> Result + Sync, @@ -632,7 +639,7 @@ mod tests { fs::write(path, content).unwrap(); } - /// Takes a snapshot, returning the cache to use next. + /// Takes a snapshot, returning the root tree and 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())) diff --git a/apps/origin-src/tests/cli.rs b/apps/origin-src/tests/cli.rs index 6c763244..628762ea 100644 --- a/apps/origin-src/tests/cli.rs +++ b/apps/origin-src/tests/cli.rs @@ -13,7 +13,7 @@ use origin_shared::{ }; use origin_src::store::Store; -/// A temporary working copy, and a user configuration of its own. +/// A temporary working copy with its own user configuration. struct Repo { dir: tempfile::TempDir, config: tempfile::TempDir, @@ -41,7 +41,7 @@ impl Repo { .unwrap() } - /// Runs a command that must succeed, returning its output. + /// Runs a command that must succeed, returning its standard output. fn ok(&self, args: &[&str]) -> String { let output = self.run(self.dir.path(), args); assert!( @@ -393,7 +393,7 @@ fn abandoning_the_current_change_restores_its_base() { assert!(show.contains("+cache\n"), "the attempt is kept: {show}"); } -/// The working copy's revision, in full. +/// The working copy's full revision id. fn revision_of(repo: &Repo) -> RevisionId { repo.read(".origin/workspace").trim().parse().unwrap() } @@ -650,7 +650,7 @@ fn a_closed_output_pipe_ends_quietly() { assert_eq!(String::from_utf8_lossy(&output.stderr), ""); } -/// The id of the statement an `annotate` issued, as it prints it. +/// The id of the statement an `annotate` issued, parsed from its output. fn issued(output: &str) -> String { let rest = output.split("statement ").nth(1).unwrap(); rest.split(':').next().unwrap().to_owned() diff --git a/tools/xtask/src/main.rs b/tools/xtask/src/main.rs index 99c27f8f..34d1f0ab 100644 --- a/tools/xtask/src/main.rs +++ b/tools/xtask/src/main.rs @@ -73,8 +73,8 @@ struct BenchGit { } impl BenchGit { - /// `path` as one `sh` word, whatever it holds: single-quoted, with each - /// `'` closing the quote, escaped, and reopening it. + /// Quotes `path` as one `sh` word: wraps it in single quotes, writing + /// each `'` inside it as `'\''`. fn quote(path: &Path) -> String { format!("'{}'", path.display().to_string().replace('\'', "'\\''")) } @@ -229,8 +229,9 @@ impl BenchGit { Ok(()) } - /// A git identity, and no user git configuration (hooks, fsmonitor) - /// skewing results. Origin's identity is in its configuration directory. + /// Environment variables that set a git identity and disable the user's + /// git configuration (hooks, fsmonitor), which would skew the results. + /// Origin's identity comes from its configuration directory. fn environment() -> impl Iterator { iter::empty() .chain([