Skip to main content

spec_driven_docs/commands/
track.rs

1//! `track` subcommand: runtime-shape.
2//!
3//! `status` reads the registry and reports freshness offline. `check` is the
4//! one network-enabled operation: it compares each pinned Git revision to its
5//! upstream through the `git` adapter and writes nothing. Registry parsing
6//! and freshness live in `services::tracking`; the network boundary lives in
7//! `adapters::git`.
8
9use camino::{Utf8Path, Utf8PathBuf};
10use jiff::civil::Date;
11
12use crate::adapters::git::{self, GitError};
13use crate::cli::track::{CheckArgs, StatusArgs, TrackArgs, TrackCommand};
14use crate::context::AppContext;
15use crate::error::AppError;
16use crate::gates::GateCtx;
17use crate::gates::paths::docs_root;
18use crate::output;
19use crate::services::tracking::{Freshness, evaluate, today_utc};
20
21/// Dispatch `sdd track`.
22///
23/// # Errors
24///
25/// [`AppError`] per the operation: usage errors, I/O, a `git` failure, or
26/// [`AppError::Violations`] when `--fail-on-update` sees a moved revision.
27pub fn run(ctx: &AppContext, args: TrackArgs) -> Result<(), AppError> {
28    match args.command {
29        TrackCommand::Status(a) => status(ctx, a),
30        TrackCommand::Check(a) => check(ctx, a),
31    }
32}
33
34fn resolve(ctx: &AppContext, target: &Utf8Path) -> Result<Utf8PathBuf, AppError> {
35    if target.is_absolute() {
36        Ok(target.to_path_buf())
37    } else if target == "." {
38        Ok(ctx.cwd.clone())
39    } else {
40        Err(AppError::Usage("target must be absolute or .".to_string()))
41    }
42}
43
44// sdd: permanent the match states the two clock sources side by side
45#[allow(clippy::option_if_let_else)]
46fn as_of(value: Option<&str>) -> Result<Date, AppError> {
47    match value {
48        None => Ok(today_utc()),
49        Some(text) => text
50            .parse::<Date>()
51            .map_err(|_| AppError::Usage(format!("--as-of is not an ISO date: {text}"))),
52    }
53}
54
55fn git_error(error: &GitError) -> AppError {
56    let code = match error {
57        GitError::Unsupported(_) => 64,
58        GitError::MissingGit | GitError::Transport(_) => 69,
59        GitError::Malformed => 65,
60        GitError::Timeout => 75,
61    };
62    AppError::Git {
63        message: error.to_string(),
64        code,
65    }
66}
67
68fn status(ctx: &AppContext, args: StatusArgs) -> Result<(), AppError> {
69    let StatusArgs {
70        target,
71        as_of: as_of_arg,
72        json,
73    } = args;
74    let target = resolve(ctx, &target)?;
75    let root = docs_root(&GateCtx::new(target.clone()));
76    let report = evaluate(&target, &root, as_of(as_of_arg.as_deref())?)?;
77
78    if let Some(fatal) = &report.fatal {
79        return Err(AppError::ManifestInvalid(fatal.detail.clone()));
80    }
81
82    if json {
83        let entries: Vec<serde_json::Value> = report
84            .entries
85            .iter()
86            .map(|a| {
87                let state = match a.freshness {
88                    Some(Freshness::Current) => "current",
89                    Some(Freshness::Overdue(_)) => "overdue",
90                    None => "invalid",
91                };
92                serde_json::json!({
93                    "id": a.entry.id,
94                    "state": state,
95                    "next_check": a.next_check.map(|d| d.to_string()),
96                    "revision": a.entry.source.as_ref().map(|s| s.revision.clone()),
97                    "revalidate": a.entry.revalidate,
98                })
99            })
100            .collect();
101        return output::json(&serde_json::json!({ "ok": true, "tracked": entries }));
102    }
103
104    for a in &report.entries {
105        let state = match a.freshness {
106            Some(Freshness::Current) => "current".to_string(),
107            Some(Freshness::Overdue(days)) => format!("overdue by {days} day(s)"),
108            None => "invalid date".to_string(),
109        };
110        let next = a
111            .next_check
112            .map_or_else(|| "-".to_string(), |d| d.to_string());
113        output::line(format!("{}: {state}; next check {next}", a.entry.id));
114        if let Some(source) = &a.entry.source {
115            output::line(format!(
116                "  pinned {} at {}",
117                source.reference, source.revision
118            ));
119        }
120        if !matches!(a.freshness, Some(Freshness::Current)) {
121            for step in &a.entry.revalidate {
122                output::line(format!("  revalidate: {step}"));
123            }
124        }
125    }
126    Ok(())
127}
128
129fn check(ctx: &AppContext, args: CheckArgs) -> Result<(), AppError> {
130    let target = resolve(ctx, &args.target)?;
131    let root = docs_root(&GateCtx::new(target.clone()));
132    let report = evaluate(&target, &root, today_utc())?;
133    if let Some(fatal) = &report.fatal {
134        return Err(AppError::ManifestInvalid(fatal.detail.clone()));
135    }
136
137    let mut results = Vec::new();
138    let mut moved = false;
139    let mut matched = false;
140    for a in &report.entries {
141        if args.id.as_deref().is_some_and(|id| id != a.entry.id) {
142            continue;
143        }
144        let Some(source) = &a.entry.source else {
145            continue;
146        };
147        matched = true;
148        let observed =
149            git::ls_remote(&source.repository, &source.reference).map_err(|e| git_error(&e))?;
150        let (state, observed_str) = match observed {
151            None => ("missing-reference", String::new()),
152            Some(sha) if sha == source.revision => ("current", sha),
153            Some(sha) => {
154                moved = true;
155                ("moved", sha)
156            }
157        };
158        results.push((
159            a.entry.id.clone(),
160            source.revision.clone(),
161            state,
162            observed_str,
163        ));
164    }
165
166    if args.id.is_some() && !matched {
167        return Err(AppError::Usage(format!(
168            "no tracked Git entry with id {}",
169            args.id.unwrap_or_default()
170        )));
171    }
172
173    if args.json {
174        let entries: Vec<serde_json::Value> = results
175            .iter()
176            .map(|(id, pinned, state, observed)| {
177                serde_json::json!({
178                    "id": id,
179                    "pinned": pinned,
180                    "state": state,
181                    "observed": if observed.is_empty() { serde_json::Value::Null } else { serde_json::Value::String(observed.clone()) },
182                })
183            })
184            .collect();
185        output::json(&serde_json::json!({ "ok": true, "checked": entries }))?;
186    } else {
187        for (id, pinned, state, observed) in &results {
188            match *state {
189                "current" => output::line(format!("{id}: current at {pinned}")),
190                "moved" => output::line(format!("{id}: moved from {pinned} to {observed}")),
191                _ => output::line(format!(
192                    "{id}: reference missing upstream (pinned {pinned})"
193                )),
194            }
195        }
196    }
197
198    if args.fail_on_update && moved {
199        return Err(AppError::Violations {
200            count: results.iter().filter(|(_, _, s, _)| *s == "moved").count(),
201        });
202    }
203    Ok(())
204}