enwiro-sdk 0.4.0

Shared SDK for enwiro plugin authors: logging, gear schema, plugin protocol types
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
use anyhow::{Context, bail};
use serde::{Deserialize, Serialize};
use std::io::Write;
use std::process::{Command, Output, Stdio};

use crate::cookbook::{CookbookMetadata, CookbookPayload, Recipe};
use crate::plugin::Plugin;

const DEFAULT_PRIORITY: u32 = 50;

#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
pub struct EnvScores {
    pub launcher: f64,
    pub slot: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CachedRecipe {
    pub cookbook: String,
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default)]
    pub sort_order: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scores: Option<EnvScores>,
}

pub trait CookbookTrait {
    fn list_recipes(&self) -> anyhow::Result<Vec<Recipe>>;
    fn cook(&self, recipe: &str) -> anyhow::Result<String>;
    fn name(&self) -> &str;
    /// Controls display and resolution order. Lower values appear first.
    /// Built-in range: git=10, chezmoi=20, github=30. Third-party plugins
    /// that don't provide metadata default to 50.
    fn priority(&self) -> u32 {
        DEFAULT_PRIORITY
    }
    /// Return optional gear configuration JSON for the given recipe.
    /// If `Some(json)` is returned after cooking, it is written to
    /// `<env>/gear.d/cookbook-<name>.json` (one file per cookbook),
    /// where the env-side reader (`enwiro_sdk::gear::LoadedGear`)
    /// merges every cookbook's contribution into one keyed map.
    fn gear(&self, _recipe: &str) -> anyhow::Result<Option<serde_json::Value>> {
        Ok(None)
    }
}

/// Sort cookbooks by priority (lower first), then alphabetically by name.
pub fn sort_cookbooks(cookbooks: &mut [Box<dyn CookbookTrait>]) {
    cookbooks.sort_by(|a, b| {
        a.priority()
            .cmp(&b.priority())
            .then_with(|| a.name().cmp(b.name()))
    });
}

pub struct CookbookClient {
    plugin: Plugin,
    metadata: CookbookMetadata,
    config: serde_json::Value,
}

impl CookbookClient {
    /// Construct a client whose config is resolved with the project-level
    /// walker rooted at the current working directory. Used by the `enw`
    /// CLI: the user invokes `enw` from a project shell, so cwd identifies
    /// the project context.
    pub fn new(plugin: Plugin) -> Self {
        let metadata = Self::fetch_metadata(&plugin.executable);
        let config = resolve_config_with_walker(&plugin, &metadata);
        Self {
            plugin,
            metadata,
            config,
        }
    }

    /// Construct a client whose config is resolved from user-level files
    /// only — no project-layer walk. Used by the enwiro daemon: it's a
    /// single long-running process serving many projects with no concept
    /// of "current project," so per-project overrides can't be applied
    /// meaningfully. The daemon's recipe cache is correspondingly
    /// project-independent.
    pub fn new_user_level_only(plugin: Plugin) -> Self {
        let metadata = Self::fetch_metadata(&plugin.executable);
        let config = resolve_user_level_only(&plugin);
        Self {
            plugin,
            metadata,
            config,
        }
    }

    #[cfg(test)]
    fn with_metadata(plugin: Plugin, metadata: CookbookMetadata) -> Self {
        Self::with_metadata_and_config(
            plugin,
            metadata,
            serde_json::Value::Object(Default::default()),
        )
    }

    #[cfg(test)]
    fn with_metadata_and_config(
        plugin: Plugin,
        metadata: CookbookMetadata,
        config: serde_json::Value,
    ) -> Self {
        Self {
            plugin,
            metadata,
            config,
        }
    }

    fn fetch_metadata(executable: &str) -> CookbookMetadata {
        let result = (|| -> anyhow::Result<CookbookMetadata> {
            let output = Command::new(executable)
                .arg("metadata")
                .output()
                .context("Failed to run cookbook metadata command")?;
            if !output.status.success() {
                bail!("Cookbook does not support metadata subcommand");
            }
            let stdout = String::from_utf8(output.stdout)
                .context("Cookbook metadata produced invalid UTF-8")?;
            CookbookMetadata::from_json(&stdout)
        })();
        match result {
            Ok(meta) => meta,
            Err(e) => {
                tracing::debug!(error = %e, "Could not fetch cookbook metadata, using defaults");
                CookbookMetadata::default()
            }
        }
    }

