sklink 0.2.1

Install skills into platform directories via a local store and symlinks
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
mod config;
mod error;
mod init;
mod install;
mod path_utils;
mod skills;
mod store;

use clap::{CommandFactory, Parser};
use clap_complete::{generate, Shell};
use std::collections::HashSet;
use std::path::Path;
use std::path::PathBuf;

use crate::error::AppError;

#[derive(Parser, Debug)]
#[command(name = "sklink")]
#[command(
    about = "Install skills into platform directories via local store and symlinks",
    long_about = "Install skills (directories) into a local store and then link them into configured platform target directories.\n\nLocal store: ~/.config/sklink/skills\nConfig file: ~/.config/sklink/config.toml\n\nRules:\n- Skills are copied into the local store before linking\n- If a local store skill already exists: error unless --force is used\n- If link does not exist: create\n- If link exists and points to expected target: skip\n- Otherwise (file/dir or wrong target): error",
    after_help = "Tip: when using cargo run, pass CLI args after `--`.\nExamples:\n  cargo run -- --help\n  cargo run -- init\n  cargo run -- list\n  cargo run -- list --installed\n  cargo run -- -p all\n  cargo run -- -i software-engineer -p kimi\n  cargo run -- --force -i software-engineer -p kimi",
    args_conflicts_with_subcommands = true,
    subcommand_precedence_over_arg = true
)]
struct Cli {
    #[command(subcommand)]
    command: Option<Commands>,

    #[arg(
        short = 'i',
        long = "install",
        value_name = "SKILL|PATH",
        help = "Skill name or path to a skill directory (repeatable). Omit to install all discovered skills"
    )]
    skills: Vec<String>,

    #[arg(
        short = 'p',
        long = "platform",
        value_name = "PLATFORM|all",
        help = "Target platform name or all"
    )]
    platform: Option<String>,

    #[arg(long, help = "Overwrite existing skill in local store")]
    force: bool,
}

#[derive(clap::Subcommand, Debug)]
enum Commands {
    Init {
        #[arg(long, help = "Overwrite config if it already exists")]
        force: bool,
    },
    List {
        #[arg(long, help = "Show installed skills across configured targets")]
        installed: bool,
    },
    Completions {
        #[arg(value_enum)]
        shell: Shell,
    },
}

fn main() {
    let cli = Cli::parse();
    if let Err(err) = run(cli) {
        print_error(&err);
        std::process::exit(1);
    }
}

fn run(cli: Cli) -> Result<(), AppError> {
    let cwd = std::env::current_dir().map_err(AppError::Io)?;
    if let Some(cmd) = cli.command {
        return match cmd {
            Commands::Init { force } => {
                let path = init::init_config(&cwd, init::InitOptions { force })?;
                println!("created config: {}", display_path(&path));
                Ok(())
            }
            Commands::List { installed } => {
                if installed {
                    return list_installed(&cwd);
                }
                list_available(&cwd)
            }
            Commands::Completions { shell } => {
                let mut cmd = Cli::command();
                generate(shell, &mut cmd, "sklink", &mut std::io::stdout());
                Ok(())
            }
        };
    }

    let config = config::load_default_config()?;
    let store_dir = store::default_store_dir(&cwd)?;
    std::fs::create_dir_all(&store_dir).map_err(|e| AppError::CreateDir {
        dir: store_dir.clone(),
        source: e,
    })?;
    let store_dir = std::fs::canonicalize(&store_dir).map_err(AppError::Io)?;

    let repo_skills_dir = skills::detect_repo_skills_dir(&cwd).ok();

    let source_skills = if cli.skills.is_empty() {
        let dir = repo_skills_dir.clone().unwrap_or_else(|| store_dir.clone());
        skills::discover_skills(&dir)?
    } else {
        resolve_requested_skills(
            repo_skills_dir.as_deref(),
            &store_dir,
            &cwd,
            &cli.skills,
            cli.force,
        )?
    };

    let mut selected_skills = Vec::new();
    let is_bulk_install = cli.skills.is_empty();
    for source in source_skills {
        let src = std::fs::canonicalize(&source.dir).map_err(AppError::Io)?;
        let expected_store = store_dir.join(&source.name);
        let src_is_store = src == expected_store;
        let store_exists = expected_store.exists();

        let dir = if src_is_store {
            src
        } else if is_bulk_install && store_exists && !cli.force {
            expected_store
        } else if !is_bulk_install && store_exists && !cli.force {
            return Err(AppError::StoreSkillAlreadyExists {
                skill: source.name,
                path: expected_store,
            });
        } else {
            store::stage_skill_to_store(&store_dir, &source.name, &src, cli.force)?
        };
        selected_skills.push(skills::SkillDir {
            name: source.name,
            dir,
        });
    }

    let platform = cli.platform.unwrap_or_else(|| "all".to_string());
    let platform_names: Vec<String> = if platform == "all" {
        let mut names: Vec<String> = config.platforms.keys().cloned().collect();
        names.sort();
        names
    } else {
        if !config.platforms.contains_key(&platform) {
            let mut names: Vec<String> = config.platforms.keys().cloned().collect();
            names.sort();
            return Err(AppError::PlatformNotFound {
                platform,
                available: names.join(", "),
            });
        }
        vec![platform]
    };

    for platform_name in platform_names {
        let Some(platform) = config.platforms.get(&platform_name) else {
            eprintln!("warning: platform not found: {platform_name}");
            continue;
        };

        for target in &platform.targets {
            let target_dir = path_utils::resolve_path(&target.dir, &cwd)?;
            let meta = match std::fs::metadata(&target_dir) {
                Ok(m) => m,
                Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
                    eprintln!(
                        "warning: target dir not found (skipped): platform={platform_name} dir={}",
                        display_path(&target_dir)
                    );
                    continue;
                }
                Err(err) => {
                    eprintln!(
                        "warning: failed to read target dir (skipped): platform={platform_name} dir={} err={err}",
                        display_path(&target_dir)
                    );
                    continue;
                }
            };
            if !meta.is_dir() {
                eprintln!(
                    "warning: target path is not a directory (skipped): platform={platform_name} dir={}",
                    display_path(&target_dir)
                );
                continue;
            }

            for skill in &selected_skills {
                let link_path = target_dir.join(&skill.name);
                match install::ensure_correct_symlink(&link_path, &skill.dir)? {
                    install::InstallOutcome::Created => {
                        println!(
                            "created {} -> {}",
                            display_path(&link_path),
                            display_path(&skill.dir)
                        );
                    }
                    install::InstallOutcome::Skipped => {
                        println!("skipped {}", display_path(&link_path));
                    }
                }
            }
        }
    }

    Ok(())
}

