oxdock-core 0.10.0-alpha

Core engine for OxDock's Dockerfile-inspired compile-time DSL, orchestrating workspace snapshots and asset embedding.
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
use anyhow::{Result, bail};
use oxdock_parser::{Arg, ArgPart, CompareOp, Expr, LogicalOp, Value};
use oxdock_process::ProcessManager;

use super::state::ExecState;
use super::steps::StepCtx;

/// Resolve an [`Arg`] using an [`ExecState`] directly (no [`StepCtx`] needed).
/// Handles `Arg::String` and all-`Text` `Arg::Parts` — `Arg::Expr` requires a
/// `StepCtx` and must go through `resolve_arg`.
pub(crate) fn resolve_arg_state<P: ProcessManager>(
    arg: &Arg,
    state: &ExecState<P>,
) -> Result<String> {
    match arg {
        Arg::String(s, _) => {
            let ctx = state.command_ctx()?;
            Ok(expand_string(s, ctx.envs(), state)?)
        }
        Arg::Expr(e) => bail!("Arg::Expr cannot be resolved without StepCtx: {:?}", e),
        Arg::Parts(parts) => {
            let ctx = state.command_ctx()?;
            let mut out = String::new();
            for part in parts {
                match part {
                    ArgPart::Text(s, _) => {
                        out.push_str(&expand_string(s, ctx.envs(), state)?);
                    }
                    ArgPart::Expr(e) => {
                        bail!("Arg::Expr cannot be resolved without StepCtx: {:?}", e)
                    }
                }
            }
            Ok(out)
        }
    }
}

/// Resolve an [`Arg`] — handles all variants.
pub(crate) fn resolve_arg<P: ProcessManager>(arg: &Arg, cx: &mut StepCtx<'_, P>) -> Result<String> {
    match arg {
        Arg::String(s, _) => Ok(expand_string(s, &cx.state.envs, cx.state)?),
        Arg::Expr(e) => {
            let val = evaluate_expr(e, cx)?;
            Ok(format_value_for_string(&val))
        }
        Arg::Parts(parts) => {
            let mut out = String::new();
            for part in parts {
                match part {
                    ArgPart::Text(s, _) => {
                        out.push_str(&expand_string(s, &cx.state.envs, cx.state)?);
                    }
                    ArgPart::Expr(e) => {
                        let val = evaluate_expr(e, cx)?;
                        out.push_str(&format_value_for_string(&val));
                    }
                }
            }
            Ok(out)
        }
    }
}

/// Resolve an optional [`Arg`]. Returns `Ok(None)` when `None` is passed.
pub(crate) fn resolve_arg_opt<P: ProcessManager>(
    arg: &Option<Arg>,
    cx: &mut StepCtx<'_, P>,
) -> Result<Option<String>> {
    match arg {
        Some(a) => resolve_arg(a, cx).map(Some),
        None => Ok(None),
    }
}

/// Resolve a list of `(name, Arg)` override pairs.
pub(crate) fn resolve_overrides<P: ProcessManager>(
    overrides: &[(String, Arg)],
    cx: &mut StepCtx<'_, P>,
) -> Result<Vec<(String, String)>> {
    overrides
        .iter()
        .map(|(k, v)| resolve_arg(v, cx).map(|val| (k.clone(), val)))
        .collect()
}

/// Resolve an [`Arg`] to an integer, enforcing the declared `int` type
/// on the interpolated value. Dynamics (`$var`, templates) validate
/// here — lower time only sees their unevaluated form.
pub(crate) fn resolve_arg_as_int<P: ProcessManager>(
    arg: &Arg,
    cx: &mut StepCtx<'_, P>,
) -> Result<i32> {
    let resolved = resolve_arg(arg, cx)?;
    resolved
        .parse::<i32>()
        .map_err(|_| anyhow::anyhow!("expected int, got {resolved:?}"))
}

/// Resolve an [`Arg`] to a duration, enforcing the declared `duration`
/// type on the interpolated value. Same lower/runtime split as ints.
pub(crate) fn resolve_arg_as_duration<P: ProcessManager>(
    arg: &Arg,
    cx: &mut StepCtx<'_, P>,
) -> Result<std::time::Duration> {
    let resolved = resolve_arg(arg, cx)?;
    oxdock_parser::command::parse_duration(&resolved)
}

