flk 0.7.0

A CLI tool for managing flake.nix devShell environments
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
//! # Devbox Manifest Parsing
//!
//! Reads a [Devbox](https://www.jetify.com/devbox) `devbox.json` file and
//! normalizes it into the handful of concepts flk understands: packages
//! (optionally version-pinned), environment variables, custom commands, and a
//! shell hook snippet.
//!
//! ## Why a manual normalizer
//!
//! Several `devbox.json` fields are unions whose shape varies between real
//! files — `packages` is a list *or* a map, `init_hook` and each script is a
//! string *or* a list of strings. Deserializing those into a `serde_json::Value`
//! and normalizing by hand gives better errors than a pile of `#[serde(untagged)]`
//! enums, which collapse every mismatch into "data did not match any variant".
//!
//! Anything flk cannot express (Devbox plugins via `include`, `env_from`,
//! per-package platform filters) is recorded in [`DevboxImport::skipped`] so
//! the importer can report it instead of silently dropping it.

use anyhow::{Context, Result};
use serde::Deserialize;
use serde_json::Value;
use std::collections::BTreeMap;

/// Raw `devbox.json` shape, before normalization.
///
/// Union-typed fields are kept as [`Value`] and resolved by [`normalize`].
/// Unknown top-level keys land in `extra` rather than failing the parse — a
/// newer Devbox release must not make the importer unusable.
#[derive(Debug, Default, Deserialize)]
#[serde(default)]
pub struct DevboxConfig {
    /// List (`["go@1.22"]`) or map (`{"go": "1.22"}` / `{"go": {"version": "1.22"}}`).
    pub packages: Value,
    /// Environment variables. Values are usually strings but may be numbers or booleans.
    pub env: BTreeMap<String, Value>,
    /// `shell.init_hook` and `shell.scripts`.
    pub shell: DevboxShell,
    /// Devbox plugin references. Not translatable — reported as skipped.
    pub include: Vec<Value>,
    /// Dotenv file to source. Not translatable — reported as skipped.
    pub env_from: Option<String>,
    /// Any key flk does not know about.
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

/// The `shell` object of a `devbox.json`.
#[derive(Debug, Default, Deserialize)]
#[serde(default)]
pub struct DevboxShell {
    /// String or list of strings, run on shell entry.
    pub init_hook: Value,
    /// Named scripts, each a string or list of strings.
    pub scripts: BTreeMap<String, Value>,
}

/// A package requested by a `devbox.json`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DevboxPackage {
    /// Attribute name, e.g. `ripgrep`.
    pub name: String,
    /// Pinned version, e.g. `3.11`. `None` for unversioned and for `@latest`.
    pub version: Option<String>,
}

/// Something in the manifest that flk cannot represent.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SkippedItem {
    /// The offending key or value, as it appears in the manifest.
    pub what: String,
    /// Why it was not imported, phrased for a user.
    pub reason: String,
}

impl SkippedItem {
    fn new(what: impl Into<String>, reason: impl Into<String>) -> Self {
        Self {
            what: what.into(),
            reason: reason.into(),
        }
    }
}

/// A `devbox.json` reduced to flk's vocabulary.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct DevboxImport {
    /// Packages to add, in manifest order.
    pub packages: Vec<DevboxPackage>,
    /// Environment variables to set.
    pub env: BTreeMap<String, String>,
    /// `shell.scripts`, each body joined into a single script.
    pub scripts: BTreeMap<String, String>,
    /// `shell.init_hook` lines, to append to the profile's `shellHook`.
    pub init_hook: Vec<String>,
    /// Manifest content that could not be translated.
    pub skipped: Vec<SkippedItem>,
}

impl DevboxImport {
    /// True when there is nothing at all to write into a profile.
    pub fn is_empty(&self) -> bool {
        self.packages.is_empty()
            && self.env.is_empty()
            && self.scripts.is_empty()
            && self.init_hook.is_empty()
    }
}

/// Parse and normalize a `devbox.json` from its raw text.
pub fn parse(contents: &str) -> Result<DevboxImport> {
    let config: DevboxConfig =
        serde_json::from_str(contents).context("Failed to parse devbox.json")?;
    normalize(config)
}

