1use std::collections::BTreeMap;
9use std::path::Path;
10
11use serde::Serialize;
12
13use crate::resolved::EntryFormat;
14use crate::storage::{list_docs, ListDocsEntry, ListSource};
15
16const EMPTY_MESSAGE: &str = "No libraries declared in ask.json. Use `ask add npm:<pkg>` or `ask add github:<owner>/<repo> --ref <tag>` to get started.";
17
18#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
20#[serde(rename_all = "kebab-case")]
21pub enum ListEntrySource {
22 PmDriven,
23 Github,
24 Unresolved,
25}
26
27impl From<ListSource> for ListEntrySource {
28 fn from(s: ListSource) -> Self {
29 match s {
30 ListSource::PmDriven => ListEntrySource::PmDriven,
31 ListSource::Github => ListEntrySource::Github,
32 ListSource::Unresolved => ListEntrySource::Unresolved,
33 }
34 }
35}
36
37#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
39pub struct ListEntry {
40 pub name: String,
41 pub version: String,
42 pub format: EntryFormat,
43 pub source: ListEntrySource,
44 pub location: String,
45 #[serde(rename = "itemCount")]
46 pub item_count: u64,
47}
48
49#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
51pub struct ListConflict {
52 pub name: String,
53 pub versions: Vec<String>,
54}
55
56#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
58pub struct ListModel {
59 pub entries: Vec<ListEntry>,
60 pub conflicts: Vec<ListConflict>,
61 pub warnings: Vec<String>,
62}
63
64pub fn build_list_model(project_dir: &Path) -> ListModel {
66 let raw = list_docs(project_dir);
67 let conflicts = detect_conflicts(&raw);
68 let entries = raw
69 .into_iter()
70 .map(|e| ListEntry {
71 name: e.name,
72 version: e.version,
73 format: e.format,
74 source: e.source.into(),
75 location: e.location,
76 item_count: e.file_count,
77 })
78 .collect();
79 ListModel {
80 entries,
81 conflicts,
82 warnings: Vec::new(),
83 }
84}
85
86fn detect_conflicts(entries: &[ListDocsEntry]) -> Vec<ListConflict> {
88 let mut by_name: BTreeMap<String, std::collections::BTreeSet<String>> = BTreeMap::new();
89 for e in entries {
90 by_name
91 .entry(e.name.clone())
92 .or_default()
93 .insert(e.version.clone());
94 }
95 by_name
96 .into_iter()
97 .filter(|(_, versions)| versions.len() >= 2)
98 .map(|(name, versions)| ListConflict {
99 name,
100 versions: versions.into_iter().collect(),
101 })
102 .collect()
103}
104
105pub fn format_list(model: &ListModel) -> String {
107 if model.entries.is_empty() {
108 return EMPTY_MESSAGE.to_string();
109 }
110 let mut sections = vec![format_header(model), format_entry_table(&model.entries)];
111 if !model.conflicts.is_empty() {
112 sections.push(format_conflicts(model));
113 }
114 if !model.warnings.is_empty() {
115 let mut lines = vec!["Warnings:".to_string()];
116 lines.extend(model.warnings.iter().map(|w| format!(" {w}")));
117 sections.push(lines.join("\n"));
118 }
119 sections.join("\n\n")
120}
121
122fn format_header(model: &ListModel) -> String {
123 let docs = model
124 .entries
125 .iter()
126 .filter(|e| e.format == EntryFormat::Docs)
127 .count();
128 let intent = model
129 .entries
130 .iter()
131 .filter(|e| e.format == EntryFormat::IntentSkills)
132 .count();
133 let mut parts = vec![format!(
134 "{} {}",
135 model.entries.len(),
136 if model.entries.len() == 1 {
137 "entry"
138 } else {
139 "entries"
140 }
141 )];
142 if docs > 0 {
143 parts.push(format!("{docs} docs"));
144 }
145 if intent > 0 {
146 parts.push(format!("{intent} intent-skills"));
147 }
148 format!("Downloaded documentation: {}", parts.join(", "))
149}
150
151fn format_entry_table(entries: &[ListEntry]) -> String {
152 let headers = ["Name", "Version", "Format", "Source", "Items", "Location"];
153 let rows: Vec<Vec<String>> = entries
154 .iter()
155 .map(|e| {
156 vec![
157 e.name.clone(),
158 e.version.clone(),
159 format_enum(&e.format),
160 source_str(e.source).to_string(),
161 e.item_count.to_string(),
162 e.location.clone(),
163 ]
164 })
165 .collect();
166 format_table(&headers, &rows)
167}
168
169fn format_conflicts(model: &ListModel) -> String {
170 let mut lines = vec!["Conflicts:".to_string()];
171 for c in &model.conflicts {
172 lines.push(format!(" {}: {}", c.name, c.versions.join(", ")));
173 }
174 lines.join("\n")
175}
176
177fn format_enum(f: &EntryFormat) -> String {
178 match f {
179 EntryFormat::Docs => "docs".into(),
180 EntryFormat::IntentSkills => "intent-skills".into(),
181 }
182}
183
184fn source_str(s: ListEntrySource) -> &'static str {
185 match s {
186 ListEntrySource::PmDriven => "pm-driven",
187 ListEntrySource::Github => "github",
188 ListEntrySource::Unresolved => "unresolved",
189 }
190}
191
192fn format_table(headers: &[&str], rows: &[Vec<String>]) -> String {
194 if headers.is_empty() {
195 return String::new();
196 }
197 let widths: Vec<usize> = headers
198 .iter()
199 .enumerate()
200 .map(|(i, h)| {
201 let max_cell = rows
202 .iter()
203 .map(|r| r.get(i).map(|c| char_len(c)).unwrap_or(0))
204 .max()
205 .unwrap_or(0);
206 char_len(h).max(max_cell) + 2
207 })
208 .collect();
209
210 let mut lines = Vec::new();
211 lines.push(
212 headers
213 .iter()
214 .enumerate()
215 .map(|(i, h)| pad_column(h, widths[i]))
216 .collect::<String>(),
217 );
218 lines.push(widths.iter().map(|w| "─".repeat(*w)).collect::<String>());
219 for row in rows {
220 lines.push(
221 row.iter()
222 .enumerate()
223 .map(|(i, c)| pad_column(c, widths[i]))
224 .collect::<String>(),
225 );
226 }
227 lines.join("\n")
228}
229
230fn char_len(s: &str) -> usize {
231 s.chars().count()
232}
233
234fn pad_column(text: &str, width: usize) -> String {
235 let len = char_len(text);
236 if len >= width {
237 format!("{text} ")
238 } else {
239 format!("{text}{}", " ".repeat(width - len))
240 }
241}
242
243#[cfg(test)]
244mod tests {
245 use super::*;
246
247 fn write(project: &Path, ask: &str, resolved: Option<&str>) {
248 std::fs::create_dir_all(crate::io::get_ask_dir(project)).unwrap();
249 std::fs::write(crate::io::get_ask_json_path(project), ask).unwrap();
250 if let Some(r) = resolved {
251 std::fs::write(crate::io::get_resolved_json_path(project), r).unwrap();
252 }
253 }
254
255 #[test]
256 fn empty_model_renders_message() {
257 let dir = tempfile::tempdir().unwrap();
258 let model = build_list_model(dir.path());
259 assert!(model.entries.is_empty());
260 assert_eq!(format_list(&model), EMPTY_MESSAGE);
261 }
262
263 #[test]
264 fn table_and_header_render() {
265 let dir = tempfile::tempdir().unwrap();
266 write(
267 dir.path(),
268 r#"{"libraries":["npm:acme","github:o/other"]}"#,
269 Some(
270 r#"{"schemaVersion":1,"generatedAt":"2026-01-01T00:00:00Z","entries":{
271 "acme":{"spec":"npm:acme","resolvedVersion":"1.2.3",
272 "contentHash":"sha256-0000000000000000000000000000000000000000000000000000000000000000",
273 "fetchedAt":"2026-01-01T00:00:00Z","fileCount":3}}}"#,
274 ),
275 );
276 let model = build_list_model(dir.path());
277 let text = format_list(&model);
278 assert!(text.starts_with("Downloaded documentation: 2 entries, 2 docs"));
280 assert!(text.contains("Name"));
281 assert!(text.contains("acme"));
282 assert!(text.contains("unresolved"));
283 assert!(text.contains('─'));
285 }
286
287 #[test]
288 fn json_serialization_uses_schema_field_names() {
289 let model = ListModel {
290 entries: vec![ListEntry {
291 name: "acme".into(),
292 version: "1.0.0".into(),
293 format: EntryFormat::Docs,
294 source: ListEntrySource::PmDriven,
295 location: ".ask/docs/acme@1.0.0".into(),
296 item_count: 5,
297 }],
298 conflicts: vec![],
299 warnings: vec![],
300 };
301 let json = serde_json::to_string(&model).unwrap();
302 assert!(json.contains(r#""itemCount":5"#));
303 assert!(json.contains(r#""format":"docs""#));
304 assert!(json.contains(r#""source":"pm-driven""#));
305 }
306
307 #[test]
308 fn detects_version_conflicts() {
309 let raw = vec![
310 ListDocsEntry {
311 name: "acme".into(),
312 version: "1.0.0".into(),
313 format: EntryFormat::Docs,
314 source: ListSource::PmDriven,
315 spec: "npm:acme".into(),
316 location: "x".into(),
317 file_count: 1,
318 },
319 ListDocsEntry {
320 name: "acme".into(),
321 version: "2.0.0".into(),
322 format: EntryFormat::Docs,
323 source: ListSource::Github,
324 spec: "github:o/acme".into(),
325 location: "y".into(),
326 file_count: 1,
327 },
328 ];
329 let conflicts = detect_conflicts(&raw);
330 assert_eq!(conflicts.len(), 1);
331 assert_eq!(conflicts[0].versions, vec!["1.0.0", "2.0.0"]);
332 }
333}