/// Evaluate an [`Expr`] to a [`Value`].
pub(crate) fn evaluate_expr<P: ProcessManager>(
    expr: &Expr,
    cx: &mut StepCtx<'_, P>,
) -> Result<Value> {
    match expr {
        Expr::Literal(Value::String(s)) => {
            // Expand {{ $var }} and {{ env:KEY }} in string literals
            Ok(Value::String(expand_string(s, &cx.state.envs, cx.state)?))
        }
        Expr::Literal(v) => Ok(v.clone()),
        Expr::Var(name) => cx
            .state
            .get_var(name)
            .or_else(|| cx.state.envs.get(name).map(|v| Value::String(v.clone())))
            .ok_or_else(|| anyhow::anyhow!("undefined variable ${name}")),
        Expr::KeyPath { base, keys } => {
            let mut current = cx
                .state
                .get_var(base)
                .or_else(|| cx.state.envs.get(base).map(|v| Value::String(v.clone())))
                .ok_or_else(|| anyhow::anyhow!("undefined variable ${base}"))?;
            for key in keys {
                match current {
                    Value::Map(map) => {
                        current = map
                            .get(key)
                            .cloned()
                            .ok_or_else(|| anyhow::anyhow!("Key '{}' not found in map", key))?;
                    }
                    Value::List(list) => {
                        let idx: usize = key
                            .parse()
                            .map_err(|_| anyhow::anyhow!("Invalid array index '{}'", key))?;
                        current = list
                            .get(idx)
                            .cloned()
                            .ok_or_else(|| anyhow::anyhow!("Index {} out of bounds", idx))?;
                    }
                    Value::String(_) | Value::Bool(_) | Value::Int(_) | Value::TaskHandle(_) => {
                        bail!("Cannot traverse into scalar value at key '{}'", key);
                    }
                }
            }
            Ok(current)
        }
        Expr::List(items) => {
            let mut result = Vec::new();
            for item in items {
                result.push(evaluate_expr(item, cx)?);
            }
            Ok(Value::List(result))
        }
        Expr::Map(entries) => {
            let mut result = std::collections::BTreeMap::new();
            for (key, val_expr) in entries {
                let val = evaluate_expr(val_expr, cx)?;
                result.insert(key.clone(), val);
            }
            Ok(Value::Map(result))
        }
        Expr::Call { name, args } => match name.as_str() {
            "GLOB" => evaluate_glob(args, cx),
            "LOAD_TOML" => evaluate_load_toml(args, cx),
            "LOAD_JSON" => evaluate_load_json(args, cx),
            _ => bail!("unknown function {name}"),
        },
        Expr::Compare { op, left, right } => {
            let lv = evaluate_expr(left, cx)?;
            let rv = evaluate_expr(right, cx)?;
            let ls = format_value_for_string(&lv);
            let rs = format_value_for_string(&rv);
            let result = match op {
                CompareOp::Eq => ls == rs,
                CompareOp::Ne => ls != rs,
            };
            Ok(Value::Bool(result))
        }
        Expr::Logical { op, left, right } => {
            let left_val = evaluate_expr(left, cx)?;
            let left_truthy = is_truthy(&left_val)?;
            match op {
                LogicalOp::Or => {
                    if left_truthy {
                        Ok(Value::Bool(true))
                    } else {
                        Ok(Value::Bool(is_truthy(&evaluate_expr(right, cx)?)?))
                    }
                }
                LogicalOp::And => {
                    if !left_truthy {
                        Ok(Value::Bool(false))
                    } else {
                        Ok(Value::Bool(is_truthy(&evaluate_expr(right, cx)?)?))
                    }
                }
            }
        }
        Expr::Not(inner) => Ok(Value::Bool(!is_truthy(&evaluate_expr(inner, cx)?)?)),
    }
}

/// Check if a value is truthy. Only `Value::Bool` is accepted; all other types produce a TypeError.
pub(crate) fn is_truthy(val: &Value) -> Result<bool> {
    match val {
        Value::Bool(b) => Ok(*b),
        other => bail!("Type Error: condition must be a Bool, found {:?}", other),
    }
}

/// Evaluate a `GLOB()` function call.
fn evaluate_glob<P: ProcessManager>(args: &[Expr], cx: &mut StepCtx<'_, P>) -> Result<Value> {
    if args.is_empty() {
        bail!("GLOB requires a pattern argument");
    }

    let pattern_val = evaluate_expr(&args[0], cx)?;
    let raw_pattern = match pattern_val {
        Value::String(s) => s,
        _ => bail!("GLOB pattern argument must evaluate to a string"),
    };

    // Up-front sandbox gate (mirrors `GuardedPath::glob_paths`): patterns are
    // sandbox-root-relative, so any `..` component escapes. Return empty
    // without traversing — the same empty-on-no-match GLOB semantics.
    if raw_pattern
        .replace('\\', "/")
        .split('/')
        .any(|seg| seg == "..")
    {
        return Ok(Value::List(Vec::new()));
    }

    let root = cx.state.fs.root().clone();
    let root_path = root.as_path().to_path_buf();
    let mut entries: Vec<Value> = root
        .glob_paths(&raw_pattern)?
        .into_iter()
        .filter_map(|p| {
            p.strip_prefix(&root_path)
                .ok()
                .map(|rel| Value::String(rel.to_string_lossy().replace('\\', "/")))
        })
        .collect();

    entries.sort_by(|a, b| format!("{}", a).cmp(&format!("{}", b)));
    Ok(Value::List(entries))
}