/// Reduce a raw [`DevboxConfig`] to flk's vocabulary.
pub fn normalize(config: DevboxConfig) -> Result<DevboxImport> {
    let mut skipped = Vec::new();

    let packages = normalize_packages(&config.packages, &mut skipped)?;

    let mut env = BTreeMap::new();
    for (name, value) in &config.env {
        match scalar_to_string(value) {
            Some(v) => {
                env.insert(name.clone(), v);
            }
            None => skipped.push(SkippedItem::new(
                format!("env.{}", name),
                "value is not a string, number or boolean",
            )),
        }
    }

    let mut scripts = BTreeMap::new();
    for (name, body) in &config.shell.scripts {
        let lines = to_lines(body);
        if lines.is_empty() {
            skipped.push(SkippedItem::new(
                format!("shell.scripts.{}", name),
                "script body is empty",
            ));
            continue;
        }
        scripts.insert(name.clone(), lines.join("\n"));
    }

    let init_hook = to_lines(&config.shell.init_hook);

    for entry in &config.include {
        let label = entry.as_str().unwrap_or("<non-string>").to_string();
        skipped.push(SkippedItem::new(
            format!("include: {}", label),
            "Devbox plugins have no flk equivalent — translate it by hand",
        ));
    }

    if let Some(env_from) = &config.env_from {
        skipped.push(SkippedItem::new(
            format!("env_from: {}", env_from),
            "dotenv sourcing is not supported — add the variables with 'flk env add'",
        ));
    }

    for key in config.extra.keys() {
        // `$schema` is editor metadata, not configuration; reporting it is noise.
        if key == "$schema" {
            continue;
        }
        skipped.push(SkippedItem::new(
            key.clone(),
            "unrecognized devbox.json key",
        ));
    }

    Ok(DevboxImport {
        packages,
        env,
        scripts,
        init_hook,
        skipped,
    })
}

/// Normalize the `packages` field from either of its two shapes.
fn normalize_packages(value: &Value, skipped: &mut Vec<SkippedItem>) -> Result<Vec<DevboxPackage>> {
    match value {
        Value::Null => Ok(Vec::new()),

        // ["go@1.22", "ripgrep"]
        Value::Array(entries) => {
            let mut packages = Vec::new();
            for entry in entries {
                match entry.as_str() {
                    Some(spec) => packages.push(split_spec(spec)),
                    None => skipped.push(SkippedItem::new(
                        entry.to_string(),
                        "package entry is not a string",
                    )),
                }
            }
            Ok(packages)
        }

        // {"go": "1.22"} or {"go": {"version": "1.22", "platforms": [...]}}
        Value::Object(entries) => {
            let mut packages = Vec::new();
            for (name, spec) in entries {
                let version = match spec {
                    Value::String(v) => Some(v.clone()),
                    Value::Object(detail) => {
                        for filter in ["platforms", "excluded_platforms"] {
                            if detail.contains_key(filter) {
                                skipped.push(SkippedItem::new(
                                    format!("packages.{}.{}", name, filter),
                                    "platform filters are not supported — the package is imported for all systems",
                                ));
                            }
                        }
                        detail
                            .get("version")
                            .and_then(Value::as_str)
                            .map(String::from)
                    }
                    other => {
                        skipped.push(SkippedItem::new(
                            format!("packages.{}", name),
                            format!("unsupported version spec: {}", other),
                        ));
                        continue;
                    }
                };

                packages.push(DevboxPackage {
                    name: name.clone(),
                    version: version.filter(|v| !is_latest(v)),
                });
            }
            Ok(packages)
        }

        other => anyhow::bail!(
            "'packages' must be a list or an object, found: {}",
            type_name(other)
        ),
    }
}

/// Split a `name@version` spec. `@latest` and a bare name both yield `None`.
fn split_spec(spec: &str) -> DevboxPackage {
    match spec.split_once('@') {
        Some((name, version)) if !name.is_empty() && !is_latest(version) => DevboxPackage {
            name: name.to_string(),
            version: Some(version.to_string()),
        },
        Some((name, _)) if !name.is_empty() => DevboxPackage {
            name: name.to_string(),
            version: None,
        },
        _ => DevboxPackage {
            name: spec.to_string(),
            version: None,
        },
    }
}

/// `latest` means "whatever nixpkgs has", which is flk's unpinned behaviour.
fn is_latest(version: &str) -> bool {
    version.eq_ignore_ascii_case("latest")
}

/// Flatten a string-or-list-of-strings field into individual lines.
fn to_lines(value: &Value) -> Vec<String> {
    match value {
        Value::String(s) => non_empty_lines(s),
        Value::Array(entries) => entries
            .iter()
            .filter_map(Value::as_str)
            .flat_map(non_empty_lines)
            .collect(),
        _ => Vec::new(),
    }
}

/// Split into lines, dropping leading/trailing blank ones but keeping interior
/// structure so multi-line hooks stay readable.
fn non_empty_lines(s: &str) -> Vec<String> {
    let lines: Vec<String> = s.lines().map(str::to_string).collect();
    let first = lines.iter().position(|l| !l.trim().is_empty());
    let last = lines.iter().rposition(|l| !l.trim().is_empty());
    match (first, last) {
        (Some(a), Some(b)) => lines[a..=b].to_vec(),
        _ => Vec::new(),
    }
}

/// Render a JSON scalar as the string flk will write into `envVars`.
fn scalar_to_string(value: &Value) -> Option<String> {
    match value {
        Value::String(s) => Some(s.clone()),
        Value::Number(n) => Some(n.to_string()),
        Value::Bool(b) => Some(b.to_string()),
        _ => None,
    }
}

