yosh-plugin-manager 0.2.5

Plugin manager for yosh shell
Documentation
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
//! `yosh-plugin update`: structural TOML rewrite of `[[plugin]].version`
//! by plugin `name`, replacing the legacy `String::replacen` flow.
//!
//! See `docs/superpowers/specs/2026-04-28-plugin-update-toml-edit-design.md`.

use std::path::Path;

use toml_edit::DocumentMut;

use crate::config;
use crate::github::GitHubClient;

/// Result of trying to update a single plugin.
#[derive(Debug)]
pub enum UpdateStatus {
    /// Latest differs from current; manifest was rewritten in-memory.
    Updated { from: String, to: String },
    /// Current already matches latest; no rewrite.
    AlreadyLatest { current: String },
    /// Per-plugin GitHub or TOML helper error; loop continues.
    Failed(String),
    /// Plugin was not considered for update for one of the SkipReason variants.
    Skipped(SkipReason),
}

#[derive(Debug)]
pub enum SkipReason {
    /// `name_filter` was Some(X) and this plugin's name was not X.
    NotMatched,
    /// Plugin source is `local:`, not GitHub.
    LocalSource,
    /// GitHub plugin has an empty `version` field (`version = ""` in TOML).
    /// `config::load_config` rejects a missing `version` key for GitHub
    /// sources but accepts an empty string; this branch surfaces the empty
    /// case explicitly rather than treating it as `"" → latest`.
    NoCurrentVersion,
}

#[derive(Debug)]
pub struct PluginUpdateResult {
    pub name: String,
    pub status: UpdateStatus,
}

#[derive(Debug)]
pub struct UpdateOutcome {
    pub results: Vec<PluginUpdateResult>,
    /// True iff at least one `UpdateStatus::Updated` was produced.
    /// `cmd_update` reads this to decide whether to invoke `cmd_sync(false)`.
    pub any_updated: bool,
}

/// Orchestration entry point. Reads `config_path`, fetches the latest
/// version of each GitHub plugin (filtered by `name_filter` if set),
/// rewrites matching `[[plugin]].version` fields in a single
/// `DocumentMut`, and writes the result back exactly once if anything
/// changed.
pub fn update(
    config_path: &Path,
    name_filter: Option<&str>,
    client: &GitHubClient,
) -> Result<UpdateOutcome, String> {
    let content = std::fs::read_to_string(config_path)
        .map_err(|e| format!("{}: {}", config_path.display(), e))?;
    let mut doc: DocumentMut = content
        .parse()
        .map_err(|e| format!("{}: {}", config_path.display(), e))?;

    let decls = config::load_config(config_path)?;

    let mut results = Vec::with_capacity(decls.len());
    let mut any_updated = false;

    for decl in &decls {
        if name_filter.is_some_and(|f| decl.name != f) {
            results.push(PluginUpdateResult {
                name: decl.name.clone(),
                status: UpdateStatus::Skipped(SkipReason::NotMatched),
            });
            continue;
        }

        let (owner, repo) = match &decl.source {
            config::PluginSource::GitHub { owner, repo } => (owner, repo),
            config::PluginSource::Local { .. } => {
                results.push(PluginUpdateResult {
                    name: decl.name.clone(),
                    status: UpdateStatus::Skipped(SkipReason::LocalSource),
                });
                continue;
            }
        };

        let current = match decl.version.as_deref() {
            Some(v) if !v.is_empty() => v.to_string(),
            _ => {
                results.push(PluginUpdateResult {
                    name: decl.name.clone(),
                    status: UpdateStatus::Skipped(SkipReason::NoCurrentVersion),
                });
                continue;
            }
        };

        let status = match client.latest_version(owner, repo) {
            Ok(latest) if latest == current => UpdateStatus::AlreadyLatest { current },
            Ok(latest) => match set_plugin_version(&mut doc, &decl.name, &latest) {
                Ok(()) => {
                    any_updated = true;
                    UpdateStatus::Updated {
                        from: current,
                        to: latest,
                    }
                }
                Err(e) => UpdateStatus::Failed(e),
            },
            Err(e) => UpdateStatus::Failed(e),
        };

        results.push(PluginUpdateResult {
            name: decl.name.clone(),
            status,
        });
    }

    if any_updated {
        std::fs::write(config_path, doc.to_string())
            .map_err(|e| format!("write {}: {}", config_path.display(), e))?;
    }

    Ok(UpdateOutcome {
        results,
        any_updated,
    })
}