/// Evaluate a `LOAD_TOML()` function call.
fn evaluate_load_toml<P: ProcessManager>(args: &[Expr], cx: &mut StepCtx<'_, P>) -> Result<Value> {
    if args.is_empty() {
        bail!("LOAD_TOML requires a path argument");
    }
    let path_val = evaluate_expr(&args[0], cx)?;
    let path_str = match path_val {
        Value::String(s) => s,
        _ => bail!("LOAD_TOML path argument must evaluate to a string"),
    };
    let target = cx
        .state
        .fs
        .resolve_read(&cx.state.cwd, &path_str)
        .map_err(|e| anyhow::anyhow!("failed to resolve TOML path '{}': {}", path_str, e))?;
    let content = cx
        .state
        .fs
        .read_file(&target)
        .map_err(|e| anyhow::anyhow!("failed to read TOML file '{}': {}", path_str, e))?;
    let content_str = std::str::from_utf8(&content)
        .map_err(|e| anyhow::anyhow!("invalid UTF-8 in TOML file '{}': {}", path_str, e))?;
    load_toml_value(content_str)
}

/// Evaluate a `LOAD_JSON()` function call.
fn evaluate_load_json<P: ProcessManager>(args: &[Expr], cx: &mut StepCtx<'_, P>) -> Result<Value> {
    if args.is_empty() {
        bail!("LOAD_JSON requires a path argument");
    }
    let path_val = evaluate_expr(&args[0], cx)?;
    let path_str = match path_val {
        Value::String(s) => s,
        _ => bail!("LOAD_JSON path argument must evaluate to a string"),
    };
    let target = cx
        .state
        .fs
        .resolve_read(&cx.state.cwd, &path_str)
        .map_err(|e| anyhow::anyhow!("failed to resolve JSON path '{}': {}", path_str, e))?;
    let content = cx
        .state
        .fs
        .read_file(&target)
        .map_err(|e| anyhow::anyhow!("failed to read JSON file '{}': {}", path_str, e))?;
    let content_str = std::str::from_utf8(&content)
        .map_err(|e| anyhow::anyhow!("invalid UTF-8 in JSON file '{}': {}", path_str, e))?;
    load_json_value(content_str)
}

/// Parse TOML content into a DSL `Value`.
pub fn load_toml_value(content: &str) -> Result<Value> {
    let json_val: serde_json::Value =
        toml::from_str(content).map_err(|e| anyhow::anyhow!("TOML parse error: {}", e))?;
    Ok(json_to_value(json_val))
}

/// Parse JSON content into a DSL `Value`.
pub fn load_json_value(content: &str) -> Result<Value> {
    let json_val: serde_json::Value =
        serde_json::from_str(content).map_err(|e| anyhow::anyhow!("JSON parse error: {}", e))?;
    Ok(json_to_value(json_val))
}

/// Convert a `serde_json::Value` to a DSL `Value`.
fn json_to_value(v: serde_json::Value) -> Value {
    match v {
        serde_json::Value::String(s) => Value::String(s),
        serde_json::Value::Bool(b) => Value::Bool(b),
        serde_json::Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                Value::Int(i)
            } else if let Some(f) = n.as_f64() {
                Value::String(f.to_string())
            } else {
                Value::String(n.to_string())
            }
        }
        serde_json::Value::Array(arr) => Value::List(arr.into_iter().map(json_to_value).collect()),
        serde_json::Value::Object(map) => Value::Map(
            map.into_iter()
                .map(|(k, v)| (k, json_to_value(v)))
                .collect(),
        ),
        serde_json::Value::Null => Value::String(String::new()),
    }
}

