1use std::path::Path;
6use std::process::Command;
7
8use sandogasa_kojihub::{Client, Error, Value, retry};
9
10const DEFAULT_RETRIES: u32 = 3;
12
13pub const TASK_CLOSED: i64 = sandogasa_kojihub::hub::TASK_CLOSED;
18pub const TASK_FAILED: i64 = sandogasa_kojihub::hub::TASK_FAILED;
19
20pub struct KojiClient {
22 client: Client,
23 instance: String,
24}
25
26#[derive(Debug)]
28pub struct BuildInfo {
29 pub id: i64,
30 pub task_id: i64,
31 pub name: String,
32 pub version: String,
33 pub release: String,
34 pub nvr: String,
35 pub state: i64,
36}
37
38#[derive(Debug, Clone)]
40pub struct TaskInfo {
41 pub id: i64,
42 pub method: String,
43 pub arch: String,
44 pub state: i64,
45}
46
47impl TaskInfo {
48 pub fn state_name(&self) -> &'static str {
49 match self.state {
50 0 => "FREE",
51 1 => "OPEN",
52 2 => "CLOSED",
53 3 => "CANCELED",
54 4 => "ASSIGNED",
55 5 => "FAILED",
56 _ => "UNKNOWN",
57 }
58 }
59}
60
61impl KojiClient {
62 pub fn new(instance: &str) -> Self {
63 let hub_url = format!("https://{instance}/kojihub");
64 Self {
65 client: Client::new(&hub_url),
66 instance: instance.to_string(),
67 }
68 }
69
70 pub fn instance(&self) -> &str {
71 &self.instance
72 }
73
74 pub fn get_build(&self, build_id: i64) -> Result<BuildInfo, Error> {
76 let result = retry(DEFAULT_RETRIES, || {
77 self.client.call("getBuild", &[Value::Int(build_id)])
78 })?;
79 Ok(BuildInfo {
80 id: result
81 .get("id")
82 .and_then(|v| v.as_int())
83 .unwrap_or(build_id),
84 task_id: result
85 .get("task_id")
86 .and_then(|v| v.as_int())
87 .ok_or_else(|| Error::Parse("missing task_id in build info".into()))?,
88 name: result
89 .get("name")
90 .and_then(|v| v.as_str())
91 .unwrap_or("")
92 .to_string(),
93 version: result
94 .get("version")
95 .and_then(|v| v.as_str())
96 .unwrap_or("")
97 .to_string(),
98 release: result
99 .get("release")
100 .and_then(|v| v.as_str())
101 .unwrap_or("")
102 .to_string(),
103 nvr: result
104 .get("nvr")
105 .and_then(|v| v.as_str())
106 .unwrap_or("")
107 .to_string(),
108 state: result.get("state").and_then(|v| v.as_int()).unwrap_or(-1),
109 })
110 }
111
112 pub fn get_task_info(&self, task_id: i64) -> Result<TaskInfo, Error> {
114 let result = retry(DEFAULT_RETRIES, || {
115 self.client.call("getTaskInfo", &[Value::Int(task_id)])
116 })?;
117 Ok(TaskInfo {
118 id: result.get("id").and_then(|v| v.as_int()).unwrap_or(task_id),
119 method: result
120 .get("method")
121 .and_then(|v| v.as_str())
122 .unwrap_or("")
123 .to_string(),
124 arch: result
125 .get("arch")
126 .and_then(|v| v.as_str())
127 .unwrap_or("")
128 .to_string(),
129 state: result.get("state").and_then(|v| v.as_int()).unwrap_or(-1),
130 })
131 }
132
133 pub fn get_task_children(&self, task_id: i64) -> Result<Vec<TaskInfo>, Error> {
135 let result = retry(DEFAULT_RETRIES, || {
136 self.client.call("getTaskChildren", &[Value::Int(task_id)])
137 })?;
138 let items = result
139 .as_array()
140 .ok_or_else(|| Error::Parse("expected array for task children".into()))?;
141 items
142 .iter()
143 .map(|v| {
144 Ok(TaskInfo {
145 id: v
146 .get("id")
147 .and_then(|v| v.as_int())
148 .ok_or_else(|| Error::Parse("missing id in child task".into()))?,
149 method: v
150 .get("method")
151 .and_then(|v| v.as_str())
152 .unwrap_or("")
153 .to_string(),
154 arch: v
155 .get("arch")
156 .and_then(|v| v.as_str())
157 .unwrap_or("")
158 .to_string(),
159 state: v.get("state").and_then(|v| v.as_int()).unwrap_or(-1),
160 })
161 })
162 .collect()
163 }
164
165 pub fn resolve_build_arch_task(&self, task_id: i64, arch: &str) -> Result<TaskInfo, Error> {
170 let info = self.get_task_info(task_id)?;
171 if info.method == "buildArch" {
172 return Ok(info);
173 }
174
175 let children = self.get_task_children(task_id)?;
176 let arch_tasks: Vec<_> = children
177 .iter()
178 .filter(|t| t.method == "buildArch" && t.arch == arch)
179 .collect();
180
181 if arch_tasks.is_empty() {
182 let available: Vec<_> = children
183 .iter()
184 .filter(|t| t.method == "buildArch")
185 .map(|t| t.arch.as_str())
186 .collect();
187 return Err(Error::Parse(format!(
188 "no buildArch task for arch '{arch}' under task {task_id}; \
189 available: {}",
190 if available.is_empty() {
191 "(none)".to_string()
192 } else {
193 available.join(", ")
194 }
195 )));
196 }
197
198 Ok(arch_tasks[0].clone())
199 }
200
201 pub fn download_log(
205 &self,
206 task_id: i64,
207 filename: &str,
208 dest_dir: &Path,
209 ) -> Result<String, Error> {
210 let profile = self.koji_profile();
211 retry(DEFAULT_RETRIES, || {
212 let mut cmd = Command::new("koji");
213 if let Some(p) = profile {
214 cmd.arg("-p").arg(p);
215 }
216 let output = cmd
217 .arg("download-logs")
218 .arg("--dir")
219 .arg(dest_dir)
220 .arg(task_id.to_string())
221 .output()
222 .map_err(|e| Error::Parse(format!("failed to run koji download-logs: {e}")))?;
223 if !output.status.success() {
224 let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
225 return Err(Error::Parse(format!(
226 "koji download-logs {task_id} failed: {stderr}"
227 )));
228 }
229 Ok(())
230 })?;
231
232 let path = dest_dir.join(filename);
233 if path.exists() {
234 return std::fs::read_to_string(&path).map_err(|e| {
235 Error::Parse(format!("failed to read {filename} for task {task_id}: {e}"))
236 });
237 }
238
239 if let Some(found) = find_file_recursive(dest_dir, filename) {
242 return std::fs::read_to_string(&found)
243 .map_err(|e| Error::Parse(format!("failed to read {}: {e}", found.display())));
244 }
245
246 let mut files = Vec::new();
248 collect_files(dest_dir, &mut files);
249 Err(Error::Parse(format!(
250 "{filename} not found for task {task_id}\n\
251 koji download-logs produced: {}",
252 if files.is_empty() {
253 "(no files)".to_string()
254 } else {
255 files
256 .iter()
257 .map(|p| p.strip_prefix(dest_dir).unwrap_or(p).display().to_string())
258 .collect::<Vec<_>>()
259 .join(", ")
260 }
261 )))
262 }
263
264 pub fn download_build_log(
271 &self,
272 build: &BuildInfo,
273 arch: &str,
274 filename: &str,
275 ) -> Result<String, Error> {
276 let topurl = self.packages_url().ok_or_else(|| {
277 Error::Parse(format!(
278 "no known packages URL for instance {}",
279 self.instance
280 ))
281 })?;
282 let url = format!(
283 "{topurl}/packages/{name}/{version}/{release}/data/logs/{arch}/{filename}",
284 name = build.name,
285 version = build.version,
286 release = build.release,
287 );
288 retry(DEFAULT_RETRIES, || {
289 let response = reqwest::blocking::get(&url)
290 .map_err(|e| Error::Parse(format!("failed to fetch {url}: {e}")))?;
291 if !response.status().is_success() {
292 return Err(Error::Parse(format!("{url}: HTTP {}", response.status())));
293 }
294 response
295 .text()
296 .map_err(|e| Error::Parse(format!("failed to read {url}: {e}")))
297 })
298 }
299
300 fn packages_url(&self) -> Option<&'static str> {
302 match self.instance.as_str() {
303 "koji.fedoraproject.org" => Some("https://kojipkgs.fedoraproject.org"),
304 "cbs.centos.org" => Some("https://cbs.centos.org/kojifiles"),
305 "kojihub.stream.centos.org" => Some("https://kojihub.stream.centos.org/kojifiles"),
306 _ => None,
307 }
308 }
309
310 fn koji_profile(&self) -> Option<&'static str> {
312 match self.instance.as_str() {
313 "koji.fedoraproject.org" => None,
314 "cbs.centos.org" => Some("cbs"),
315 "kojihub.stream.centos.org" => Some("stream"),
316 _ => None,
317 }
318 }
319}
320
321pub fn find_file_in(dir: &Path, name: &str) -> Option<std::path::PathBuf> {
323 find_file_recursive(dir, name)
324}
325
326fn find_file_recursive(dir: &Path, name: &str) -> Option<std::path::PathBuf> {
327 let entries = std::fs::read_dir(dir).ok()?;
328 for entry in entries.flatten() {
329 let path = entry.path();
330 if path.is_file() && path.file_name().and_then(|n| n.to_str()) == Some(name) {
331 return Some(path);
332 }
333 if path.is_dir()
334 && let Some(found) = find_file_recursive(&path, name)
335 {
336 return Some(found);
337 }
338 }
339 None
340}
341
342fn collect_files(dir: &Path, out: &mut Vec<std::path::PathBuf>) {
344 if let Ok(entries) = std::fs::read_dir(dir) {
345 for entry in entries.flatten() {
346 let path = entry.path();
347 if path.is_file() {
348 out.push(path);
349 } else if path.is_dir() {
350 collect_files(&path, out);
351 }
352 }
353 }
354}