1use anyhow::{Context, Result};
12use robonix_cli::config::Config;
13use robonix_cli::output;
14use serde_yaml::Value;
15use std::io::{self, BufRead, Write};
16use std::path::{Path, PathBuf};
17
18use super::run_package;
19
20fn prompt_sudo_retry(failed: Vec<(PathBuf, std::io::Error)>) -> Result<()> {
25 if failed.is_empty() {
26 return Ok(());
27 }
28 eprintln!();
29 eprintln!("These paths could not be removed (likely docker-build root-owned files):");
30 for (p, e) in &failed {
31 eprintln!(" ✗ {} : {}", p.display(), e);
32 }
33 eprintln!();
34 eprint!(
35 "Retry with `sudo rm -rf` for the {} path(s) above? [y/N] ",
36 failed.len()
37 );
38 io::stderr().flush().ok();
39 let mut line = String::new();
40 io::stdin().lock().read_line(&mut line)?;
41 let yes = matches!(line.trim().to_ascii_lowercase().as_str(), "y" | "yes");
42 if !yes {
43 anyhow::bail!(
44 "{} path(s) skipped (run `sudo rm -rf <path>` manually if needed)",
45 failed.len()
46 );
47 }
48 let mut cmd = std::process::Command::new("sudo");
49 cmd.arg("rm").arg("-rf");
50 for (p, _) in &failed {
51 cmd.arg(p);
52 }
53 let status = cmd
54 .status()
55 .context("failed to spawn sudo (is it installed?)")?;
56 if !status.success() {
57 anyhow::bail!("sudo rm exited with {:?}", status.code());
58 }
59 Ok(())
60}
61
62pub async fn execute(
63 config: Config,
64 package: Option<PathBuf>,
65 file: Option<PathBuf>,
66 cache: bool,
67 sessions: bool,
68 llm_metrics: bool,
69) -> Result<()> {
70 let wipe = Wipe {
71 cache,
72 sessions,
73 llm_metrics,
74 };
75 match (package, file) {
76 (Some(_), Some(_)) => {
77 anyhow::bail!("pass one of -p / -f, not both")
78 }
79 (Some(pkg), None) => clean_package(&pkg),
80 (None, Some(f)) => clean_deploy(&config, &f, &wipe),
81 (None, None) => {
82 let cwd = std::env::current_dir().context("get cwd")?;
87 let deploy = cwd.join("robonix_manifest.yaml");
88 if deploy.is_file() {
89 return clean_deploy(&config, &deploy, &wipe);
90 }
91 match run_package::find_package_from_cwd() {
92 Ok(pkg) => clean_package(&pkg),
93 Err(_) => anyhow::bail!(
94 "no robonix_manifest.yaml in {} and no package_manifest.yaml in any parent. \
95 Pass `-f <manifest>` (deploy) or `-p <pkg>` (package).",
96 cwd.display()
97 ),
98 }
99 }
100 }
101}
102
103fn clean_package(pkg: &Path) -> Result<()> {
104 let pkg = pkg
105 .canonicalize()
106 .with_context(|| format!("not a directory: {}", pkg.display()))?;
107 let build = pkg.join("rbnx-build");
108 if !build.exists() {
109 output::sub_step(&format!(
110 "nothing to clean: {} (no rbnx-build/)",
111 pkg.display()
112 ));
113 return Ok(());
114 }
115 output::action("Cleaning", &build.display().to_string());
116 if let Err(e) = std::fs::remove_dir_all(&build) {
117 return prompt_sudo_retry(vec![(build, e)]);
121 }
122 Ok(())
123}
124
125struct Wipe {
127 cache: bool,
129 sessions: bool,
131 llm_metrics: bool,
133}
134
135fn clean_deploy(config: &Config, manifest_path: &Path, wipe: &Wipe) -> Result<()> {
136 let manifest_path = manifest_path
137 .canonicalize()
138 .with_context(|| format!("manifest not found: {}", manifest_path.display()))?;
139 let manifest_dir = manifest_path
140 .parent()
141 .context("deploy manifest has no parent directory")?
142 .to_path_buf();
143 let raw = std::fs::read_to_string(&manifest_path)
144 .with_context(|| format!("read {}", manifest_path.display()))?;
145 let root: Value =
146 serde_yaml::from_str(&raw).with_context(|| format!("parse {}", manifest_path.display()))?;
147 let cache_root = manifest_dir.join("rbnx-boot").join("cache");
148
149 output::action("Cleaning deploy", &manifest_path.display().to_string());
150
151 let mut pkgs: Vec<PathBuf> = Vec::new();
153 for section in &["primitive", "service", "skill"] {
154 let Some(seq) = root.get(*section).and_then(|v| v.as_sequence()) else {
155 continue;
156 };
157 for entry in seq {
158 let local = entry.get("path").and_then(|v| v.as_str());
159 let url = entry.get("url").and_then(|v| v.as_str());
160 match (local, url) {
161 (Some(p), _) => pkgs.push(manifest_dir.join(p)),
162 (None, Some(u)) => pkgs.push(cache_root.join(super::deploy::repo_dir_name(u))),
165 _ => {}
166 }
167 }
168 }
169 if let Some(map) = root.get("system").and_then(|v| v.as_mapping())
172 && let Some(source_root) = config.robonix_source_path.as_ref()
173 {
174 for (key, _) in map {
175 let Some(k) = key.as_str() else { continue };
176 if super::deploy::is_builtin_system(k) {
177 continue;
178 }
179 let pkg = source_root.join("system").join(k);
180 if pkg.exists() {
181 pkgs.push(pkg);
182 }
183 }
184 }
185
186 output::step("packages", &format!("{} to inspect", pkgs.len()));
189 let mut failed: Vec<(PathBuf, std::io::Error)> = Vec::new();
190 for p in &pkgs {
191 if !p.exists() {
192 continue;
193 }
194 let build = p.join("rbnx-build");
195 if build.exists() {
196 output::sub_step(&format!("rm -rf {}", build.display()));
197 if let Err(e) = std::fs::remove_dir_all(&build) {
198 failed.push((build, e));
199 }
200 }
201 }
202
203 let rbnx_boot = manifest_dir.join("rbnx-boot");
210 if rbnx_boot.exists() {
211 if let Ok(entries) = std::fs::read_dir(&rbnx_boot) {
212 for entry in entries.flatten() {
213 let path = entry.path();
214 let name = entry.file_name();
215 let is_cache = name == "cache";
216 if is_cache && !wipe.cache {
217 output::sub_step(&format!("keep {} (use --cache to wipe)", path.display()));
218 continue;
219 }
220 if name == "sessions" && !wipe.sessions {
221 output::sub_step(&format!("keep {} (use --sessions to wipe)", path.display()));
222 continue;
223 }
224 if name == "llm-metrics" && !wipe.llm_metrics {
225 output::sub_step(&format!(
226 "keep {} (use --llm-metrics to wipe)",
227 path.display()
228 ));
229 continue;
230 }
231 let label = if is_cache { " (cache)" } else { "" };
232 let kind = entry.file_type().ok();
233 if kind.map(|k| k.is_dir()).unwrap_or(false) {
234 output::sub_step(&format!("rm -rf {}{}", path.display(), label));
235 if let Err(e) = std::fs::remove_dir_all(&path) {
236 failed.push((path, e));
237 }
238 } else {
239 output::sub_step(&format!("rm {}{}", path.display(), label));
240 if let Err(e) = std::fs::remove_file(&path) {
241 failed.push((path, e));
242 }
243 }
244 }
245 }
246 let _ = std::fs::remove_dir(&rbnx_boot);
249 }
250
251 prompt_sudo_retry(failed)
252}