/// Single-pass string expansion: handles escapes and `{{ }}` template tags.
///
/// `{{ $var }}` — interpolates script variable (supports key-paths: `{{ $d.name.0 }}`).
/// `{{ env:KEY }}` — interpolates environment variable.
/// Bare `$` is literal text — `{{ }}` is the ONLY interpolation trigger.
///
/// Escape rules:
/// - `\\` → literal `\`
/// - `\{{` → literal `{{` (skip template expansion)
/// - `\n`, `\t`, `\r`, `\"` → control characters
/// - Unrecognized `\X` → literal `\X`
pub(crate) fn expand_string<P: ProcessManager>(
    input: &str,
    env: &std::collections::HashMap<String, String>,
    state: &ExecState<P>,
) -> Result<String> {
    let mut output = String::with_capacity(input.len());
    let mut chars = input.chars().peekable();
    while let Some(c) = chars.next() {
        match c {
            '\\' => match chars.peek() {
                Some(&'\\') => {
                    output.push('\\');
                    chars.next();
                }
                Some(&'{') => {
                    // Check for \{{ (literal {{)
                    let mut lookahead = chars.clone();
                    lookahead.next(); // skip first {
                    if lookahead.next() == Some('{') {
                        output.push_str("{{");
                        chars.next(); // skip first {
                        chars.next(); // skip second {
                    } else {
                        output.push('\\');
                    }
                }
                Some(&'n') => {
                    output.push('\n');
                    chars.next();
                }
                Some(&'t') => {
                    output.push('\t');
                    chars.next();
                }
                Some(&'r') => {
                    output.push('\r');
                    chars.next();
                }
                Some(&'"') => {
                    output.push('"');
                    chars.next();
                }
                _ => {
                    output.push('\\');
                }
            },
            '{' if chars.peek() == Some(&'{') => {
                chars.next(); // consume second {
                let mut template_key = String::new();
                let mut found_close = false;
                while let Some(ch) = chars.next() {
                    if ch == '}' && chars.peek() == Some(&'}') {
                        chars.next(); // consume second }
                        found_close = true;
                        break;
                    }
                    template_key.push(ch);
                }
                if found_close {
                    let key = template_key.trim();
                    if let Some(var_expr) = key.strip_prefix('$') {
                        // {{ $var }} or {{ $var.path.0 }} — look up in scope chain.
                        // Parse key-path from the extracted string, NOT from chars.
                        // Trim whitespace from segments to tolerate spaces around dots.
                        let mut parts = var_expr.split('.');
                        if let Some(base_var) = parts.next() {
                            let base_trim = base_var.trim();
                            let mut current = state
                                .get_var(base_trim)
                                .or_else(|| env.get(base_trim).map(|v| Value::String(v.clone())));
                            for part in parts {
                                let part_trim = part.trim();
                                current = match current {
                                    Some(Value::Map(map)) => map.get(part_trim).cloned(),
                                    Some(Value::List(list)) => part_trim
                                        .parse::<usize>()
                                        .ok()
                                        .and_then(|idx| list.get(idx).cloned()),
                                    _ => None,
                                };
                                if current.is_none() {
                                    break;
                                }
                            }
                            if let Some(v) = current {
                                output.push_str(&format_value_for_string(&v));
                            }
                            // Missing → emit empty
                        }
                    } else {
                        // {{ env:KEY }} — look up in env (script + process)
                        // {{ script_env:KEY }} — explicit script env
                        // {{ bare_key }} — DSL variable only, NOT env
                        if let Some(env_key) = key
                            .strip_prefix("env:")
                            .or_else(|| key.strip_prefix("script_env:"))
                        {
                            if let Some(val) = env.get(env_key) {
                                output.push_str(val);
                            }
                            // Missing → emit empty
                        } else if let Some(val) = state.get_var(key) {
                            output.push_str(&format_value_for_string(&val));
                        }
                        // Bare key not in DSL vars → emit empty
                    }
                } else {
                    // Unclosed template — preserve verbatim
                    output.push_str("{{");
                    output.push_str(&template_key);
                }
            }
            _ => {
                output.push(c);
            }
        }
    }
    Ok(output)
}

/// Expand bare `$var` references in a string using DSL scope.
/// Used by RUN commands to expand DSL variables before passing to shell.
/// Undefined variables are left as-is (shell will handle them).
pub(crate) fn expand_dsl_vars<P: ProcessManager>(input: &str, state: &ExecState<P>) -> String {
    let mut output = String::with_capacity(input.len());
    let mut chars = input.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '$' {
            let mut var_name = String::new();
            while let Some(&ch) = chars.peek() {
                if ch.is_ascii_alphanumeric() || ch == '_' {
                    var_name.push(ch);
                    chars.next();
                } else {
                    break;
                }
            }
            if var_name.is_empty() {
                output.push('$');
                continue;
            }
            if let Some(val) = state.get_var(&var_name) {
                output.push_str(&format_value_for_string(&val));
            } else {
                output.push('$');
                output.push_str(&var_name);
            }
        } else {
            output.push(c);
        }
    }
    output
}

/// Format a `Value` as a string for inline interpolation.
pub(crate) fn format_value_for_string(val: &Value) -> String {
    match val {
        Value::String(s) => s.clone(),
        Value::Int(i) => i.to_string(),
        Value::Bool(b) => b.to_string(),
        Value::List(items) => items
            .iter()
            .map(format_value_for_string)
            .collect::<Vec<_>>()
            .join(" "),
        Value::Map(map) => map
            .iter()
            .map(|(k, v)| format!("\"{}\": {}", k, format_value_for_string(v)))
            .collect::<Vec<_>>()
            .join(", "),
        Value::TaskHandle(id) => format!("task#{}", id),
    }
}