Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ origin workspace list | rm <path>

origin op log [-n <count>] # what this node did, operation by operation, in every workspace
origin undo # move this workspace's working copy back one operation
origin watch [--kind <kind>] [--subject <id>] [--since <cursor>] # events, as they happen
```

Landing rebases a change onto the target's tip, file by file, checks the
Expand Down Expand Up @@ -74,7 +75,11 @@ Every node keeps an op log of what it did: records written, landings left
waiting and working copies moved, numbered in order. `origin undo` only
moves the working copy of the workspace it runs in back to where it was
before its latest operation; records and targets stay as they are, so an
undone landing still landed.
undone landing still landed. `origin watch` prints events derived from the
op log, one a line starting with a cursor: `statement.issued`,
`revision.created`, `target.advanced` and `check.requested`. `--kind`
takes an event name or a statement kind (`core.conflict`, `ci.*`), and
`--since` resumes after a cursor.

Changes are named by a unique prefix of their id, or `@` for the working
copy's. A revision is `@`, a change (for its head), or a unique prefix of
Expand Down
28 changes: 28 additions & 0 deletions apps/origin-src/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ use clap::{Args, CommandFactory, Parser, Subcommand};
use origin_shared::{Digest, Inputs, Kind, RepoPath, TargetName, Verdict};

use crate::config::UserConfig;
use crate::events::Filter;
use crate::oplog::Actor;
use crate::policy::KindPattern;
use crate::workspace::{Annotated, Payload, Workspace};

/// A modern, git-compatible source control system.
Expand Down Expand Up @@ -154,6 +156,21 @@ enum WorkspaceCommand {
/// Move this workspace's working copy back to where it was before its
/// latest operation. Records and targets stay as they are.
Undo,
/// Print events as they happen, one a line, starting with the cursor to
/// resume from. Runs until interrupted.
Watch {
/// Only events of this name, such as `check.requested`, or about
/// statements of this kind, such as `core.conflict` or `ci.*`.
#[arg(long)]
kind: Vec<KindPattern>,
/// Only events about this: a revision or change id prefix, or a
/// target name.
#[arg(long)]
subject: Vec<String>,
/// Start after this cursor instead of now: `0` for every event kept.
#[arg(long)]
since: Option<u64>,
},
}

#[derive(Debug, Subcommand)]
Expand Down Expand Up @@ -474,6 +491,17 @@ impl WorkspaceCommand {
Self::Workspace(WorkspacesCommand::Rm { path }) => workspace.remove_workspace(&path)?,
Self::Op(OpCommand::Log { limit }) => workspace.op_log(limit)?,
Self::Undo => workspace.undo()?,
Self::Watch {
kind,
subject,
since,
} => workspace.watch(
&Filter {
kinds: kind,
subjects: subject,
},
since,
)?,
}
Ok(())
}
Expand Down
26 changes: 25 additions & 1 deletion apps/origin-src/src/workspace/ops.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! The op log commands: `op log` and `undo`.
//! The op log commands: `op log`, `undo` and `watch`.
//!
//! `undo` takes back the latest operation of the workspace it runs in that
//! moved its working copy, other than recording its draft: it moves the
Expand All @@ -18,10 +18,12 @@
//! diverge.

use std::collections::{BTreeMap, HashSet};
use std::time::Duration;

use origin_shared::{Record, RecordId, Revision, RevisionId};

use super::{Workspace, WorkspaceError};
use crate::events::{Events, Filter};
use crate::index;
use crate::oplog::{Effect, Entry, Move, Why};
use crate::queue::Proposal;
Expand Down Expand Up @@ -202,4 +204,26 @@ impl Workspace {
}
Err(WorkspaceError::NothingToUndo)
}

/// `origin watch [--kind <kind>]... [--subject <subject>]... [--since
/// <cursor>]`: prints the events that pass `filter` as they happen, one
/// a line, from `since`, or from now. Runs until interrupted.
///
/// # Errors
///
/// Fails if the cursor expired, or the op log or a record cannot be read.
pub fn watch(&self, filter: &Filter, since: Option<u64>) -> Result<(), WorkspaceError> {
let events = Events::new(&self.store);
let mut cursor = match since {
Some(since) => since,
None => events.end()?,
};
loop {
let page = events.wait(cursor, filter, 256, Duration::from_secs(60))?;
for event in &page.events {
println!("{event}");
}
cursor = page.next;
}
}
}
54 changes: 52 additions & 2 deletions apps/origin-src/tests/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
//! `origin` binary.

use std::fs::{self, OpenOptions};
use std::io::Write;
use std::io::{BufRead, BufReader, Write};
use std::os::unix::fs::{MetadataExt, PermissionsExt};
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
use std::process::{Child, Command, Output, Stdio};
use std::slice;
use std::sync::mpsc;
use std::thread;
Expand Down Expand Up @@ -50,6 +50,26 @@ impl Repo {
self.command(cwd, args).output().unwrap()
}

/// Starts a long-running command, such as `watch`, returning it and its
/// output lines as they come.
fn spawn(&self, args: &[&str]) -> (Child, mpsc::Receiver<String>) {
let mut child = self
.command(self.dir.path(), args)
.stdout(Stdio::piped())
.spawn()
.unwrap();
let stdout = BufReader::new(child.stdout.take().unwrap());
let (send, receive) = mpsc::channel();
thread::spawn(move || {
for line in stdout.lines() {
if send.send(line.unwrap()).is_err() {
break;
}
}
});
(child, receive)
}

/// The revision the working copy is, in full.
fn revision(&self) -> String {
self.read(".origin/workspace").trim_end().to_owned()
Expand Down Expand Up @@ -2044,3 +2064,33 @@ fn a_move_that_cannot_be_finished_leaves_the_files() {
assert!(!repo.path(".origin/moving").exists());
repo.ok(&["log"]);
}

#[test]
fn watch_prints_events_from_a_cursor_or_as_they_happen() {
let repo = Repo::new();
let line =
|receive: &mpsc::Receiver<String>| receive.recv_timeout(Duration::from_secs(20)).unwrap();
// From the start: the targets `init` created.
let (mut all, receive) = repo.spawn(&["watch", "--since", "0"]);
let policy = line(&receive);
assert!(
policy.contains(" target.advanced target=policy seq=0 "),
"{policy}"
);
all.kill().unwrap();

let (mut checks, receive) = repo.spawn(&["watch", "--kind", "ci.*"]);
// Let it read where the log ends before anything happens.
thread::sleep(Duration::from_millis(500));
repo.ok(&["describe", "Work"]);
repo.ok(&["annotate", "@", "ci.test", "--pass"]);
let issued = line(&receive);
checks.kill().unwrap();
let fields: Vec<_> = issued.split(' ').collect();
assert!(fields[0].parse::<u64>().is_ok(), "a cursor first: {issued}");
assert_eq!(fields[1], "statement.issued");
assert!(
issued.contains(" kind=ci.test verdict=pass issuer=user:ada"),
"{issued}"
);
}