/// Human-readable JSON type name, for error messages.
fn type_name(value: &Value) -> &'static str {
    match value {
        Value::Null => "null",
        Value::Bool(_) => "a boolean",
        Value::Number(_) => "a number",
        Value::String(_) => "a string",
        Value::Array(_) => "a list",
        Value::Object(_) => "an object",
    }
}

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

    fn pkg(name: &str, version: Option<&str>) -> DevboxPackage {
        DevboxPackage {
            name: name.to_string(),
            version: version.map(String::from),
        }
    }

    #[test]
    fn parses_list_form_packages() {
        let import = parse(r#"{"packages": ["ripgrep", "go@1.22"]}"#).unwrap();
        assert_eq!(
            import.packages,
            vec![pkg("ripgrep", None), pkg("go", Some("1.22"))]
        );
    }

    #[test]
    fn map_form_packages_normalize_like_list_form() {
        let from_map = parse(r#"{"packages": {"go": {"version": "1.22"}}}"#).unwrap();
        let from_short_map = parse(r#"{"packages": {"go": "1.22"}}"#).unwrap();
        let from_list = parse(r#"{"packages": ["go@1.22"]}"#).unwrap();

        assert_eq!(from_map.packages, from_list.packages);
        assert_eq!(from_short_map.packages, from_list.packages);
    }

    #[test]
    fn latest_is_treated_as_unpinned() {
        let import = parse(r#"{"packages": ["hello@latest", "world@LATEST"]}"#).unwrap();
        assert_eq!(
            import.packages,
            vec![pkg("hello", None), pkg("world", None)]
        );
    }

    #[test]
    fn platform_filters_are_reported_not_applied() {
        let import =
            parse(r#"{"packages": {"go": {"version": "1.22", "platforms": ["x86_64-linux"]}}}"#)
                .unwrap();

        assert_eq!(import.packages, vec![pkg("go", Some("1.22"))]);
        assert!(import
            .skipped
            .iter()
            .any(|s| s.what == "packages.go.platforms"));
    }

    #[test]
    fn init_hook_accepts_string_or_list() {
        let as_list = parse(r#"{"shell": {"init_hook": ["echo one", "echo two"]}}"#).unwrap();
        let as_string = parse(r#"{"shell": {"init_hook": "echo one\necho two"}}"#).unwrap();

        assert_eq!(as_list.init_hook, vec!["echo one", "echo two"]);
        assert_eq!(as_list.init_hook, as_string.init_hook);
    }

    #[test]
    fn scripts_accept_string_or_list() {
        let import = parse(
            r#"{"shell": {"scripts": {
                 "build": ["cargo build", "cargo test"],
                 "fmt": "cargo fmt"
               }}}"#,
        )
        .unwrap();

        assert_eq!(import.scripts["build"], "cargo build\ncargo test");
        assert_eq!(import.scripts["fmt"], "cargo fmt");
    }

    #[test]
    fn empty_script_is_skipped_not_imported() {
        let import = parse(r#"{"shell": {"scripts": {"noop": []}}}"#).unwrap();

        assert!(import.scripts.is_empty());
        assert!(import
            .skipped
            .iter()
            .any(|s| s.what == "shell.scripts.noop"));
    }

    #[test]
    fn env_values_coerce_scalars_to_strings() {
        let import = parse(r#"{"env": {"PORT": 8080, "DEBUG": true, "NAME": "flk"}}"#).unwrap();

        assert_eq!(import.env["PORT"], "8080");
        assert_eq!(import.env["DEBUG"], "true");
        assert_eq!(import.env["NAME"], "flk");
    }

    #[test]
    fn include_and_env_from_are_reported_as_skipped() {
        let import = parse(r#"{"include": ["plugin:nginx"], "env_from": ".env"}"#).unwrap();

        assert!(import
            .skipped
            .iter()
            .any(|s| s.what.contains("plugin:nginx")));
        assert!(import.skipped.iter().any(|s| s.what.contains(".env")));
    }

    #[test]
    fn unknown_keys_do_not_fail_the_parse_and_are_reported() {
        let import = parse(r#"{"$schema": "https://x", "future_field": 1}"#).unwrap();

        assert!(import.skipped.iter().any(|s| s.what == "future_field"));
        assert!(
            !import.skipped.iter().any(|s| s.what == "$schema"),
            "$schema is editor metadata and should not be reported"
        );
    }

    #[test]
    fn malformed_json_reports_the_file() {
        let err = parse("{ not json").unwrap_err();
        assert!(err.to_string().contains("devbox.json"));
    }

    #[test]
    fn packages_of_wrong_type_is_an_error() {
        let err = parse(r#"{"packages": "ripgrep"}"#).unwrap_err();
        assert!(err.to_string().contains("must be a list or an object"));
    }

    #[test]
    fn empty_manifest_is_empty() {
        assert!(parse("{}").unwrap().is_empty());
    }
}