1use 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
23pub 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
65fn 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
79fn 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
91fn 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
108fn 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
119fn 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
165fn 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
232fn 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}