    /// Spawn the cookbook with the given subcommand args, write the
    /// resolved `CookbookPayload` to its stdin, and collect output.
    /// Centralizes the stdin pipe so every subcommand carries the same
    /// payload.
    fn spawn_with_payload(&self, args: &[&str]) -> anyhow::Result<Output> {
        let mut child = Command::new(&self.plugin.executable)
            .args(args)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .context("Failed to spawn cookbook")?;
        if let Some(mut stdin) = child.stdin.take() {
            let payload = CookbookPayload::new(self.config.clone());
            let bytes =
                serde_json::to_vec(&payload).context("Failed to serialize cookbook payload")?;
            stdin
                .write_all(&bytes)
                .context("Failed to write cookbook payload to stdin")?;
        }
        child.wait_with_output().context("Cookbook process failed")
    }
}

/// Resolve a cookbook's config with the project-layer walker rooted at
/// the current working directory, filtered through the cookbook's
/// `project_overridable` allowlist. Falls back to an empty JSON object
/// (with `warn` log) on error so a single misconfigured cookbook
/// doesn't break the whole CLI.
fn resolve_config_with_walker(plugin: &Plugin, metadata: &CookbookMetadata) -> serde_json::Value {
    let cwd = match std::env::current_dir() {
        Ok(c) => c,
        Err(e) => {
            tracing::warn!(error = %e, "Could not determine cwd; cookbook config defaults to empty");
            return serde_json::Value::Object(Default::default());
        }
    };
    let scope = scope_for(plugin);
    let allowlist: Vec<&str> = metadata
        .project_overridable
        .iter()
        .map(String::as_str)
        .collect();
    match crate::config::build_cookbook_config(&cwd, &scope, &allowlist) {
        Ok(v) => v,
        Err(e) => {
            tracing::warn!(cookbook = %plugin.name, error = %e, "Failed to resolve cookbook config; using empty config");
            serde_json::Value::Object(Default::default())
        }
    }
}

/// Resolve a cookbook's config from the user-level file only. Used by
/// the daemon, which has no meaningful "current project" cwd.
fn resolve_user_level_only(plugin: &Plugin) -> serde_json::Value {
    let scope = scope_for(plugin);
    match crate::config::load_user_config(&scope) {
        Ok(v) => v,
        Err(e) => {
            tracing::warn!(cookbook = %plugin.name, error = %e, "Failed to load user-level cookbook config; using empty config");
            serde_json::Value::Object(Default::default())
        }
    }
}

fn scope_for(plugin: &Plugin) -> String {
    format!("cookbook-{}", plugin.name)
}

impl CookbookTrait for CookbookClient {
    fn list_recipes(&self) -> anyhow::Result<Vec<Recipe>> {
        tracing::debug!(cookbook = %self.plugin.name, "Listing recipes from cookbook");
        let output = self.spawn_with_payload(&["list-recipes"])?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            tracing::error!(cookbook = %self.plugin.name, %stderr, "Cookbook failed to list recipes");
            bail!(
                "Cookbook '{}' failed to list recipes: {}",
                self.plugin.name,
                stderr
            );
        }

