1use std::collections::{BTreeMap, BTreeSet};
19use std::path::{Path, PathBuf};
20
21use crate::error::{CoreError, ErrorCode};
22use crate::fs::Fs;
23use crate::layering::{Project, ProjectRepo, same_path};
24use crate::model::applied::Scope;
25use crate::model::clients::ClientSelection;
26use crate::model::ids::{self, IdKind};
27use crate::model::skill_meta::{SkillEnable, SkillMeta, SkillSource, SkillSourceKind};
28use crate::skills::classify::{self, EntryClass};
29use crate::skills::hash_cache::{FolderHashCache, Summary};
30use crate::skills::link::{self, CLIENT_SKILLS, Replacement, SyncReport};
31use crate::skills::{
32 SKILL_FILE, SkillFiles, SkillsEnv, content_hash, frontmatter, read_folder, store,
33};
34use crate::store::{self as store_mod, CommitId, Operation, Store, Transaction};
35
36#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct FoundFolder {
39 pub client: &'static str,
40 pub path: PathBuf,
41}
42
43#[derive(Debug, Clone)]
46pub struct Variant {
47 pub hash: String,
49 pub folders: Vec<FoundFolder>,
51 pub in_store: bool,
53 pub description: Option<String>,
55 pub bytes: u64,
56 files: Option<SkillFiles>,
59}
60
61impl Variant {
62 pub fn clients(&self) -> impl Iterator<Item = &'static str> + '_ {
64 self.folders.iter().map(|folder| folder.client)
65 }
66}
67
68#[derive(Debug, Clone)]
70pub struct Candidate {
71 pub name: String,
73 pub variants: Vec<Variant>,
74}
75
76impl Candidate {
77 pub fn is_conflict(&self) -> bool {
80 self.variants.len() > 1
81 }
82
83 pub fn variant(&self, hash: &str) -> Option<&Variant> {
84 self.variants.iter().find(|variant| variant.hash == hash)
85 }
86}
87
88#[derive(Debug, Clone)]
91pub struct FolderProblem {
92 pub client: &'static str,
93 pub name: String,
94 pub path: PathBuf,
95 pub error: CoreError,
96}
97
98#[derive(Debug, Clone)]
100pub struct UnmanagedScan {
101 pub scope: Scope,
102 pub candidates: Vec<Candidate>,
104 pub problems: Vec<FolderProblem>,
105}
106
107impl UnmanagedScan {
108 pub fn candidate(&self, name: &str) -> Option<&Candidate> {
109 self.candidates
110 .iter()
111 .find(|candidate| candidate.name == name)
112 }
113}
114
115#[derive(Debug, Clone, PartialEq, Eq)]
117pub enum AdoptAction {
118 Pick {
121 variant: String,
122 },
123 Both {
126 primary: String,
127 },
128 Skip,
129}
130
131#[derive(Debug, Clone, PartialEq, Eq)]
132pub struct AdoptChoice {
133 pub name: String,
134 pub action: AdoptAction,
135}
136
137#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139pub enum FolderStatus {
140 Adopted,
142 Differs,
144 Conflict,
146 Skipped,
148 Kept,
151}
152
153impl FolderStatus {
154 pub const fn as_str(self) -> &'static str {
155 match self {
156 FolderStatus::Adopted => "adopted",
157 FolderStatus::Differs => "differs",
158 FolderStatus::Conflict => "conflict",
159 FolderStatus::Skipped => "skipped",
160 FolderStatus::Kept => "kept",
161 }
162 }
163}
164
165#[derive(Debug, Clone)]
166pub struct FolderResult {
167 pub client: &'static str,
168 pub name: String,
169 pub path: PathBuf,
170 pub skill_id: Option<String>,
172 pub status: FolderStatus,
173 pub trash: Option<PathBuf>,
175 pub error: Option<CoreError>,
176}
177
178#[derive(Debug, Clone, Default)]
180pub struct AdoptReport {
181 pub commit: Option<CommitId>,
182 pub added: Vec<String>,
184 pub reused: Vec<String>,
186 pub folders: Vec<FolderResult>,
187 pub problems: Vec<FolderProblem>,
189 pub sync: SyncReport,
191}
192
193impl AdoptReport {
194 pub fn needs_attention(&self) -> bool {
197 self.sync.needs_attention()
198 || self
199 .folders
200 .iter()
201 .any(|folder| matches!(folder.status, FolderStatus::Conflict | FolderStatus::Kept))
202 }
203}
204
205pub fn scan(
209 store: Option<&Store<'_>>,
210 sx: &SkillsEnv<'_>,
211 scope: Scope,
212 project: Option<&Path>,
213 client: Option<&str>,
214) -> Result<UnmanagedScan, CoreError> {
215 scan_with(store, sx, scope, project, client, None)
216}
217
218pub fn scan_cached(
223 store: Option<&Store<'_>>,
224 sx: &SkillsEnv<'_>,
225 scope: Scope,
226 project: Option<&Path>,
227 client: Option<&str>,
228 cache: &FolderHashCache,
229) -> Result<UnmanagedScan, CoreError> {
230 scan_with(store, sx, scope, project, client, Some(cache))
231}
232
233struct Read {
236 summary: Summary,
237 files: Option<SkillFiles>,
238}
239
240fn read(fs: &dyn Fs, dir: &Path, cache: Option<&FolderHashCache>) -> Result<Read, CoreError> {
241 match cache {
242 Some(cache) => Ok(Read {
243 summary: cache.summary(fs, dir)?,
244 files: None,
245 }),
246 None => {
247 let files = read_folder(fs, dir)?;
248 Ok(Read {
249 summary: Summary::of(&files),
250 files: Some(files),
251 })
252 }
253 }
254}
255
256fn scan_with(
257 store: Option<&Store<'_>>,
258 sx: &SkillsEnv<'_>,
259 scope: Scope,
260 project: Option<&Path>,
261 client: Option<&str>,
262 cache: Option<&FolderHashCache>,
263) -> Result<UnmanagedScan, CoreError> {
264 if let Some(client) = client {
265 link::skills_dir(sx.env, client, scope, project)?;
266 }
267 let mut groups: BTreeMap<String, Vec<(FoundFolder, Read)>> = BTreeMap::new();
268 let mut problems = Vec::new();
269 let repo = match (scope, project) {
271 (Scope::Project | Scope::ProjectLocal, Some(root)) => ProjectRepo::discover(root)?,
272 _ => None,
273 };
274 for dir in classify::scan(sx, scope, project)? {
275 if client.is_some_and(|client| client != dir.client) {
276 continue;
277 }
278 for entry in dir.entries {
279 if entry.class != EntryClass::Unmanaged || !sx.fs.is_dir(&entry.path) {
280 continue;
281 }
282 let problem = |error: CoreError| FolderProblem {
283 client: dir.client,
284 name: entry.name.clone(),
285 path: entry.path.clone(),
286 error,
287 };
288 if !ids::is_valid(IdKind::Skill, &entry.name) {
289 problems.push(problem(
290 CoreError::new(
291 ErrorCode::InvalidId,
292 format!(
293 "{:?} is not a skill id (lower-case letters, digits and `-`), so \
294 the folder cannot be replaced by a link of that name; import it \
295 under another id instead",
296 entry.name
297 ),
298 )
299 .with_path(&entry.path),
300 ));
301 continue;
302 }
303 if let Some(repo) = &repo
304 && repo.tracks_any_under(&entry.path)?
305 {
306 problems.push(problem(
307 CoreError::new(
308 ErrorCode::InvalidValue,
309 "the project's repository tracks files in this folder (teammates get it \
310 from there), so it is not adopted",
311 )
312 .with_path(&entry.path),
313 ));
314 continue;
315 }
316 match read(sx.fs, &entry.path, cache) {
317 Ok(found) if found.summary.has_skill_file => {
318 groups.entry(entry.name.clone()).or_default().push((
319 FoundFolder {
320 client: dir.client,
321 path: entry.path.clone(),
322 },
323 found,
324 ));
325 }
326 Ok(_) => problems.push(problem(store::missing_skill_file(&entry.path))),
327 Err(err) => problems.push(problem(err)),
328 }
329 }
330 }
331 let mut candidates = Vec::new();
332 for (name, found) in groups {
333 let mut variants: Vec<Variant> = Vec::new();
334 for (folder, found) in found {
335 match variants
336 .iter_mut()
337 .find(|variant| variant.hash == found.summary.hash)
338 {
339 Some(variant) => variant.folders.push(folder),
340 None => variants.push(variant(found, vec![folder])),
341 }
342 }
343 if let Some(store) = store {
344 match stored(store, &name, cache)? {
345 Stored::Absent => {}
346 Stored::WithoutContent => {
347 for variant in variants {
351 for folder in variant.folders {
352 problems.push(FolderProblem {
353 client: folder.client,
354 name: name.clone(),
355 error: CoreError::new(
356 ErrorCode::AlreadyExists,
357 format!(
358 "skill {name:?} is in the store without content; remove \
359 it or import the folder under another id"
360 ),
361 )
362 .with_path(&folder.path),
363 path: folder.path,
364 });
365 }
366 }
367 continue;
368 }
369 Stored::Content(found) => {
370 match variants
371 .iter_mut()
372 .find(|variant| variant.hash == found.summary.hash)
373 {
374 Some(variant) => variant.in_store = true,
375 None => {
376 let mut stored = variant(found, Vec::new());
377 stored.in_store = true;
378 variants.push(stored);
379 }
380 }
381 }
382 }
383 }
384 candidates.push(Candidate { name, variants });
385 }
386 Ok(UnmanagedScan {
387 scope,
388 candidates,
389 problems,
390 })
391}
392
393enum Stored {
395 Absent,
396 WithoutContent,
399 Content(Read),
400}
401
402fn stored(
403 store: &Store<'_>,
404 id: &str,
405 cache: Option<&FolderHashCache>,
406) -> Result<Stored, CoreError> {
407 let fs = store.fs();
408 let dir = store::content_dir(store, id)?;
409 match crate::skills::entry(fs, &dir)? {
410 crate::skills::Entry::Dir => Ok(match read(fs, &dir, cache) {
411 Ok(found) => Stored::Content(found),
412 Err(_) => Stored::WithoutContent,
413 }),
414 crate::skills::Entry::Missing if !fs.exists(&store.path(&store::meta_path(id)?)?) => {
415 Ok(Stored::Absent)
416 }
417 _ => Ok(Stored::WithoutContent),
418 }
419}
420
421fn variant(found: Read, folders: Vec<FoundFolder>) -> Variant {
422 Variant {
423 hash: found.summary.hash,
424 folders,
425 in_store: false,
426 description: found.summary.description,
427 bytes: found.summary.bytes,
428 files: found.files,
429 }
430}
431
432pub fn default_choices(scan: &UnmanagedScan) -> Vec<AdoptChoice> {
434 scan.candidates
435 .iter()
436 .filter(|candidate| !candidate.is_conflict())
437 .map(|candidate| AdoptChoice {
438 name: candidate.name.clone(),
439 action: AdoptAction::Pick {
440 variant: candidate.variants[0].hash.clone(),
441 },
442 })
443 .collect()
444}
445
446struct Wanted<'a> {
448 id: String,
450 renamed: bool,
453 variant: &'a Variant,
454 display_name: String,
456}
457
458pub fn adopt(
466 store: &Store<'_>,
467 sx: &SkillsEnv<'_>,
468 scope: Scope,
469 project: Option<&Path>,
470 client: Option<&str>,
471 choices: &[AdoptChoice],
472) -> Result<AdoptReport, CoreError> {
473 let project = match scope {
474 Scope::User => None,
475 Scope::Project | Scope::ProjectLocal => {
476 let folder = project.ok_or_else(|| {
477 CoreError::new(
478 ErrorCode::InvalidPath,
479 "a project scope needs an absolute folder",
480 )
481 })?;
482 Some(link::trusted_project(store, sx, folder)?)
483 }
484 };
485 let root = project.as_ref().map(|project| project.root.as_path());
486 let scan = scan(Some(store), sx, scope, root, client)?;
487 for choice in choices {
488 if choice.action != AdoptAction::Skip && scan.candidate(&choice.name).is_none() {
489 return Err(changed(format!(
490 "there is no unmanaged skill folder {:?} any more",
491 choice.name
492 )));
493 }
494 }
495
496 let mut report = AdoptReport {
497 problems: scan.problems.clone(),
498 ..AdoptReport::default()
499 };
500 let mut wanted: Vec<Wanted<'_>> = Vec::new();
501 for candidate in &scan.candidates {
502 let action = choices
503 .iter()
504 .find(|choice| choice.name == candidate.name)
505 .map(|choice| &choice.action);
506 let (primary, both) = match action {
507 Some(AdoptAction::Pick { variant }) => (variant, false),
508 Some(AdoptAction::Both { primary }) => (primary, true),
509 None | Some(AdoptAction::Skip) => {
510 let status = if action.is_none() && candidate.is_conflict() {
511 FolderStatus::Conflict
512 } else {
513 FolderStatus::Skipped
514 };
515 for variant in &candidate.variants {
516 report.folders.extend(
517 variant
518 .folders
519 .iter()
520 .map(|folder| result(candidate, folder, None, status)),
521 );
522 }
523 continue;
524 }
525 };
526 let chosen = candidate.variant(primary).ok_or_else(|| {
527 changed(format!(
528 "the chosen content of {:?} is in no folder any more",
529 candidate.name
530 ))
531 })?;
532 if candidate
533 .variants
534 .iter()
535 .any(|variant| variant.in_store && variant.hash != chosen.hash)
536 {
537 return Err(CoreError::new(
538 ErrorCode::InvalidValue,
539 format!(
540 "skill {:?} is in the store with other content; pick the store's copy, or \
541 keep it and import the folders as {:?}-<client>",
542 candidate.name, candidate.name
543 ),
544 ));
545 }
546 if !chosen.folders.is_empty() {
548 wanted.push(Wanted {
549 id: candidate.name.clone(),
550 renamed: false,
551 variant: chosen,
552 display_name: display_name(&candidate.name, chosen),
553 });
554 }
555 for other in candidate
556 .variants
557 .iter()
558 .filter(|variant| variant.hash != chosen.hash)
559 {
560 match other.folders.first() {
561 Some(first) if both => {
562 let id = format!("{}-{}", candidate.name, first.client);
563 ids::check(IdKind::Skill, &id)?;
564 wanted.push(Wanted {
565 id,
566 renamed: true,
567 variant: other,
568 display_name: display_name(&candidate.name, other),
569 });
570 }
571 _ => report.folders.extend(
572 other
573 .folders
574 .iter()
575 .map(|folder| result(candidate, folder, None, FolderStatus::Differs)),
576 ),
577 }
578 }
579 }
580 if wanted.is_empty() {
581 sort_folders(&mut report.folders);
582 return Ok(report);
583 }
584
585 let mut resolved: Vec<(String, bool)> = Vec::new();
587 for item in &wanted {
588 resolved.push(resolve_id(store, sx.fs, item, &resolved)?);
589 }
590 let ids: Vec<&str> = resolved.iter().map(|(id, _)| id.as_str()).collect();
591 let mut operation = Operation::new("skill.adopt", summary(&ids, project.as_ref()));
592 for id in &ids {
593 operation = operation.entity(format!("skill/{id}"));
594 }
595 let staging = |tx: &mut Transaction<'_>| stage(tx, scope, &wanted, &resolved);
596 let committed = match &project {
597 None => store.transaction(operation, staging)?,
598 Some(project) => {
599 let (mut text, path) = link::skills_file_text(project)?;
600 for id in &ids {
601 if let Some(edited) = link::edit_manifest(&text, id, true, &path)? {
602 text = edited;
603 }
604 }
605 let operation = operation
606 .entity(format!("project/{}", project.id))
607 .scope(store_mod::Scope::Project(project.id.clone()));
608 link::commit_project_edit(store, sx, project, &text, None, operation, staging)?
609 }
610 };
611 report.commit = committed.commit;
612 for (id, new) in &resolved {
613 if *new {
614 report.added.push(id.clone());
615 } else if !report.reused.contains(id) {
616 report.reused.push(id.clone());
617 }
618 }
619
620 let mut replacements: Vec<Replacement> = Vec::new();
624 let mut aliases: Vec<(&'static str, usize)> = Vec::new();
625 for (item, (id, _)) in wanted.iter().zip(&resolved) {
626 for folder in &item.variant.folders {
627 if let Some(first) = replacements
628 .iter()
629 .position(|known| same_path(&known.folder, &folder.path))
630 {
631 aliases.push((folder.client, first));
632 continue;
633 }
634 let dir = link::skills_dir(sx.env, folder.client, scope, root)?;
635 replacements.push(Replacement {
636 client: folder.client,
637 folder: folder.path.clone(),
638 entry: dir.join(id),
639 skill_id: id.clone(),
640 });
641 }
642 }
643 let replaced = link::replace_folders(store, sx, &replacements)?;
644 let mut results: Vec<FolderResult> = Vec::new();
645 for (replacement, outcome) in replacements.iter().zip(replaced) {
646 let name = replacement
647 .folder
648 .file_name()
649 .map(|name| name.to_string_lossy().into_owned())
650 .unwrap_or_default();
651 let (status, trash, error) = match outcome {
652 Ok(trash) => (FolderStatus::Adopted, Some(trash), None),
653 Err(err) => (FolderStatus::Kept, None, Some(err)),
654 };
655 results.push(FolderResult {
656 client: replacement.client,
657 name,
658 path: replacement.folder.clone(),
659 skill_id: Some(replacement.skill_id.clone()),
660 status,
661 trash,
662 error,
663 });
664 }
665 for (client, first) in aliases {
667 let shared = FolderResult {
668 client,
669 ..results[first].clone()
670 };
671 results.push(shared);
672 }
673 report.folders.extend(results);
674 report.sync = link::sync(store, sx)?;
675 sort_folders(&mut report.folders);
676 Ok(report)
677}
678
679fn sort_folders(folders: &mut [FolderResult]) {
681 let order = |client: &str| {
682 CLIENT_SKILLS
683 .iter()
684 .position(|entry| entry.client == client)
685 };
686 folders.sort_by(|a, b| {
687 (a.name.as_str(), order(a.client)).cmp(&(b.name.as_str(), order(b.client)))
688 });
689}
690
691fn changed(why: String) -> CoreError {
692 CoreError::new(
693 ErrorCode::EntryChanged,
694 format!("{why}; scan the skill folders again"),
695 )
696}
697
698fn result(
699 candidate: &Candidate,
700 folder: &FoundFolder,
701 skill_id: Option<String>,
702 status: FolderStatus,
703) -> FolderResult {
704 FolderResult {
705 client: folder.client,
706 name: candidate.name.clone(),
707 path: folder.path.clone(),
708 skill_id,
709 status,
710 trash: None,
711 error: None,
712 }
713}
714
715fn display_name(name: &str, variant: &Variant) -> String {
716 variant
717 .files
718 .as_ref()
719 .and_then(|files| files.get(SKILL_FILE))
720 .and_then(|text| {
721 frontmatter::parse(&String::from_utf8_lossy(text))
722 .ok()
723 .flatten()
724 })
725 .and_then(|fm| fm.name().map(str::to_owned))
726 .unwrap_or_else(|| name.to_owned())
727}
728
729fn resolve_id(
734 store: &Store<'_>,
735 fs: &dyn crate::fs::Fs,
736 item: &Wanted<'_>,
737 earlier: &[(String, bool)],
738) -> Result<(String, bool), CoreError> {
739 if item.variant.in_store {
740 return Ok((item.id.clone(), false));
741 }
742 let taken = |id: &str| earlier.iter().any(|(known, _)| known == id);
743 let same = |id: &str| -> Result<Option<bool>, CoreError> {
744 Ok(match store::get(store, id)? {
745 None => None,
746 Some(skill) => Some(
747 skill.has_content
748 && store::read_content(store, id)
752 .is_ok_and(|content| content_hash(&content) == item.variant.hash),
753 ),
754 })
755 };
756 if !item.renamed {
757 return match same(&item.id)? {
759 None if !taken(&item.id) => Ok((item.id.clone(), true)),
760 _ => Err(changed(format!(
761 "skill {:?} was added to the store meanwhile",
762 item.id
763 ))),
764 };
765 }
766 for n in 1..1000 {
767 let id = if n == 1 {
768 item.id.clone()
769 } else {
770 format!("{}-{n}", item.id)
771 };
772 if !ids::is_valid(IdKind::Skill, &id) || taken(&id) {
773 continue;
774 }
775 let mut on_disk = false;
776 for folder in &item.variant.folders {
777 if let Some(dir) = folder.path.parent() {
778 on_disk |=
779 crate::skills::entry(fs, &dir.join(&id))? != crate::skills::Entry::Missing;
780 }
781 }
782 if on_disk {
783 continue;
784 }
785 match same(&id)? {
786 None => return Ok((id, true)),
787 Some(true) => return Ok((id, false)),
788 Some(false) => {}
789 }
790 }
791 Err(CoreError::new(
792 ErrorCode::AlreadyExists,
793 format!("no free id for skill {:?}", item.id),
794 ))
795}
796
797fn summary(ids: &[&str], project: Option<&Project>) -> String {
798 let what = if ids.len() <= 3 {
799 ids.join(", ")
800 } else {
801 format!("{} skills", ids.len())
802 };
803 match project {
804 Some(project) => format!("skill: adopt {what} in project {}", project.id),
805 None => format!("skill: adopt {what}"),
806 }
807}
808
809fn stage(
812 tx: &mut Transaction<'_>,
813 scope: Scope,
814 wanted: &[Wanted<'_>],
815 resolved: &[(String, bool)],
816) -> Result<(), CoreError> {
817 for (item, (id, new)) in wanted.iter().zip(resolved) {
818 let mut meta = if *new {
819 if store::exists(tx, id)? {
820 return Err(changed(format!(
821 "skill {id:?} was added to the store meanwhile"
822 )));
823 }
824 let files = item
825 .variant
826 .files
827 .as_ref()
828 .ok_or_else(|| changed(format!("the content of skill {id:?} was not read")))?;
829 store::stage_content(tx, id, files)?;
830 let mut meta = SkillMeta::new(id);
831 meta.name = Some(item.display_name.clone());
832 meta.source = Some(SkillSource {
833 kind: SkillSourceKind::Local,
834 url: None,
835 path: None,
836 git_ref: None,
837 commit: None,
838 catalog: None,
839 extra: toml::Table::new(),
840 });
841 meta
842 } else {
843 store::read_meta(tx, id)?.unwrap_or_else(|| SkillMeta::new(id))
844 };
845 if scope == Scope::User {
846 let enable = meta.enable.get_or_insert_with(SkillEnable::default);
847 enable.clients = with_clients(enable.clients.take(), item.variant.clients());
848 }
849 store::stage_meta(tx, &meta)?;
850 }
851 Ok(())
852}
853
854fn with_clients<'a>(
856 current: Option<ClientSelection>,
857 clients: impl Iterator<Item = &'a str>,
858) -> Option<ClientSelection> {
859 let mut list: BTreeSet<String> = match current {
860 Some(ClientSelection::AllDetected) => return Some(ClientSelection::AllDetected),
861 Some(ClientSelection::List(ids)) => ids.into_iter().collect(),
862 None => BTreeSet::new(),
863 };
864 list.extend(clients.map(str::to_owned));
865 Some(ClientSelection::List(list.into_iter().collect()))
866}