fn list_available(cwd: &Path) -> Result<(), AppError> {
    let store_dir = store::default_store_dir(cwd)?;

    let skills_dir = skills::detect_repo_skills_dir(cwd).unwrap_or(store_dir);
    let skills = skills::discover_skills(&skills_dir)?;
    for skill in skills {
        println!("{}", skill.name);
    }
    Ok(())
}

fn resolve_requested_skills(
    repo_skills_dir: Option<&Path>,
    store_dir: &Path,
    cwd: &Path,
    requested: &[String],
    prefer_repo: bool,
) -> Result<Vec<skills::SkillDir>, AppError> {
    let mut seen = HashSet::new();
    let mut out = Vec::new();

    for raw in requested {
        let (name, raw_dir) = if looks_like_path(raw) {
            let dir = path_utils::resolve_path(raw, cwd)?;
            let name = dir
                .file_name()
                .map(|s| s.to_string_lossy().to_string())
                .ok_or_else(|| AppError::SkillNotFound {
                    skill: raw.clone(),
                    path: dir.clone(),
                    source: std::io::Error::other("missing directory name"),
                })?;
            (name, dir)
        } else {
            let repo_candidate = repo_skills_dir.map(|d| d.join(raw));
            if prefer_repo && repo_candidate.as_ref().is_some_and(|d| d.is_dir()) {
                (raw.clone(), repo_candidate.unwrap())
            } else {
                let store_candidate = store_dir.join(raw);
                if store_candidate.is_dir() {
                    (raw.clone(), store_candidate)
                } else if let Some(repo_candidate) = repo_candidate {
                    (raw.clone(), repo_candidate)
                } else {
                    return Err(AppError::SkillNotFound {
                        skill: raw.clone(),
                        path: store_candidate,
                        source: std::io::Error::new(
                            std::io::ErrorKind::NotFound,
                            "skill not found in local store and repo skills dir not found",
                        ),
                    });
                }
            }
        };

        if !seen.insert(name.clone()) {
            continue;
        }

        validate_skill_dir(raw, &raw_dir)?;
        let dir = std::fs::canonicalize(&raw_dir).map_err(|e| AppError::SkillNotFound {
            skill: raw.clone(),
            path: raw_dir.clone(),
            source: e,
        })?;
        out.push(skills::SkillDir { name, dir });
    }

    Ok(out)
}

fn looks_like_path(raw: &str) -> bool {
    raw.contains('/') || raw.starts_with('.') || raw.starts_with('~')
}

fn validate_skill_dir(skill: &str, dir: &PathBuf) -> Result<(), AppError> {
    let meta = std::fs::metadata(dir).map_err(|e| AppError::SkillNotFound {
        skill: skill.to_string(),
        path: dir.clone(),
        source: e,
    })?;
    if !meta.is_dir() {
        return Err(AppError::SkillNotFound {
            skill: skill.to_string(),
            path: dir.clone(),
            source: std::io::Error::other("not a directory"),
        });
    }
    Ok(())
}