        let stdout =
            String::from_utf8(output.stdout).context("Cookbook produced invalid UTF-8 output")?;
        Ok(stdout
            .lines()
            .filter(|line| !line.is_empty())
            .map(|line| serde_json::from_str::<Recipe>(line).unwrap_or_else(|_| Recipe::new(line)))
            .collect())
    }

    fn cook(&self, recipe: &str) -> anyhow::Result<String> {
        tracing::debug!(cookbook = %self.plugin.name, recipe = %recipe, "Cooking recipe");
        let output = self.spawn_with_payload(&["cook", recipe])?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            tracing::error!(cookbook = %self.plugin.name, recipe = %recipe, %stderr, "Cookbook failed to cook recipe");
            bail!(
                "Cookbook '{}' failed to cook '{}': {}",
                self.plugin.name,
                recipe,
                stderr
            );
        }

        let stdout =
            String::from_utf8(output.stdout).context("Cookbook produced invalid UTF-8 output")?;
        Ok(stdout.trim().to_string())
    }

    fn name(&self) -> &str {
        &self.plugin.name
    }

    fn priority(&self) -> u32 {
        self.metadata.default_priority.unwrap_or(DEFAULT_PRIORITY)
    }

    /// Invoke the cookbook binary's optional `gear <recipe>` subcommand and
    /// parse its stdout as JSON. Returns `Ok(None)` if the subcommand fails
    /// for any reason (old cookbook that doesn't implement `gear`, exec
    /// error, malformed JSON) so a missing or broken `gear` never blocks
    /// cooking. Best-effort by design.
    fn gear(&self, recipe: &str) -> anyhow::Result<Option<serde_json::Value>> {
        let output = match self.spawn_with_payload(&["gear", recipe]) {
            Ok(o) => o,
            Err(e) => {
                tracing::debug!(cookbook = %self.plugin.name, error = %e, "Cookbook gear exec failed");
                return Ok(None);
            }
        };
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            tracing::debug!(cookbook = %self.plugin.name, recipe = %recipe, %stderr, "Cookbook gear subcommand returned non-zero");
            return Ok(None);
        }
        match serde_json::from_slice::<serde_json::Value>(&output.stdout) {
            Ok(json) => Ok(Some(json)),
            Err(e) => {
                tracing::debug!(cookbook = %self.plugin.name, error = %e, "Cookbook gear stdout was not valid JSON");
                Ok(None)
            }
        }
    }
}

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

    fn mock_plugin(name: &str) -> Plugin {
        Plugin {
            name: name.to_string(),
            kind: PluginKind::Cookbook,
            executable: String::new(),
        }
    }

    #[test]
    fn test_cookbook_client_uses_priority_from_metadata() {
        let client = CookbookClient::with_metadata(
            mock_plugin("git"),
            CookbookMetadata {
                default_priority: Some(10),
                project_overridable: vec![],
            },
        );
        assert_eq!(client.priority(), 10);
    }

    #[test]
    fn test_cookbook_client_default_priority_when_no_metadata() {
        let client = CookbookClient::with_metadata(mock_plugin("git"), CookbookMetadata::default());
        assert_eq!(client.priority(), DEFAULT_PRIORITY);
    }

    #[test]
    fn test_cookbook_client_name_from_plugin() {
        let client =
            CookbookClient::with_metadata(mock_plugin("my-cookbook"), CookbookMetadata::default());
        assert_eq!(client.name(), "my-cookbook");
    }

    /// Regression guard for AC #1: "without `.enwiro.toml` present, behavior
    /// is identical to today (user-level files still loaded; no regression)."
    /// With no user-level TOML and no project-level TOML, the SDK must
    /// produce an empty-object config so cookbook structs with
    /// `#[serde(default)]` can deserialize to defaults instead of erroring
    /// on missing fields. Also exercises the shell-script cookbook path
    /// (proves the language-agnostic protocol works with no payload).
    #[test]
    fn test_shell_cookbook_receives_defaults_when_no_user_or_project_config() {
        use std::os::unix::fs::PermissionsExt;

        let tempdir = tempfile::tempdir().expect("tempdir");
        let home_dir = tempdir.path().join("home");
        let project_dir = tempdir.path().join("proj");
        std::fs::create_dir_all(&home_dir).expect("mkdir home");
        std::fs::create_dir_all(&project_dir).expect("mkdir project");

        // Deliberately do NOT write any user or project config files.

        let script = project_dir.join("fake-cookbook");
        std::fs::write(
            &script,
            r#"#!/bin/sh
payload=$(cat)
echo "$payload"
"#,
        )
        .expect("write script");
        std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755))
            .expect("chmod script");

        let config = crate::config::ConfigLoader::with_home(home_dir.clone())
            .build_cookbook_config(&project_dir, "cookbook-fake", &["repo_globs"])
            .expect("no-files build_cookbook_config succeeds");

        // The loader must give the cookbook an object (not null) so that
        // `serde_json::from_value::<CookbookConfig>(payload.config)` against
        // a struct with `#[serde(default)]` deserializes to defaults.
        assert!(
            config.is_object(),
            "config from a no-files load must be a JSON object so #[serde(default)] structs deserialize cleanly; got {config:?}"
        );

        let plugin = Plugin {
            name: "fake".to_string(),
            kind: PluginKind::Cookbook,
            executable: script.to_string_lossy().into_owned(),
        };
        let client =
            CookbookClient::with_metadata_and_config(plugin, CookbookMetadata::default(), config);

        let stdout = client.cook("anything").expect("cook returns stdout");
        let payload: CookbookPayload =
            serde_json::from_str(&stdout).expect("cookbook saw a valid CookbookPayload on stdin");
        assert!(
            payload.config.is_object(),
            "cookbook must see config as an object (not null) so its #[serde(default)] struct can deserialize; got {:?}",
            payload.config
        );
    }

    /// End-to-end integration: a project-level `.enwiro.toml` is found by
    /// the SDK loader, filtered through a cookbook's `project_overridable`
    /// allowlist, merged on top of the user-level config, and piped into a
    /// language-agnostic (shell-script) cookbook over stdin. This satisfies
    /// the ADR/AC requirement of one integration test exercising a
    /// shell-script cookbook with the full project-walker pipeline.
    #[test]
    fn test_shell_cookbook_receives_merged_project_layer_config() {
        use std::os::unix::fs::PermissionsExt;

        let tempdir = tempfile::tempdir().expect("tempdir");
        let home_dir = tempdir.path().join("home");
        let project_dir = tempdir.path().join("proj");
        std::fs::create_dir_all(&home_dir).expect("mkdir home");
        std::fs::create_dir_all(&project_dir).expect("mkdir project");

        // User-level config for the fake cookbook (scope `cookbook-fake`).
        let user_config_dir = home_dir.join(".config/enwiro");
        std::fs::create_dir_all(&user_config_dir).expect("mkdir user config dir");
        std::fs::write(
            user_config_dir.join("cookbook-fake.toml"),
            "repo_globs = [\"from-user\"]\n",
        )
        .expect("write user config");

        // Project-level `.enwiro.toml` overrides `repo_globs` (allowlisted)
        // and tries to set `not_allowed` (should be dropped).
        std::fs::write(
            project_dir.join(".enwiro.toml"),
            "[cookbook-fake]\nrepo_globs = [\"from-project\"]\nnot_allowed = \"x\"\n",
        )
        .expect("write project config");

        // Fake shell-script cookbook that echoes the payload on `cook`.
        let script = project_dir.join("fake-cookbook");
        std::fs::write(
            &script,
            r#"#!/bin/sh
payload=$(cat)
echo "$payload"
"#,
        )
        .expect("write script");
        std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755))
            .expect("chmod script");

        // Resolve config via the SDK's loader with the project as cwd.
        let config = crate::config::ConfigLoader::with_home(home_dir.clone())
            .build_cookbook_config(&project_dir, "cookbook-fake", &["repo_globs"])
            .expect("build_cookbook_config succeeds");

        let metadata = CookbookMetadata {
            default_priority: Some(99),
            project_overridable: vec!["repo_globs".to_string()],
        };
        let plugin = Plugin {
            name: "fake".to_string(),
            kind: PluginKind::Cookbook,
            executable: script.to_string_lossy().into_owned(),
        };
        let client = CookbookClient::with_metadata_and_config(plugin, metadata, config);

        let stdout = client.cook("anything").expect("cook returns stdout");
        let payload: CookbookPayload =
            serde_json::from_str(&stdout).expect("cookbook saw a valid CookbookPayload on stdin");

        assert_eq!(payload.version, 1, "payload version should be 1");
        assert_eq!(
            payload.config["repo_globs"],
            serde_json::json!(["from-project"]),
            "project layer must win over user layer for the allowlisted key"
        );
        assert!(
            payload.config.get("not_allowed").is_none(),
            "non-allowlisted key must be dropped before reaching the cookbook; got {:?}",
            payload.config
        );
    }
}