Skip to main content

rbnx/cmd/
update.rs

1// SPDX-License-Identifier: MulanPSL-2.0
2//! `rbnx update` — pull remote (`url:`) providers to their latest upstream
3//! commit. Two modes, both gated on a y/N confirmation (or `--yes`) after an
4//! overview; `--check` prints the overview of a deploy and pulls nothing:
5//!
6//!   * deploy dir (cwd has `robonix_manifest.yaml`, or `-f <manifest>`):
7//!     update every cloned `url:` provider in that deploy.
8//!   * package dir (`-p <dir>`, or cwd is itself a git checkout): update just
9//!     that one repo.
10//!
11//! Equivalent to a `git pull` (fast-forward) of each checkout. Diverged
12//! checkouts are reported and skipped, never force-reset.
13
14use anyhow::Result;
15use std::io::{self, IsTerminal, Write};
16use std::path::{Path, PathBuf};
17use std::process::Command;
18
19use robonix_cli::{Config, output};
20
21use super::check_remotes::{self, RemoteProvider, RemoteStatus};
22
23/// Entry point for `rbnx update [-p <dir>] [-f <manifest>] [-y] [--check [--json]]`.
24pub async fn execute(
25    _config: Config,
26    path: Option<PathBuf>,
27    file: Option<PathBuf>,
28    yes: bool,
29    check: bool,
30    json: bool,
31) -> Result<()> {
32    if let Some(p) = path {
33        return update_single(&p, yes);
34    }
35    let manifest = match file {
36        Some(f) => f,
37        None => {
38            let cwd = std::env::current_dir()?;
39            let m = cwd.join("robonix_manifest.yaml");
40            if m.is_file() {
41                m
42            } else if check {
43                anyhow::bail!(
44                    "--check needs a deploy manifest: no robonix_manifest.yaml in {}; pass -f <manifest>",
45                    cwd.display()
46                );
47            } else if cwd.join(".git").is_dir() {
48                return update_single(&cwd, yes);
49            } else {
50                anyhow::bail!(
51                    "no robonix_manifest.yaml in {} and cwd is not a git checkout.\n\
52                     Run from a deploy dir, or pass -f <manifest> / -p <package dir>.",
53                    cwd.display()
54                );
55            }
56        }
57    };
58    if json {
59        println!("{}", check_json(&manifest)?);
60        return Ok(());
61    }
62    update_deploy(&manifest, yes, check)
63}
64
65/// Run git in `dir`, returning trimmed stdout on success.
66fn git(dir: &Path, args: &[&str]) -> Option<String> {
67    let out = Command::new("git")
68        .arg("-C")
69        .arg(dir)
70        .args(args)
71        .output()
72        .ok()?;
73    if !out.status.success() {
74        return None;
75    }
76    Some(String::from_utf8_lossy(&out.stdout).trim().to_string())
77}
78
79/// Fetch the remote branch tip into FETCH_HEAD (deepened so behind-counts work
80/// on the shallow clones boot creates). Returns false when fetch fails.
81fn fetch(dir: &Path, branch: &str) -> bool {
82    Command::new("git")
83        .arg("-C")
84        .arg(dir)
85        .args(["fetch", "--quiet", "--depth", "200", "origin", branch])
86        .status()
87        .map(|s| s.success())
88        .unwrap_or(false)
89}
90
91/// Ask before pulling. Without a terminal nobody can answer, so refuse rather
92/// than read whatever stdin holds.
93fn prompt_yes(question: &str, yes: bool) -> Result<bool> {
94    if yes {
95        return Ok(true);
96    }
97    if !io::stdin().is_terminal() {
98        anyhow::bail!("cannot ask for confirmation: stdin is not a terminal (pass --yes to pull)");
99    }
100    print!("{question} [y/N]: ");
101    io::stdout().flush()?;
102    let mut input = String::new();
103    io::stdin().read_line(&mut input)?;
104    let a = input.trim().to_lowercase();
105    Ok(a == "y" || a == "yes")
106}
107
108/// Fast-forward `dir` to FETCH_HEAD. Returns Ok(false) when it cannot (diverged).
109fn fast_forward(dir: &Path) -> Result<bool> {
110    let ok = Command::new("git")
111        .arg("-C")
112        .arg(dir)
113        .args(["merge", "--ff-only", "FETCH_HEAD"])
114        .status()?
115        .success();
116    Ok(ok)
117}
118
119/// Update a single package checkout (overview → confirm → fast-forward).
120fn update_single(dir: &Path, yes: bool) -> Result<()> {
121    if !dir.join(".git").is_dir() {
122        anyhow::bail!("{} is not a git checkout", dir.display());
123    }
124    let branch = git(dir, &["rev-parse", "--abbrev-ref", "HEAD"]).unwrap_or_else(|| "HEAD".into());
125    let local = git(dir, &["rev-parse", "--short", "HEAD"]).unwrap_or_default();
126
127    output::boot_section(&format!("update {}", dir.display()));
128    output::sub_step(&format!("branch {branch}  local {local}"));
129    output::action("fetch", "origin");
130    if !fetch(dir, &branch) {
131        anyhow::bail!("git fetch failed (offline?)");
132    }
133
134    let remote = git(dir, &["rev-parse", "--short", "FETCH_HEAD"]).unwrap_or_default();
135    if remote.is_empty() || remote == local {
136        output::success("already up to date");
137        return Ok(());
138    }
139    let behind = git(dir, &["rev-list", "--count", "HEAD..FETCH_HEAD"]);
140    let subject = git(dir, &["log", "-1", "--format=%s", "FETCH_HEAD"]).unwrap_or_default();
141    let date = git(
142        dir,
143        &["log", "-1", "--format=%cd", "--date=relative", "FETCH_HEAD"],
144    )
145    .unwrap_or_default();
146    output::sub_step(&format!(
147        "remote {remote} ({date}): {subject}{}",
148        behind
149            .map(|n| format!("   [{n} commit(s) behind]"))
150            .unwrap_or_default()
151    ));
152
153    if !prompt_yes("Pull to latest?", yes)? {
154        output::info("skipped");
155        return Ok(());
156    }
157    if fast_forward(dir)? {
158        output::success(&format!("updated → {remote}"));
159    } else {
160        anyhow::bail!("fast-forward failed — local checkout diverged; resolve manually");
161    }
162    Ok(())
163}
164
165/// Update every outdated cloned `url:` provider in a deploy manifest.
166fn update_deploy(manifest: &Path, yes: bool, check: bool) -> Result<()> {
167    let cloned: Vec<RemoteProvider> = check_remotes::collect_remote_providers(manifest)?
168        .into_iter()
169        .filter(|p| p.dir.join(".git").is_dir())
170        .collect();
171    if cloned.is_empty() {
172        output::info("no cloned remote providers in this deploy — nothing to update");
173        return Ok(());
174    }
175
176    output::boot_section(&format!("update remote providers — {}", manifest.display()));
177    let statuses: Vec<RemoteStatus> = cloned.iter().map(check_remotes::status_of).collect();
178    for st in &statuses {
179        let detail = match (&st.note, st.behind) {
180            (Some(note), _) => note.clone(),
181            (None, Some(0)) => "up to date".to_string(),
182            (None, Some(n)) => format!(
183                "{n} behind → {} ({}): {}",
184                output::short_sha(&st.remote_sha),
185                st.remote_date,
186                st.remote_subject
187            ),
188            (None, None) if st.outdated() => format!(
189                "behind → {} ({}): {}",
190                output::short_sha(&st.remote_sha),
191                st.remote_date,
192                st.remote_subject
193            ),
194            (None, None) => "up to date".to_string(),
195        };
196        output::boot_note(&st.name, &detail);
197    }
198
199    let outdated: Vec<&RemoteStatus> = statuses.iter().filter(|s| s.outdated()).collect();
200    if outdated.is_empty() {
201        output::success("all remote providers up to date");
202        return Ok(());
203    }
204    if check {
205        return Ok(());
206    }
207    if !prompt_yes(
208        &format!("Pull {} package(s) to latest?", outdated.len()),
209        yes,
210    )? {
211        output::info("skipped");
212        return Ok(());
213    }
214    for st in outdated {
215        output::action("pull", &st.name);
216        match fast_forward(&st.dir) {
217            Ok(true) => output::success(&format!(
218                "{} → {}",
219                st.name,
220                output::short_sha(&st.remote_sha)
221            )),
222            Ok(false) => output::warning(&format!(
223                "{}: fast-forward failed (diverged) — skipped",
224                st.name
225            )),
226            Err(e) => output::warning(&format!("{}: {e}", st.name)),
227        }
228    }
229    Ok(())
230}
231
232/// `--check --json`: every `url:` provider in the deploy, cloned or not.
233/// Unknown values are null.
234fn check_json(manifest: &Path) -> Result<serde_json::Value> {
235    let known = |s: &str| (!s.is_empty()).then(|| s.to_string());
236    let packages: Vec<_> = check_remotes::collect_remote_providers(manifest)?
237        .iter()
238        .map(|p| {
239            let st = check_remotes::status_of(p);
240            serde_json::json!({
241                "name": p.name,
242                "kind": p.kind,
243                "dir": p.dir,
244                "url": p.url,
245                "branch": p.branch,
246                "cloned": p.dir.join(".git").is_dir(),
247                "local_sha": known(&st.local_sha),
248                "remote_sha": known(&st.remote_sha),
249                "behind": st.behind,
250                "remote_date": known(&st.remote_date),
251                "remote_subject": known(&st.remote_subject),
252                "note": st.note,
253            })
254        })
255        .collect();
256    Ok(serde_json::json!({ "manifest": manifest, "packages": packages }))
257}
258
259#[cfg(test)]
260mod tests {
261    use super::*;
262
263    #[test]
264    fn check_json_lists_uncloned_provider() {
265        let dir = std::env::temp_dir().join(format!("rbnx-update-check-{}", std::process::id()));
266        std::fs::create_dir_all(&dir).unwrap();
267        let manifest = dir.join("robonix_manifest.yaml");
268        std::fs::write(
269            &manifest,
270            "service:\n  - name: map\n    url: https://example.com/org/service-map-rbnx.git\n",
271        )
272        .unwrap();
273
274        let report = check_json(&manifest).unwrap();
275        std::fs::remove_dir_all(&dir).unwrap();
276
277        let pkg = &report["packages"][0];
278        assert_eq!(report["packages"].as_array().unwrap().len(), 1);
279        assert_eq!(pkg["name"], "map");
280        assert_eq!(pkg["kind"], "service");
281        assert_eq!(pkg["url"], "https://example.com/org/service-map-rbnx.git");
282        assert_eq!(pkg["cloned"], false);
283        assert!(pkg["branch"].is_null());
284        assert!(pkg["local_sha"].is_null());
285        assert!(pkg["behind"].is_null());
286        assert!(pkg["note"].as_str().unwrap().contains("not cloned"));
287    }
288}
浙ICP备2023005800号-2 浙公网安备33010902005384号