use crate::procs::{self, Process};
use crate::session::{self, CheckRun};
use crate::{Error, Git, nul_fields};
use jouet_output::time;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::BTreeSet;
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
const DATA_OPEN: &str = "<!-- jouet-handoff";
const DATA_CLOSE: &str = "-->";
const LIST_LIMIT: usize = 50;
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Handoff {
pub created_at: String,
pub worktree: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub branch: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub head: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub head_subject: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub operation: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub upstream: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ahead: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub behind: Option<u32>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub changes: Vec<Change>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub untracked: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub diff_sha256: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pr: Option<Pr>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub checks: Vec<CheckRun>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub processes: Vec<Process>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub jobs: Vec<Job>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub daemons: Vec<Daemon>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub notes: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Change {
pub status: String,
pub path: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub from: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Pr {
pub repo: String,
pub number: u64,
pub title: String,
pub url: String,
pub state: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub attention: Vec<Attention>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Attention {
pub code: String,
pub message: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Job {
pub id: String,
pub state: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub exit_code: Option<i32>,
pub pid: u32,
pub command: String,
pub log: String,
}
impl Job {
fn describe(&self) -> String {
match self.exit_code {
Some(code) => format!("exited {code}"),
None => self.state.clone(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct JobNow {
pub id: String,
pub then: String,
pub now: String,
}
pub fn jobs_now(then: &[Job], now: &[Job]) -> (Vec<JobNow>, Vec<Drift>) {
let mut states = Vec::new();
let mut drift = Vec::new();
for j in then {
let current = now.iter().find(|n| n.id == j.id && n.pid == j.pid);
states.push(JobNow {
id: j.id.clone(),
then: j.describe(),
now: current.map_or_else(|| "gone".into(), Job::describe),
});
if j.state != "running" {
continue;
}
let message = match current {
Some(n) if n.state == "running" => continue,
Some(n) => format!(
"job `{}` has {} since; `jouet job logs {}` shows how it ended",
j.id,
match n.exit_code {
Some(code) => format!("exited {code}"),
None => format!("ended ({})", n.state),
},
j.id
),
None => format!(
"job `{}` is no longer in this worktree, or was started again",
j.id
),
};
drift.push(Drift {
code: "job_ended",
message,
});
}
(states, drift)
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Daemon {
pub id: String,
pub status: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pid: Option<u32>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub port: Vec<u16>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
}
impl Daemon {
pub fn alive(&self) -> bool {
matches!(
self.status.as_str(),
"running" | "waiting" | "stopping" | "restarting"
)
}
fn failed(&self) -> bool {
matches!(self.status.as_str(), "errored" | "failed")
}
fn describe(&self) -> String {
let mut s = self.status.clone();
if let Some(error) = &self.error {
let _ = write!(s, " ({error})");
}
if let Some(pid) = self.pid {
let _ = write!(s, ", pid {pid}");
}
if !self.port.is_empty() {
let ports: Vec<String> = self.port.iter().map(u16::to_string).collect();
let _ = write!(s, ", port {}", ports.join(", "));
}
s
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct DaemonNow {
pub id: String,
pub then: String,
pub now: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
}
pub fn daemons_now(then: &[Daemon], now: &[Daemon]) -> (Vec<DaemonNow>, Vec<Drift>) {
let mut states = Vec::new();
let mut drift = Vec::new();
for d in then {
let current = now.iter().find(|n| n.id == d.id);
states.push(DaemonNow {
id: d.id.clone(),
then: d.status.clone(),
now: current.map_or_else(|| "gone".into(), |n| n.status.clone()),
error: current.and_then(|n| n.error.clone()),
});
if !d.alive() {
continue;
}
let (code, message) = match current {
None => (
"daemon_gone",
format!("`{}` is no longer known to pitchfork", d.id),
),
Some(n) if n.failed() => (
"daemon_failed",
format!(
"`{}` has {}; `pitchfork logs {} -n 50` shows why",
d.id,
n.describe(),
d.id
),
),
Some(n) if !n.alive() => ("daemon_stopped", format!("`{}` is {} now", d.id, n.status)),
Some(n) if n.pid.is_some() && d.pid.is_some() && n.pid != d.pid => (
"daemon_restarted",
format!(
"`{}` has restarted: pid {} then, {} now",
d.id,
d.pid.unwrap_or(0),
n.pid.unwrap_or(0)
),
),
Some(_) => continue,
};
drift.push(Drift { code, message });
}
(states, drift)
}
#[derive(Debug, Clone, Default)]
pub struct Options {
pub session: Option<(PathBuf, String)>,
pub processes: bool,
}
pub fn default_path(git: &Git) -> Result<PathBuf, Error> {
Ok(git.git_dir()?.join("jouet").join("handoff.md"))
}
pub fn collect(git: &Git, opts: &Options) -> Result<Handoff, Error> {
let top = git.toplevel()?;
let mut h = git_facts(git, &top)?;
h.created_at = time::format_utc(time::now());
match &opts.session {
Some((dir, id)) => match session::last_checks(dir, id, &top) {
Some(runs) => h.checks = runs,
None => h.notes.push(format!(
"checks: none recorded for session {id} in this worktree (jouet setup's hooks record them)"
)),
},
None => h
.notes
.push("checks: no session ID, so no recorded test or lint runs".into()),
}
if opts.processes {
match procs::in_worktree(&top) {
Some(found) => h.processes = found,
None => h
.notes
.push("processes: not listed on this platform (Linux only)".into()),
}
}
Ok(h)
}
fn git_facts(git: &Git, top: &Path) -> Result<Handoff, Error> {
let status = git.text(&[
"status",
"--porcelain=v2",
"--branch",
"-z",
"--untracked-files=all",
])?;
let mut h = Handoff {
worktree: top.display().to_string(),
..Handoff::default()
};
let mut fields = nul_fields(&status);
while let Some(field) = fields.next() {
if let Some(header) = field.strip_prefix("# ") {
let (key, value) = header.split_once(' ').unwrap_or((header, ""));
match key {
"branch.oid" if value != "(initial)" => h.head = Some(value.into()),
"branch.head" if value != "(detached)" => h.branch = Some(value.into()),
"branch.upstream" => h.upstream = Some(value.into()),
"branch.ab" => {
let mut counts = value
.split(' ')
.map(|n| n.trim_start_matches(['+', '-']).parse().ok());
h.ahead = counts.next().flatten();
h.behind = counts.next().flatten();
}
_ => {}
}
continue;
}
let (kind, rest) = field.split_at(1);
let rest = rest.trim_start();
match kind {
"1" => h.changes.push(entry(rest, 6, None)),
"2" => {
let from = fields.next().map(str::to_string);
h.changes.push(entry(rest, 7, from));
}
"u" => h.changes.push(entry(rest, 8, None)),
"?" => h.untracked.push(rest.to_string()),
_ => {}
}
}
if h.head.is_some() {
h.head_subject = git.line(&["log", "-1", "--format=%s", "HEAD"]);
}
h.diff_sha256 = fingerprint(git)?;
h.operation = operation(&git.git_dir()?);
Ok(h)
}
fn fingerprint(git: &Git) -> Result<Option<String>, Error> {
let diff = ["diff", "--binary", "--no-ext-diff", "--no-color"];
let staged = git.text(&[&diff[..], &["--cached"]].concat())?;
let unstaged = git.text(&diff)?;
if staged.is_empty() && unstaged.is_empty() {
return Ok(None);
}
let mut hash = Sha256::new();
for (name, text) in [("staged", &staged), ("unstaged", &unstaged)] {
hash.update(format!("{name} {}\n", text.len()));
hash.update(text.as_bytes());
}
Ok(Some(hex(&hash.finalize())))
}
fn entry(rest: &str, fields: usize, from: Option<String>) -> Change {
let mut parts = rest.splitn(fields + 2, ' ');
let xy = parts.next().unwrap_or("..").replace('.', " ");
let path = parts.nth(fields).unwrap_or_default().to_string();
Change {
status: xy,
path,
from,
}
}
fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
fn operation(git_dir: &Path) -> Option<String> {
let has = |name: &str| git_dir.join(name).exists();
let op = if has("rebase-merge") || (has("rebase-apply") && !has("rebase-apply/applying")) {
"rebase"
} else if has("rebase-apply") {
"am"
} else if has("MERGE_HEAD") {
"merge"
} else if has("CHERRY_PICK_HEAD") {
"cherry-pick"
} else if has("REVERT_HEAD") {
"revert"
} else if has("BISECT_LOG") {
"bisect"
} else {
return None;
};
Some(op.into())
}
impl Handoff {
pub fn markdown(&self, data: bool) -> String {
let mut s = String::new();
let title = self.branch.as_deref().unwrap_or("detached HEAD");
let _ = writeln!(s, "# Handoff: {title}\n");
let _ = writeln!(s, "Written {} in `{}`.\n", self.created_at, self.worktree);
let mut branch = format!("- **Branch:** {title}");
if let Some(up) = &self.upstream {
let _ = write!(branch, ", tracking {up}");
if let (Some(a), Some(b)) = (self.ahead, self.behind) {
let _ = write!(branch, " ({a} ahead, {b} behind)");
}
} else {
branch.push_str(", no upstream");
}
let _ = writeln!(s, "{branch}");
match (&self.head, &self.head_subject) {
(Some(head), subject) => {
let _ = writeln!(
s,
"- **HEAD:** {} {}",
head.get(..12).unwrap_or(head),
subject.as_deref().unwrap_or("")
);
}
(None, _) => s.push_str("- **HEAD:** none yet (unborn branch)\n"),
}
if let Some(op) = &self.operation {
let _ = writeln!(s, "- **In progress:** a {op}");
}
match &self.pr {
Some(pr) => {
let _ = writeln!(
s,
"- **PR:** {}#{} ({}) {}: {}",
pr.repo, pr.number, pr.state, pr.url, pr.title
);
if pr.attention.is_empty() {
s.push_str(" - no attention codes\n");
}
for a in &pr.attention {
let _ = writeln!(s, " - `{}`: {}", a.code, a.message);
}
}
None => s.push_str("- **PR:** none found\n"),
}
if !self.checks.is_empty() {
s.push_str("- **Last checks:**\n");
for c in &self.checks {
let verdict = if c.exit_code == 0 { "passed" } else { "failed" };
let _ = writeln!(
s,
" - {} {verdict} (exit {}): `{}`",
c.kind, c.exit_code, c.command
);
}
}
let changes: Vec<String> = self
.changes
.iter()
.map(|c| match &c.from {
Some(from) => format!("`{}` {} (from {from})", c.status, c.path),
None => format!("`{}` {}", c.status, c.path),
})
.collect();
list(&mut s, "Uncommitted", &changes, data);
let untracked: Vec<String> = self.untracked.clone();
list(&mut s, "Untracked", &untracked, data);
let processes: Vec<String> = self
.processes
.iter()
.map(|p| format!("{} `{}`: attach with `{}`", p.pid, p.command, p.attach()))
.collect();
list(&mut s, "Background processes", &processes, data);
let jobs: Vec<String> = self
.jobs
.iter()
.map(|j| {
let follow = if j.state == "running" {
format!(", `jouet wait job {}`", j.id)
} else {
String::new()
};
format!(
"`{}` {}, pid {}: `{}`; `jouet job logs {}`{follow}",
j.id,
j.describe(),
j.pid,
j.command,
j.id
)
})
.collect();
list(&mut s, "Jobs", &jobs, data);
let daemons: Vec<String> = self
.daemons
.iter()
.map(|d| {
let follow = if d.alive() {
format!(", `jouet wait daemon {}`", d.id)
} else {
String::new()
};
format!(
"`{}` {}: `pitchfork logs {} -n 50`{follow}",
d.id,
d.describe(),
d.id
)
})
.collect();
list(&mut s, "pitchfork daemons", &daemons, data);
if !self.notes.is_empty() {
s.push_str("- **Not gathered:**\n");
for n in &self.notes {
let _ = writeln!(s, " - {n}");
}
}
if data {
let json = serde_json::to_string_pretty(self)
.expect("a handoff always serializes")
.replace("-->", "--\\u003e");
let _ = write!(s, "\n{DATA_OPEN}\n{json}\n{DATA_CLOSE}\n");
}
s
}
}
fn list(s: &mut String, heading: &str, items: &[String], data: bool) {
if items.is_empty() {
return;
}
let _ = writeln!(s, "- **{heading} ({}):**", items.len());
for item in items.iter().take(LIST_LIMIT) {
let _ = writeln!(s, " - {item}");
}
if items.len() > LIST_LIMIT {
let rest = items.len() - LIST_LIMIT;
let whole = if data {
"the data at the end of this file lists all of them"
} else {
"`jouet pickup --json` lists all of them"
};
let _ = writeln!(s, " - ... {rest} more ({whole})");
}
}
pub fn parse(text: &str) -> Result<Handoff, String> {
let json = if text.trim_start().starts_with('{') {
text
} else {
let start = text
.rfind(DATA_OPEN)
.ok_or("this is not a jouet handoff: it has no `<!-- jouet-handoff` data")?;
let body = &text[start + DATA_OPEN.len()..];
let end = body
.find(DATA_CLOSE)
.ok_or("the handoff's data is cut short: no closing `-->`")?;
&body[..end]
};
serde_json::from_str(json).map_err(|e| format!("reading the handoff's data: {e}"))
}
pub fn write(path: &Path, handoff: &Handoff) -> std::io::Result<()> {
let text = if path.extension().is_some_and(|e| e == "json") {
let mut json = serde_json::to_string_pretty(handoff)?;
json.push('\n');
json
} else {
handoff.markdown(true)
};
crate::write_atomic(path, &text)
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Drift {
pub code: &'static str,
pub message: String,
}
pub fn drift(git: &Git, then: &Handoff) -> Result<Vec<Drift>, Error> {
let top = git.toplevel()?;
let now = git_facts(git, &top)?;
let mut out = Vec::new();
let mut add = |code, message: String| out.push(Drift { code, message });
if now.worktree != then.worktree {
add(
"worktree",
format!("written in {}, read in {}", then.worktree, now.worktree),
);
}
if now.branch != then.branch {
add(
"branch",
format!(
"the branch was {}, now {}",
then.branch.as_deref().unwrap_or("detached"),
now.branch.as_deref().unwrap_or("detached")
),
);
}
if now.head != then.head {
let (code, message) = head_drift(git, then.head.as_deref(), now.head.as_deref());
add(code, message);
}
if now.operation != then.operation {
add(
"operation",
format!(
"the operation in progress was {}, now {}",
then.operation.as_deref().unwrap_or("none"),
now.operation.as_deref().unwrap_or("none")
),
);
}
if now.upstream != then.upstream {
add(
"upstream",
format!(
"the upstream was {}, now {}",
then.upstream.as_deref().unwrap_or("none"),
now.upstream.as_deref().unwrap_or("none")
),
);
} else if now.behind != then.behind {
add(
"behind",
format!(
"{} behind {}, was {}",
now.behind.unwrap_or(0),
now.upstream.as_deref().unwrap_or("the upstream"),
then.behind.unwrap_or(0)
),
);
}
if now.changes != then.changes {
add("uncommitted", changed_files(&then.changes, &now.changes));
} else if now.diff_sha256 != then.diff_sha256 {
add(
"uncommitted",
"the uncommitted files are the same, but their staged or unstaged changes differ"
.into(),
);
}
let (before, after): (BTreeSet<_>, BTreeSet<_>) = (
then.untracked.iter().collect(),
now.untracked.iter().collect(),
);
if before != after {
let gone: Vec<String> = before.difference(&after).map(|p| (*p).clone()).collect();
let new: Vec<String> = after.difference(&before).map(|p| (*p).clone()).collect();
add("untracked", changed_sets("untracked", &new, &gone));
}
for p in &then.processes {
if procs::alive(p.pid) == Some(false) {
add(
"process_exited",
format!("{} `{}` has exited", p.pid, p.command),
);
}
}
Ok(out)
}
fn head_drift(git: &Git, then: Option<&str>, now: Option<&str>) -> (&'static str, String) {
let (Some(then), Some(now)) = (then, now) else {
return (
"head",
format!(
"HEAD was {}, now {}",
then.unwrap_or("unborn"),
now.unwrap_or("unborn")
),
);
};
let short = |s: &str| s.get(..12).unwrap_or(s).to_string();
if git.commit_sha(then).is_none() {
return (
"head",
format!(
"HEAD was {}, which is not in this repository; now {}",
short(then),
short(now)
),
);
}
if git.is_ancestor(then, now) {
let n = git.count(&format!("{then}..{now}")).unwrap_or(0);
return (
"head",
format!(
"{n} new {} since the handoff ({}..{})",
if n == 1 { "commit" } else { "commits" },
short(then),
short(now)
),
);
}
if git.is_ancestor(now, then) {
let n = git.count(&format!("{now}..{then}")).unwrap_or(0);
return (
"head",
format!(
"HEAD moved back {n} {} to {} (it was {})",
if n == 1 { "commit" } else { "commits" },
short(now),
short(then)
),
);
}
(
"head",
format!(
"HEAD was rewritten: it was {}, now {}, and neither contains the other",
short(then),
short(now)
),
)
}
fn changed_files(then: &[Change], now: &[Change]) -> String {
let status = |list: &[Change], path: &str| {
list.iter()
.find(|c| c.path == path)
.map(|c| c.status.clone())
};
let paths: BTreeSet<&str> = then.iter().chain(now).map(|c| c.path.as_str()).collect();
let mut parts = Vec::new();
for path in paths {
match (status(then, path), status(now, path)) {
(None, Some(s)) => parts.push(format!("{path} is now changed (`{s}`)")),
(Some(_), None) => parts.push(format!("{path} no longer has changes")),
(Some(a), Some(b)) if a != b => {
parts.push(format!("{path} was `{a}`, now `{b}`"));
}
_ => {}
}
}
parts.join("; ")
}
fn changed_sets(what: &str, new: &[String], gone: &[String]) -> String {
let mut parts = Vec::new();
if !new.is_empty() {
parts.push(format!("now {what}: {}", new.join(", ")));
}
if !gone.is_empty() {
parts.push(format!("no longer {what}: {}", gone.join(", ")));
}
parts.join("; ")
}
#[cfg(test)]
#[path = "handoff_tests.rs"]
mod tests;