1use crate::procs::{self, Process};
16use crate::session::{self, CheckRun};
17use crate::{Error, Git, nul_fields};
18use jouet_output::time;
19use serde::{Deserialize, Serialize};
20use sha2::{Digest, Sha256};
21use std::collections::BTreeSet;
22use std::fmt::Write as _;
23use std::path::{Path, PathBuf};
24
25const DATA_OPEN: &str = "<!-- jouet-handoff";
26const DATA_CLOSE: &str = "-->";
27const LIST_LIMIT: usize = 50;
29
30#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
31pub struct Handoff {
32 pub created_at: String,
33 pub worktree: String,
34 #[serde(default, skip_serializing_if = "Option::is_none")]
35 pub branch: Option<String>,
36 #[serde(default, skip_serializing_if = "Option::is_none")]
38 pub head: Option<String>,
39 #[serde(default, skip_serializing_if = "Option::is_none")]
40 pub head_subject: Option<String>,
41 #[serde(default, skip_serializing_if = "Option::is_none")]
43 pub operation: Option<String>,
44 #[serde(default, skip_serializing_if = "Option::is_none")]
45 pub upstream: Option<String>,
46 #[serde(default, skip_serializing_if = "Option::is_none")]
47 pub ahead: Option<u32>,
48 #[serde(default, skip_serializing_if = "Option::is_none")]
49 pub behind: Option<u32>,
50 #[serde(default, skip_serializing_if = "Vec::is_empty")]
52 pub changes: Vec<Change>,
53 #[serde(default, skip_serializing_if = "Vec::is_empty")]
54 pub untracked: Vec<String>,
55 #[serde(default, skip_serializing_if = "Option::is_none")]
58 pub diff_sha256: Option<String>,
59 #[serde(default, skip_serializing_if = "Option::is_none")]
60 pub pr: Option<Pr>,
61 #[serde(default, skip_serializing_if = "Vec::is_empty")]
62 pub checks: Vec<CheckRun>,
63 #[serde(default, skip_serializing_if = "Vec::is_empty")]
64 pub processes: Vec<Process>,
65 #[serde(default, skip_serializing_if = "Vec::is_empty")]
67 pub jobs: Vec<Job>,
68 #[serde(default, skip_serializing_if = "Vec::is_empty")]
71 pub daemons: Vec<Daemon>,
72 #[serde(default, skip_serializing_if = "Vec::is_empty")]
74 pub notes: Vec<String>,
75}
76
77#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
78pub struct Change {
79 pub status: String,
82 pub path: String,
83 #[serde(default, skip_serializing_if = "Option::is_none")]
85 pub from: Option<String>,
86}
87
88#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
89pub struct Pr {
90 pub repo: String,
91 pub number: u64,
92 pub title: String,
93 pub url: String,
94 pub state: String,
95 #[serde(default, skip_serializing_if = "Vec::is_empty")]
96 pub attention: Vec<Attention>,
97}
98
99#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
100pub struct Attention {
101 pub code: String,
102 pub message: String,
103}
104
105#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
107pub struct Job {
108 pub id: String,
109 pub state: String,
111 #[serde(default, skip_serializing_if = "Option::is_none")]
112 pub exit_code: Option<i32>,
113 pub pid: u32,
114 pub command: String,
116 pub log: String,
117}
118
119impl Job {
120 fn describe(&self) -> String {
121 match self.exit_code {
122 Some(code) => format!("exited {code}"),
123 None => self.state.clone(),
124 }
125 }
126}
127
128#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
130pub struct JobNow {
131 pub id: String,
132 pub then: String,
135 pub now: String,
137}
138
139pub fn jobs_now(then: &[Job], now: &[Job]) -> (Vec<JobNow>, Vec<Drift>) {
143 let mut states = Vec::new();
144 let mut drift = Vec::new();
145 for j in then {
146 let current = now.iter().find(|n| n.id == j.id && n.pid == j.pid);
147 states.push(JobNow {
148 id: j.id.clone(),
149 then: j.describe(),
150 now: current.map_or_else(|| "gone".into(), Job::describe),
151 });
152 if j.state != "running" {
153 continue;
154 }
155 let message = match current {
156 Some(n) if n.state == "running" => continue,
157 Some(n) => format!(
158 "job `{}` has {} since; `jouet job logs {}` shows how it ended",
159 j.id,
160 match n.exit_code {
161 Some(code) => format!("exited {code}"),
162 None => format!("ended ({})", n.state),
163 },
164 j.id
165 ),
166 None => format!(
167 "job `{}` is no longer in this worktree, or was started again",
168 j.id
169 ),
170 };
171 drift.push(Drift {
172 code: "job_ended",
173 message,
174 });
175 }
176 (states, drift)
177}
178
179#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
181pub struct Daemon {
182 pub id: String,
184 pub status: String,
186 #[serde(default, skip_serializing_if = "Option::is_none")]
187 pub pid: Option<u32>,
188 #[serde(default, skip_serializing_if = "Vec::is_empty")]
189 pub port: Vec<u16>,
190 #[serde(default, skip_serializing_if = "Option::is_none")]
192 pub error: Option<String>,
193}
194
195impl Daemon {
196 pub fn alive(&self) -> bool {
198 matches!(
199 self.status.as_str(),
200 "running" | "waiting" | "stopping" | "restarting"
201 )
202 }
203
204 fn failed(&self) -> bool {
205 matches!(self.status.as_str(), "errored" | "failed")
206 }
207
208 fn describe(&self) -> String {
210 let mut s = self.status.clone();
211 if let Some(error) = &self.error {
212 let _ = write!(s, " ({error})");
213 }
214 if let Some(pid) = self.pid {
215 let _ = write!(s, ", pid {pid}");
216 }
217 if !self.port.is_empty() {
218 let ports: Vec<String> = self.port.iter().map(u16::to_string).collect();
219 let _ = write!(s, ", port {}", ports.join(", "));
220 }
221 s
222 }
223}
224
225#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
227pub struct DaemonNow {
228 pub id: String,
229 pub then: String,
231 pub now: String,
233 #[serde(skip_serializing_if = "Option::is_none")]
234 pub error: Option<String>,
235}
236
237pub fn daemons_now(then: &[Daemon], now: &[Daemon]) -> (Vec<DaemonNow>, Vec<Drift>) {
241 let mut states = Vec::new();
242 let mut drift = Vec::new();
243 for d in then {
244 let current = now.iter().find(|n| n.id == d.id);
245 states.push(DaemonNow {
246 id: d.id.clone(),
247 then: d.status.clone(),
248 now: current.map_or_else(|| "gone".into(), |n| n.status.clone()),
249 error: current.and_then(|n| n.error.clone()),
250 });
251 if !d.alive() {
252 continue;
253 }
254 let (code, message) = match current {
255 None => (
256 "daemon_gone",
257 format!("`{}` is no longer known to pitchfork", d.id),
258 ),
259 Some(n) if n.failed() => (
260 "daemon_failed",
261 format!(
262 "`{}` has {}; `pitchfork logs {} -n 50` shows why",
263 d.id,
264 n.describe(),
265 d.id
266 ),
267 ),
268 Some(n) if !n.alive() => ("daemon_stopped", format!("`{}` is {} now", d.id, n.status)),
269 Some(n) if n.pid.is_some() && d.pid.is_some() && n.pid != d.pid => (
270 "daemon_restarted",
271 format!(
272 "`{}` has restarted: pid {} then, {} now",
273 d.id,
274 d.pid.unwrap_or(0),
275 n.pid.unwrap_or(0)
276 ),
277 ),
278 Some(_) => continue,
279 };
280 drift.push(Drift { code, message });
281 }
282 (states, drift)
283}
284
285#[derive(Debug, Clone, Default)]
287pub struct Options {
288 pub session: Option<(PathBuf, String)>,
290 pub processes: bool,
292}
293
294pub fn default_path(git: &Git) -> Result<PathBuf, Error> {
298 Ok(git.git_dir()?.join("jouet").join("handoff.md"))
299}
300
301pub fn collect(git: &Git, opts: &Options) -> Result<Handoff, Error> {
304 let top = git.toplevel()?;
305 let mut h = git_facts(git, &top)?;
306 h.created_at = time::format_utc(time::now());
307 match &opts.session {
308 Some((dir, id)) => match session::last_checks(dir, id, &top) {
309 Some(runs) => h.checks = runs,
310 None => h.notes.push(format!(
311 "checks: none recorded for session {id} in this worktree (jouet setup's hooks record them)"
312 )),
313 },
314 None => h
315 .notes
316 .push("checks: no session ID, so no recorded test or lint runs".into()),
317 }
318 if opts.processes {
319 match procs::in_worktree(&top) {
320 Some(found) => h.processes = found,
321 None => h
322 .notes
323 .push("processes: not listed on this platform (Linux only)".into()),
324 }
325 }
326 Ok(h)
327}
328
329fn git_facts(git: &Git, top: &Path) -> Result<Handoff, Error> {
331 let status = git.text(&[
332 "status",
333 "--porcelain=v2",
334 "--branch",
335 "-z",
336 "--untracked-files=all",
337 ])?;
338 let mut h = Handoff {
339 worktree: top.display().to_string(),
340 ..Handoff::default()
341 };
342 let mut fields = nul_fields(&status);
343 while let Some(field) = fields.next() {
344 if let Some(header) = field.strip_prefix("# ") {
345 let (key, value) = header.split_once(' ').unwrap_or((header, ""));
346 match key {
347 "branch.oid" if value != "(initial)" => h.head = Some(value.into()),
348 "branch.head" if value != "(detached)" => h.branch = Some(value.into()),
349 "branch.upstream" => h.upstream = Some(value.into()),
350 "branch.ab" => {
351 let mut counts = value
352 .split(' ')
353 .map(|n| n.trim_start_matches(['+', '-']).parse().ok());
354 h.ahead = counts.next().flatten();
355 h.behind = counts.next().flatten();
356 }
357 _ => {}
358 }
359 continue;
360 }
361 let (kind, rest) = field.split_at(1);
362 let rest = rest.trim_start();
363 match kind {
364 "1" => h.changes.push(entry(rest, 6, None)),
365 "2" => {
366 let from = fields.next().map(str::to_string);
367 h.changes.push(entry(rest, 7, from));
368 }
369 "u" => h.changes.push(entry(rest, 8, None)),
370 "?" => h.untracked.push(rest.to_string()),
371 _ => {}
372 }
373 }
374 if h.head.is_some() {
375 h.head_subject = git.line(&["log", "-1", "--format=%s", "HEAD"]);
376 }
377 h.diff_sha256 = fingerprint(git)?;
378 h.operation = operation(&git.git_dir()?);
379 Ok(h)
380}
381
382fn fingerprint(git: &Git) -> Result<Option<String>, Error> {
388 let diff = ["diff", "--binary", "--no-ext-diff", "--no-color"];
389 let staged = git.text(&[&diff[..], &["--cached"]].concat())?;
390 let unstaged = git.text(&diff)?;
391 if staged.is_empty() && unstaged.is_empty() {
392 return Ok(None);
393 }
394 let mut hash = Sha256::new();
395 for (name, text) in [("staged", &staged), ("unstaged", &unstaged)] {
396 hash.update(format!("{name} {}\n", text.len()));
397 hash.update(text.as_bytes());
398 }
399 Ok(Some(hex(&hash.finalize())))
400}
401
402fn entry(rest: &str, fields: usize, from: Option<String>) -> Change {
405 let mut parts = rest.splitn(fields + 2, ' ');
406 let xy = parts.next().unwrap_or("..").replace('.', " ");
407 let path = parts.nth(fields).unwrap_or_default().to_string();
408 Change {
409 status: xy,
410 path,
411 from,
412 }
413}
414
415fn hex(bytes: &[u8]) -> String {
416 bytes.iter().map(|b| format!("{b:02x}")).collect()
417}
418
419fn operation(git_dir: &Path) -> Option<String> {
422 let has = |name: &str| git_dir.join(name).exists();
423 let op = if has("rebase-merge") || (has("rebase-apply") && !has("rebase-apply/applying")) {
424 "rebase"
425 } else if has("rebase-apply") {
426 "am"
427 } else if has("MERGE_HEAD") {
428 "merge"
429 } else if has("CHERRY_PICK_HEAD") {
430 "cherry-pick"
431 } else if has("REVERT_HEAD") {
432 "revert"
433 } else if has("BISECT_LOG") {
434 "bisect"
435 } else {
436 return None;
437 };
438 Some(op.into())
439}
440
441impl Handoff {
442 pub fn markdown(&self, data: bool) -> String {
444 let mut s = String::new();
445 let title = self.branch.as_deref().unwrap_or("detached HEAD");
446 let _ = writeln!(s, "# Handoff: {title}\n");
447 let _ = writeln!(s, "Written {} in `{}`.\n", self.created_at, self.worktree);
448 let mut branch = format!("- **Branch:** {title}");
449 if let Some(up) = &self.upstream {
450 let _ = write!(branch, ", tracking {up}");
451 if let (Some(a), Some(b)) = (self.ahead, self.behind) {
452 let _ = write!(branch, " ({a} ahead, {b} behind)");
453 }
454 } else {
455 branch.push_str(", no upstream");
456 }
457 let _ = writeln!(s, "{branch}");
458 match (&self.head, &self.head_subject) {
459 (Some(head), subject) => {
460 let _ = writeln!(
461 s,
462 "- **HEAD:** {} {}",
463 head.get(..12).unwrap_or(head),
464 subject.as_deref().unwrap_or("")
465 );
466 }
467 (None, _) => s.push_str("- **HEAD:** none yet (unborn branch)\n"),
468 }
469 if let Some(op) = &self.operation {
470 let _ = writeln!(s, "- **In progress:** a {op}");
471 }
472 match &self.pr {
473 Some(pr) => {
474 let _ = writeln!(
475 s,
476 "- **PR:** {}#{} ({}) {}: {}",
477 pr.repo, pr.number, pr.state, pr.url, pr.title
478 );
479 if pr.attention.is_empty() {
480 s.push_str(" - no attention codes\n");
481 }
482 for a in &pr.attention {
483 let _ = writeln!(s, " - `{}`: {}", a.code, a.message);
484 }
485 }
486 None => s.push_str("- **PR:** none found\n"),
487 }
488 if !self.checks.is_empty() {
489 s.push_str("- **Last checks:**\n");
490 for c in &self.checks {
491 let verdict = if c.exit_code == 0 { "passed" } else { "failed" };
492 let _ = writeln!(
493 s,
494 " - {} {verdict} (exit {}): `{}`",
495 c.kind, c.exit_code, c.command
496 );
497 }
498 }
499 let changes: Vec<String> = self
500 .changes
501 .iter()
502 .map(|c| match &c.from {
503 Some(from) => format!("`{}` {} (from {from})", c.status, c.path),
504 None => format!("`{}` {}", c.status, c.path),
505 })
506 .collect();
507 list(&mut s, "Uncommitted", &changes, data);
508 let untracked: Vec<String> = self.untracked.clone();
509 list(&mut s, "Untracked", &untracked, data);
510 let processes: Vec<String> = self
511 .processes
512 .iter()
513 .map(|p| format!("{} `{}`: attach with `{}`", p.pid, p.command, p.attach()))
514 .collect();
515 list(&mut s, "Background processes", &processes, data);
516 let jobs: Vec<String> = self
517 .jobs
518 .iter()
519 .map(|j| {
520 let follow = if j.state == "running" {
521 format!(", `jouet wait job {}`", j.id)
522 } else {
523 String::new()
524 };
525 format!(
526 "`{}` {}, pid {}: `{}`; `jouet job logs {}`{follow}",
527 j.id,
528 j.describe(),
529 j.pid,
530 j.command,
531 j.id
532 )
533 })
534 .collect();
535 list(&mut s, "Jobs", &jobs, data);
536 let daemons: Vec<String> = self
537 .daemons
538 .iter()
539 .map(|d| {
540 let follow = if d.alive() {
541 format!(", `jouet wait daemon {}`", d.id)
542 } else {
543 String::new()
544 };
545 format!(
546 "`{}` {}: `pitchfork logs {} -n 50`{follow}",
547 d.id,
548 d.describe(),
549 d.id
550 )
551 })
552 .collect();
553 list(&mut s, "pitchfork daemons", &daemons, data);
554 if !self.notes.is_empty() {
555 s.push_str("- **Not gathered:**\n");
556 for n in &self.notes {
557 let _ = writeln!(s, " - {n}");
558 }
559 }
560 if data {
561 let json = serde_json::to_string_pretty(self)
562 .expect("a handoff always serializes")
563 .replace("-->", "--\\u003e");
566 let _ = write!(s, "\n{DATA_OPEN}\n{json}\n{DATA_CLOSE}\n");
567 }
568 s
569 }
570}
571
572fn list(s: &mut String, heading: &str, items: &[String], data: bool) {
575 if items.is_empty() {
576 return;
577 }
578 let _ = writeln!(s, "- **{heading} ({}):**", items.len());
579 for item in items.iter().take(LIST_LIMIT) {
580 let _ = writeln!(s, " - {item}");
581 }
582 if items.len() > LIST_LIMIT {
583 let rest = items.len() - LIST_LIMIT;
584 let whole = if data {
585 "the data at the end of this file lists all of them"
586 } else {
587 "`jouet pickup --json` lists all of them"
588 };
589 let _ = writeln!(s, " - ... {rest} more ({whole})");
590 }
591}
592
593pub fn parse(text: &str) -> Result<Handoff, String> {
595 let json = if text.trim_start().starts_with('{') {
596 text
597 } else {
598 let start = text
599 .rfind(DATA_OPEN)
600 .ok_or("this is not a jouet handoff: it has no `<!-- jouet-handoff` data")?;
601 let body = &text[start + DATA_OPEN.len()..];
602 let end = body
603 .find(DATA_CLOSE)
604 .ok_or("the handoff's data is cut short: no closing `-->`")?;
605 &body[..end]
606 };
607 serde_json::from_str(json).map_err(|e| format!("reading the handoff's data: {e}"))
608}
609
610pub fn write(path: &Path, handoff: &Handoff) -> std::io::Result<()> {
612 let text = if path.extension().is_some_and(|e| e == "json") {
613 let mut json = serde_json::to_string_pretty(handoff)?;
614 json.push('\n');
615 json
616 } else {
617 handoff.markdown(true)
618 };
619 crate::write_atomic(path, &text)
620}
621
622#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
624pub struct Drift {
625 pub code: &'static str,
626 pub message: String,
627}
628
629pub fn drift(git: &Git, then: &Handoff) -> Result<Vec<Drift>, Error> {
632 let top = git.toplevel()?;
633 let now = git_facts(git, &top)?;
634 let mut out = Vec::new();
635 let mut add = |code, message: String| out.push(Drift { code, message });
636 if now.worktree != then.worktree {
637 add(
638 "worktree",
639 format!("written in {}, read in {}", then.worktree, now.worktree),
640 );
641 }
642 if now.branch != then.branch {
643 add(
644 "branch",
645 format!(
646 "the branch was {}, now {}",
647 then.branch.as_deref().unwrap_or("detached"),
648 now.branch.as_deref().unwrap_or("detached")
649 ),
650 );
651 }
652 if now.head != then.head {
653 let (code, message) = head_drift(git, then.head.as_deref(), now.head.as_deref());
654 add(code, message);
655 }
656 if now.operation != then.operation {
657 add(
658 "operation",
659 format!(
660 "the operation in progress was {}, now {}",
661 then.operation.as_deref().unwrap_or("none"),
662 now.operation.as_deref().unwrap_or("none")
663 ),
664 );
665 }
666 if now.upstream != then.upstream {
667 add(
668 "upstream",
669 format!(
670 "the upstream was {}, now {}",
671 then.upstream.as_deref().unwrap_or("none"),
672 now.upstream.as_deref().unwrap_or("none")
673 ),
674 );
675 } else if now.behind != then.behind {
676 add(
677 "behind",
678 format!(
679 "{} behind {}, was {}",
680 now.behind.unwrap_or(0),
681 now.upstream.as_deref().unwrap_or("the upstream"),
682 then.behind.unwrap_or(0)
683 ),
684 );
685 }
686 if now.changes != then.changes {
687 add("uncommitted", changed_files(&then.changes, &now.changes));
688 } else if now.diff_sha256 != then.diff_sha256 {
689 add(
690 "uncommitted",
691 "the uncommitted files are the same, but their staged or unstaged changes differ"
692 .into(),
693 );
694 }
695 let (before, after): (BTreeSet<_>, BTreeSet<_>) = (
696 then.untracked.iter().collect(),
697 now.untracked.iter().collect(),
698 );
699 if before != after {
700 let gone: Vec<String> = before.difference(&after).map(|p| (*p).clone()).collect();
701 let new: Vec<String> = after.difference(&before).map(|p| (*p).clone()).collect();
702 add("untracked", changed_sets("untracked", &new, &gone));
703 }
704 for p in &then.processes {
705 if procs::alive(p.pid) == Some(false) {
706 add(
707 "process_exited",
708 format!("{} `{}` has exited", p.pid, p.command),
709 );
710 }
711 }
712 Ok(out)
713}
714
715fn head_drift(git: &Git, then: Option<&str>, now: Option<&str>) -> (&'static str, String) {
716 let (Some(then), Some(now)) = (then, now) else {
717 return (
718 "head",
719 format!(
720 "HEAD was {}, now {}",
721 then.unwrap_or("unborn"),
722 now.unwrap_or("unborn")
723 ),
724 );
725 };
726 let short = |s: &str| s.get(..12).unwrap_or(s).to_string();
727 if git.commit_sha(then).is_none() {
728 return (
729 "head",
730 format!(
731 "HEAD was {}, which is not in this repository; now {}",
732 short(then),
733 short(now)
734 ),
735 );
736 }
737 if git.is_ancestor(then, now) {
738 let n = git.count(&format!("{then}..{now}")).unwrap_or(0);
739 return (
740 "head",
741 format!(
742 "{n} new {} since the handoff ({}..{})",
743 if n == 1 { "commit" } else { "commits" },
744 short(then),
745 short(now)
746 ),
747 );
748 }
749 if git.is_ancestor(now, then) {
750 let n = git.count(&format!("{now}..{then}")).unwrap_or(0);
751 return (
752 "head",
753 format!(
754 "HEAD moved back {n} {} to {} (it was {})",
755 if n == 1 { "commit" } else { "commits" },
756 short(now),
757 short(then)
758 ),
759 );
760 }
761 (
762 "head",
763 format!(
764 "HEAD was rewritten: it was {}, now {}, and neither contains the other",
765 short(then),
766 short(now)
767 ),
768 )
769}
770
771fn changed_files(then: &[Change], now: &[Change]) -> String {
774 let status = |list: &[Change], path: &str| {
775 list.iter()
776 .find(|c| c.path == path)
777 .map(|c| c.status.clone())
778 };
779 let paths: BTreeSet<&str> = then.iter().chain(now).map(|c| c.path.as_str()).collect();
780 let mut parts = Vec::new();
781 for path in paths {
782 match (status(then, path), status(now, path)) {
783 (None, Some(s)) => parts.push(format!("{path} is now changed (`{s}`)")),
784 (Some(_), None) => parts.push(format!("{path} no longer has changes")),
785 (Some(a), Some(b)) if a != b => {
786 parts.push(format!("{path} was `{a}`, now `{b}`"));
787 }
788 _ => {}
789 }
790 }
791 parts.join("; ")
792}
793
794fn changed_sets(what: &str, new: &[String], gone: &[String]) -> String {
795 let mut parts = Vec::new();
796 if !new.is_empty() {
797 parts.push(format!("now {what}: {}", new.join(", ")));
798 }
799 if !gone.is_empty() {
800 parts.push(format!("no longer {what}: {}", gone.join(", ")));
801 }
802 parts.join("; ")
803}
804
805#[cfg(test)]
806#[path = "handoff_tests.rs"]
807mod tests;