fn list_installed(cwd: &Path) -> Result<(), AppError> {
    let config = config::load_default_config()?;
    let store_dir = store::default_store_dir(cwd)?;
    let store_dir = std::fs::canonicalize(&store_dir).ok();

    let mut platform_names: Vec<String> = config.platforms.keys().cloned().collect();
    platform_names.sort();

    for platform_name in platform_names {
        let Some(platform) = config.platforms.get(&platform_name) else {
            continue;
        };

        println!("{platform_name}");

        let mut target_dirs = Vec::new();
        for target in &platform.targets {
            let target_dir = path_utils::resolve_path(&target.dir, cwd)?;
            let meta = match std::fs::metadata(&target_dir) {
                Ok(m) => m,
                Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
                    eprintln!(
                        "warning: target dir not found (skipped): platform={platform_name} dir={}",
                        display_path(&target_dir)
                    );
                    continue;
                }
                Err(err) => {
                    eprintln!(
                        "warning: failed to read target dir (skipped): platform={platform_name} dir={} err={err}",
                        display_path(&target_dir)
                    );
                    continue;
                }
            };
            if !meta.is_dir() {
                eprintln!(
                    "warning: target path is not a directory (skipped): platform={platform_name} dir={}",
                    display_path(&target_dir)
                );
                continue;
            }
            target_dirs.push(target_dir);
        }

        target_dirs.sort_by_key(|a| display_path(a));

        for (target_idx, target_dir) in target_dirs.iter().enumerate() {
            let target_prefix = if target_idx + 1 == target_dirs.len() {
                "└──"
            } else {
                "├──"
            };
            println!("{target_prefix} {}", display_path(target_dir));

            let entries = match std::fs::read_dir(target_dir) {
                Ok(e) => e,
                Err(err) => {
                    eprintln!(
                        "warning: failed to list target dir (skipped): platform={platform_name} dir={} err={err}",
                        display_path(target_dir)
                    );
                    continue;
                }
            };

            let mut rendered = Vec::new();
            for entry in entries {
                let entry = match entry {
                    Ok(e) => e,
                    Err(err) => {
                        eprintln!(
                            "warning: failed to read target entry (skipped): platform={platform_name} dir={} err={err}",
                            display_path(target_dir)
                        );
                        continue;
                    }
                };
                let name = entry.file_name().to_string_lossy().to_string();
                if name == ".DS_Store" {
                    continue;
                }

                let path = entry.path();
                let meta = match std::fs::symlink_metadata(&path) {
                    Ok(m) => m,
                    Err(err) => {
                        let line = format!("[?] {name} (error:{err})");
                        rendered.push((name, line));
                        continue;
                    }
                };

                let line = if meta.file_type().is_symlink() {
                    match std::fs::read_link(&path) {
                        Ok(raw_target) => {
                            let resolved = install::resolve_symlink_target(&path, &raw_target);
                            match std::fs::canonicalize(&resolved) {
                                Ok(resolved) => {
                                    let status = match &store_dir {
                                        Some(store_dir) => {
                                            let expected = store_dir.join(&name);
                                            let expected = std::fs::canonicalize(expected).ok();
                                            if expected.is_some_and(|e| e == resolved) {
                                                "ok".to_string()
                                            } else {
                                                "outside-store".to_string()
                                            }
                                        }
                                        None => "unknown-store".to_string(),
                                    };
                                    format!("[L] {name} -> {} ({status})", display_path(&resolved))
                                }
                                Err(err) => format!("[L] {name} (broken:{err})"),
                            }
                        }
                        Err(err) => format!("[L] {name} (broken:{err})"),
                    }
                } else if meta.is_dir() {
                    format!("[D] {name}")
                } else if meta.is_file() {
                    format!("[F] {name}")
                } else {
                    format!("[?] {name}")
                };

                rendered.push((name, line));
            }

            rendered.sort_by(|a, b| a.0.cmp(&b.0));

            for (entry_idx, (_, line)) in rendered.iter().enumerate() {
                let has_more_targets = target_idx + 1 != target_dirs.len();
                let indent = if has_more_targets { "" } else { "    " };
                let prefix = if entry_idx + 1 == rendered.len() {
                    "└──"
                } else {
                    "├──"
                };
                println!("{indent}{prefix} {line}");
            }
        }
    }

    Ok(())
}

fn display_path(path: &Path) -> String {
    path.to_string_lossy().to_string()
}

fn print_error(err: &AppError) {
    eprintln!("{err}");
    match err {
        AppError::ConfigRead { .. } | AppError::ConfigParse { .. } => {
            eprintln!("hint: run 'sklink init' to generate a default config");
        }
        AppError::ConfigAlreadyExists { .. } => {
            eprintln!("hint: run 'sklink init --force' to overwrite the existing config");
        }
        _ => {}
    }
}