/// Pure TOML helper: locate the `[[plugin]]` table whose `name` equals
/// `name`, then set its `version` field to `new_version`. Returns `Err`
/// on missing/duplicate match or on structural anomalies in the
/// `plugin` key.
pub fn set_plugin_version(
    doc: &mut DocumentMut,
    name: &str,
    new_version: &str,
) -> Result<(), String> {
    let plugin_item = doc
        .get_mut("plugin")
        .ok_or_else(|| "config has no [[plugin]] array".to_string())?;
    let plugins = plugin_item
        .as_array_of_tables_mut()
        .ok_or_else(|| "config 'plugin' key is not an array of tables".to_string())?;

    let matches: Vec<usize> = plugins
        .iter()
        .enumerate()
        .filter_map(|(i, t)| {
            if t.get("name").and_then(|v| v.as_str()) == Some(name) {
                Some(i)
            } else {
                None
            }
        })
        .collect();

    match matches.as_slice() {
        [] => Err(format!("plugin '{}' not found in config", name)),
        [idx] => {
            plugins
                .get_mut(*idx)
                .expect("index from filter_map is in-bounds")
                .insert("version", toml_edit::value(new_version));
            Ok(())
        }
        _ => Err(format!(
            "plugin '{}' appears multiple times in config",
            name
        )),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::github::GitHubClientWithBase;

    #[test]
    fn set_version_basic_replaces_existing() {
        let toml = r#"[[plugin]]
name = "foo"
source = "github:owner/foo"
version = "1.0.0"
enabled = true
"#;
        let mut doc = toml.parse::<DocumentMut>().unwrap();
        set_plugin_version(&mut doc, "foo", "2.0.0").unwrap();
        let out = doc.to_string();
        assert!(out.contains(r#"version = "2.0.0""#), "out:\n{}", out);
        assert!(!out.contains(r#"version = "1.0.0""#), "out:\n{}", out);
    }

    #[test]
    fn set_version_same_version_siblings_no_collision() {
        let toml = r#"[[plugin]]
name = "alpha"
source = "github:owner/alpha"
version = "1.0.0"
enabled = true

[[plugin]]
name = "beta"
source = "github:owner/beta"
version = "1.0.0"
enabled = true
"#;
        let mut doc = toml.parse::<DocumentMut>().unwrap();
        set_plugin_version(&mut doc, "beta", "1.1.0").unwrap();
        let out = doc.to_string();

        let reparsed = out.parse::<DocumentMut>().unwrap();
        let plugins = reparsed["plugin"].as_array_of_tables().unwrap();
        assert_eq!(plugins.len(), 2);

        let alpha = plugins
            .iter()
            .find(|t| t.get("name").and_then(|v| v.as_str()) == Some("alpha"))
            .expect("alpha entry survives");
        let beta = plugins
            .iter()
            .find(|t| t.get("name").and_then(|v| v.as_str()) == Some("beta"))
            .expect("beta entry survives");

        assert_eq!(
            alpha.get("version").and_then(|v| v.as_str()),
            Some("1.0.0"),
            "sibling alpha was modified"
        );
        assert_eq!(
            beta.get("version").and_then(|v| v.as_str()),
            Some("1.1.0"),
            "target beta was not updated"
        );
    }

    #[test]
    fn set_version_preserves_comments_and_layout() {
        let toml = r#"# yosh plugin manifest
# managed by yosh-plugin

[[plugin]]
name = "foo"
source = "github:owner/foo"
version = "1.0.0"
enabled = true
"#;
        let mut doc = toml.parse::<DocumentMut>().unwrap();
        set_plugin_version(&mut doc, "foo", "1.1.0").unwrap();
        let out = doc.to_string();
        assert!(out.contains("# yosh plugin manifest"), "out:\n{}", out);
        assert!(out.contains("# managed by yosh-plugin"), "out:\n{}", out);
        assert!(out.contains(r#"version = "1.1.0""#), "out:\n{}", out);
    }

    #[test]
    fn set_version_inserts_when_missing() {
        let toml = r#"[[plugin]]
name = "foo"
source = "github:owner/foo"
enabled = true
"#;
        let mut doc = toml.parse::<DocumentMut>().unwrap();
        set_plugin_version(&mut doc, "foo", "1.0.0").unwrap();
        let out = doc.to_string();
        assert!(out.contains(r#"version = "1.0.0""#), "out:\n{}", out);
    }

    #[test]
    fn set_version_unknown_name_errors() {
        let toml = r#"[[plugin]]
name = "foo"
source = "github:owner/foo"
version = "1.0.0"
"#;
        let mut doc = toml.parse::<DocumentMut>().unwrap();
        let err = set_plugin_version(&mut doc, "nonexistent", "2.0.0").unwrap_err();
        assert!(err.contains("nonexistent"), "err: {}", err);
        assert!(err.contains("not found"), "err: {}", err);
    }

    #[test]
    fn set_version_no_plugin_array_errors() {
        let toml = "# empty config\n";
        let mut doc = toml.parse::<DocumentMut>().unwrap();
        let err = set_plugin_version(&mut doc, "foo", "1.0.0").unwrap_err();
        assert!(err.contains("no [[plugin]] array"), "err: {}", err);
    }

    #[test]
    fn set_version_plugin_key_wrong_type_errors() {
        let toml = "plugin = \"not-an-array\"\n";
        let mut doc = toml.parse::<DocumentMut>().unwrap();
        let err = set_plugin_version(&mut doc, "foo", "1.0.0").unwrap_err();
        assert!(err.contains("array of tables"), "err: {}", err);
    }

    #[test]
    fn set_version_duplicate_name_errors() {
        let toml = r#"[[plugin]]
name = "foo"
source = "github:owner/foo"
version = "1.0.0"

[[plugin]]
name = "foo"
source = "github:other/foo"
version = "2.0.0"
"#;
        let mut doc = toml.parse::<DocumentMut>().unwrap();
        let err = set_plugin_version(&mut doc, "foo", "3.0.0").unwrap_err();
        assert!(err.contains("multiple"), "err: {}", err);
    }

    #[test]
    fn update_skips_local_sources() {
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("plugins.toml");
        // Stage a local plugin file so config::load_config doesn't trip on the path.
        let plugin_file = dir.path().join("local.wasm");
        std::fs::write(&plugin_file, b"\0asm\x01\0\0\0").unwrap();
        std::fs::write(
            &config_path,
            format!(
                r#"[[plugin]]
name = "local-only"
source = "local:{}"
"#,
                plugin_file.display()
            ),
        )
        .unwrap();

        // Point at an unreachable base; if update tries to call out, the
        // test would either hang or fail. LocalSource skip should bypass.
        let client = GitHubClientWithBase::new("http://127.0.0.1:1").into_client();
        let outcome = update(&config_path, None, &client).unwrap();

        assert_eq!(outcome.results.len(), 1);
        assert!(matches!(
            outcome.results[0].status,
            UpdateStatus::Skipped(SkipReason::LocalSource)
        ));
        assert!(!outcome.any_updated);
    }

    #[test]
    fn update_name_filter_only_matches() {
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("plugins.toml");
        std::fs::write(
            &config_path,
            r#"[[plugin]]
name = "alpha"
source = "github:owner/alpha"
version = "1.0.0"

[[plugin]]
name = "beta"
source = "github:owner/beta"
version = "1.0.0"
"#,
        )
        .unwrap();

        let mut server = mockito::Server::new();
        // Only beta should be queried.
        let _m_beta = server
            .mock("GET", "/repos/owner/beta/releases/latest")
            .with_status(200)
            .with_body(r#"{"tag_name": "v2.0.0"}"#)
            .create();

        let client = GitHubClientWithBase::new(&server.url()).into_client();
        let outcome = update(&config_path, Some("beta"), &client).unwrap();

        let alpha = outcome.results.iter().find(|r| r.name == "alpha").unwrap();
        let beta = outcome.results.iter().find(|r| r.name == "beta").unwrap();
        assert!(matches!(
            alpha.status,
            UpdateStatus::Skipped(SkipReason::NotMatched)
        ));
        assert!(matches!(beta.status, UpdateStatus::Updated { .. }));

        let after = std::fs::read_to_string(&config_path).unwrap();
        let reparsed = after.parse::<DocumentMut>().unwrap();
        let plugins = reparsed["plugin"].as_array_of_tables().unwrap();
        let alpha_tbl = plugins
            .iter()
            .find(|t| t.get("name").and_then(|v| v.as_str()) == Some("alpha"))
            .unwrap();
        let beta_tbl = plugins
            .iter()
            .find(|t| t.get("name").and_then(|v| v.as_str()) == Some("beta"))
            .unwrap();
        assert_eq!(
            alpha_tbl.get("version").and_then(|v| v.as_str()),
            Some("1.0.0"),
            "alpha should be untouched"
        );
        assert_eq!(
            beta_tbl.get("version").and_then(|v| v.as_str()),
            Some("2.0.0"),
            "beta should be updated"
        );
    }

    #[test]
    fn update_no_changes_preserves_file_contents() {
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("plugins.toml");
        let original = r#"[[plugin]]
name = "foo"
source = "github:owner/foo"
version = "1.0.0"
"#;
        std::fs::write(&config_path, original).unwrap();

        // Capture mtime before the call so we can assert no write happened.
        // Byte-identical content alone would not catch a regression that
        // dropped the `if any_updated` guard at update.rs:122 — the rewrite
        // would still produce identical bytes (set_plugin_version was not
        // called), but the mtime would advance.
        let before_mtime = std::fs::metadata(&config_path).unwrap().modified().unwrap();
        // Sleep just long enough that a re-write would produce a distinct
        // mtime on filesystems with second-resolution timestamps (HFS+).
        std::thread::sleep(std::time::Duration::from_millis(1100));

        let mut server = mockito::Server::new();
        // Latest equals current: no rewrite.
        let _m = server
            .mock("GET", "/repos/owner/foo/releases/latest")
            .with_status(200)
            .with_body(r#"{"tag_name": "v1.0.0"}"#)
            .create();

        let client = GitHubClientWithBase::new(&server.url()).into_client();
        let outcome = update(&config_path, None, &client).unwrap();

        assert!(!outcome.any_updated);
        assert!(matches!(
            outcome.results[0].status,
            UpdateStatus::AlreadyLatest { .. }
        ));

        let after = std::fs::read_to_string(&config_path).unwrap();
        assert_eq!(after, original, "file content must be byte-identical");
        let after_mtime = std::fs::metadata(&config_path).unwrap().modified().unwrap();
        assert_eq!(
            before_mtime, after_mtime,
            "config mtime must be unchanged when no plugin was updated",
        );
    }

    #[test]
    fn update_partial_failure_persists_successes() {
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("plugins.toml");
        std::fs::write(
            &config_path,
            r#"[[plugin]]
name = "good"
source = "github:owner/good"
version = "1.0.0"

[[plugin]]
name = "bad"
source = "github:owner/bad"
version = "1.0.0"
"#,
        )
        .unwrap();

        let mut server = mockito::Server::new();
        let _m_good = server
            .mock("GET", "/repos/owner/good/releases/latest")
            .with_status(200)
            .with_body(r#"{"tag_name": "v2.0.0"}"#)
            .create();
        let _m_bad = server
            .mock("GET", "/repos/owner/bad/releases/latest")
            .with_status(404)
            .create();

        let client = GitHubClientWithBase::new(&server.url()).into_client();
        let outcome = update(&config_path, None, &client).unwrap();

        let good = outcome.results.iter().find(|r| r.name == "good").unwrap();
        let bad = outcome.results.iter().find(|r| r.name == "bad").unwrap();
        assert!(matches!(good.status, UpdateStatus::Updated { .. }));
        assert!(
            matches!(&bad.status, UpdateStatus::Failed(_)),
            "bad should be Failed, got: {:?}",
            bad.status
        );

        let after = std::fs::read_to_string(&config_path).unwrap();
        assert!(
            after.contains(r#"version = "2.0.0""#),
            "good's update must be persisted, got:\n{}",
            after
        );
    }
}