1use anyhow::{Context, Result};
16use std::path::{Path, PathBuf};
17use std::process::Command;
18
19use robonix_cli::output;
20
21#[derive(Debug, Clone)]
23pub struct RemoteProvider {
24 pub name: String,
25 pub kind: &'static str,
27 pub url: String,
28 pub branch: Option<String>,
29 pub dir: PathBuf,
31}
32
33#[derive(Debug, Clone)]
35pub struct RemoteStatus {
36 pub name: String,
37 pub dir: PathBuf,
38 pub behind: Option<u32>,
41 pub local_sha: String,
42 pub remote_sha: String,
43 pub remote_date: String,
44 pub remote_subject: String,
45 pub note: Option<String>,
47}
48
49impl RemoteStatus {
50 pub fn outdated(&self) -> bool {
53 self.behind.map(|b| b > 0).unwrap_or(false)
54 || (!self.remote_sha.is_empty() && self.remote_sha != self.local_sha)
55 }
56}
57
58fn git(dir: &Path, args: &[&str]) -> Option<String> {
60 let out = Command::new("git")
61 .arg("-C")
62 .arg(dir)
63 .args(args)
64 .output()
65 .ok()?;
66 if !out.status.success() {
67 return None;
68 }
69 let s = String::from_utf8(out.stdout).ok()?.trim().to_string();
70 Some(s)
71}
72
73fn origin_url(dir: &Path) -> Option<String> {
74 git(dir, &["config", "--get", "remote.origin.url"]).filter(|s| !s.trim().is_empty())
75}
76
77pub fn collect_remote_providers(manifest_path: &Path) -> Result<Vec<RemoteProvider>> {
79 let raw = std::fs::read_to_string(manifest_path)
80 .with_context(|| format!("read deploy manifest {}", manifest_path.display()))?;
81 let doc: serde_yaml::Value = serde_yaml::from_str(&raw)
82 .with_context(|| format!("parse deploy manifest {}", manifest_path.display()))?;
83
84 let manifest_dir = manifest_path.parent().unwrap_or_else(|| Path::new("."));
85 let cache_root = manifest_dir.join("rbnx-boot").join("cache");
86
87 let mut providers = Vec::new();
88 for section in ["primitive", "service", "skill"] {
89 let Some(entries) = doc.get(section).and_then(|v| v.as_sequence()) else {
90 continue;
91 };
92 for entry in entries {
93 if entry.get("status").and_then(|v| v.as_str()) == Some("disabled") {
95 continue;
96 }
97 let Some(url) = entry.get("url").and_then(|v| v.as_str()) else {
98 continue; };
100 let name = entry
101 .get("name")
102 .and_then(|v| v.as_str())
103 .map(|s| s.to_string())
104 .filter(|s| !s.is_empty())
105 .unwrap_or_else(|| {
106 url.trim_end_matches(".git")
107 .rsplit('/')
108 .next()
109 .unwrap_or("pkg")
110 .to_string()
111 });
112 let branch = entry
113 .get("branch")
114 .and_then(|v| v.as_str())
115 .map(|s| s.to_string());
116 providers.push(RemoteProvider {
117 dir: cache_root.join(super::deploy::repo_dir_name(url)),
120 name,
121 kind: section,
122 url: url.to_string(),
123 branch,
124 });
125 }
126 }
127 Ok(providers)
128}
129
130fn target_branch(p: &RemoteProvider) -> String {
133 if let Some(b) = &p.branch {
134 return b.clone();
135 }
136 git(&p.dir, &["rev-parse", "--abbrev-ref", "origin/HEAD"])
137 .and_then(|s| s.rsplit('/').next().map(|s| s.to_string()))
138 .unwrap_or_else(|| "main".to_string())
139}
140
141pub fn status_of(p: &RemoteProvider) -> RemoteStatus {
144 let mut st = RemoteStatus {
145 name: p.name.clone(),
146 dir: p.dir.clone(),
147 behind: None,
148 local_sha: String::new(),
149 remote_sha: String::new(),
150 remote_date: String::new(),
151 remote_subject: String::new(),
152 note: None,
153 };
154
155 if !p.dir.join(".git").is_dir() {
156 st.note = Some("not cloned yet (will clone on next boot/build)".into());
157 return st;
158 }
159
160 st.local_sha = git(&p.dir, &["rev-parse", "HEAD"]).unwrap_or_default();
161 if origin_url(&p.dir).is_none() {
162 st.note = Some("local checkout has no origin remote — skipped".into());
163 return st;
164 }
165 let branch = target_branch(p);
166
167 let sources = origin_url(&p.dir)
181 .map(|url| super::run_package::url_candidates(&url))
182 .unwrap_or_else(|| vec!["origin".into()]);
183 let fetch = |source: &str| {
184 let fetch_args = [
185 "-C",
186 p.dir.to_str().unwrap_or("."),
187 "-c",
188 "http.lowSpeedLimit=1000",
189 "-c",
190 "http.lowSpeedTime=8",
191 "fetch",
192 "--quiet",
193 "--depth",
194 "200",
195 source,
196 &branch,
197 ];
198 let timed = Command::new("timeout")
202 .arg("6")
203 .arg("git")
204 .args(fetch_args)
205 .status();
206 match timed {
207 Ok(s) => s.success(),
208 Err(_) => Command::new("git")
210 .args(fetch_args)
211 .status()
212 .map(|s| s.success())
213 .unwrap_or(false),
214 }
215 };
216 let fetched = sources.iter().any(|source| fetch(source));
217 if !fetched {
218 st.note = Some("git fetch timed out / failed (offline?) — skipped".into());
219 return st;
220 }
221
222 let remote_ref = "FETCH_HEAD";
223 st.remote_sha = git(&p.dir, &["rev-parse", remote_ref]).unwrap_or_default();
224 st.remote_date = git(
225 &p.dir,
226 &["log", "-1", "--format=%cd", "--date=relative", remote_ref],
227 )
228 .unwrap_or_default();
229 st.remote_subject = git(&p.dir, &["log", "-1", "--format=%s", remote_ref]).unwrap_or_default();
230 st.behind = git(
231 &p.dir,
232 &["rev-list", "--count", &format!("HEAD..{remote_ref}")],
233 )
234 .and_then(|s| s.parse::<u32>().ok());
235 st
236}
237
238pub fn report_outdated(manifest_path: &Path) {
241 let providers = match collect_remote_providers(manifest_path) {
242 Ok(p) => p,
243 Err(_) => return,
244 };
245 let remote: Vec<_> = providers
246 .into_iter()
247 .filter(|p| p.dir.join(".git").is_dir())
248 .collect();
249 if remote.is_empty() {
250 return;
251 }
252
253 output::boot_section("checking remote providers for updates (skip: --no-update-check)");
259 let mut outdated = Vec::new();
260 for p in &remote {
261 if origin_url(&p.dir).is_none() {
262 let st = status_of(p);
263 output::boot_skip(
264 &p.name,
265 st.note
266 .as_deref()
267 .unwrap_or("local checkout has no origin remote — skipped"),
268 );
269 continue;
270 }
271 output::boot_progress(&p.name, "fetching origin…", 0);
272 let st = status_of(p);
273 if st.outdated() {
274 let behind = match st.behind {
275 Some(n) => format!("{n} behind"),
276 None => "behind".to_string(),
277 };
278 output::boot_update_avail(
279 &p.name,
280 &format!(
281 "{behind}; remote {} ({}): {}",
282 output::short_sha(&st.remote_sha),
283 st.remote_date,
284 st.remote_subject
285 ),
286 );
287 outdated.push(st);
288 } else if let Some(note) = &st.note {
289 output::boot_skip(&p.name, note);
292 } else {
293 output::boot_ok(&p.name, "up to date");
294 }
295 }
296
297 if outdated.is_empty() {
299 output::sub_step(&format!(
300 "{} remote provider(s) up to date — nothing to update",
301 remote.len()
302 ));
303 return;
304 }
305 output::sub_step(&format!(
306 "{} of {} provider(s) have updates available:",
307 outdated.len(),
308 remote.len()
309 ));
310 output::info(&format!(
311 "update all: rbnx update -f {}",
312 manifest_path.display()
313 ));
314 output::info("update one: cd <pkg dir> && rbnx update (or: rbnx update -p <pkg dir>)");
315}