openjd-expr 0.1.0

Open Job Description expression language — types, evaluation, and path mapping
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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// Copyright by contributors to this project.
// SPDX-License-Identifier: (Apache-2.0 OR MIT)

//! Path method implementations.
//!
//! Uses `path_parse` for format-aware path manipulation instead of
//! `std::path::Path` which only understands the host OS's path format.

use crate::error::ExpressionError;
use crate::function_library::EvalContext;
use crate::path_mapping::PathFormat;
use crate::value::ExprValue;

use super::path_parse as pp;

type R = Result<ExprValue, ExpressionError>;
type Ctx<'a> = &'a mut dyn EvalContext;

fn get_path(a: &ExprValue, ctx: &dyn EvalContext) -> Result<(String, PathFormat), ExpressionError> {
    match a {
        ExprValue::Path { value, format } => Ok((value.clone(), *format)),
        ExprValue::String(s) => Ok((s.clone(), ctx.path_format())),
        _ => Err(ExpressionError::new(format!(
            "Path method not supported on {}",
            a.expr_type()
        ))),
    }
}

fn get_str_arg(a: &[ExprValue], idx: usize) -> String {
    a.get(idx)
        .map(|v| match v {
            ExprValue::String(s) => s.clone(),
            ExprValue::Path { value, .. } => value.clone(),
            _ => String::new(),
        })
        .unwrap_or_default()
}

pub fn as_posix_fn(ctx: Ctx, a: &[ExprValue]) -> R {
    let (path_str, _) = get_path(&a[0], ctx)?;
    Ok(ExprValue::String(path_str.replace('\\', "/")))
}

pub fn with_name_fn(ctx: Ctx, a: &[ExprValue]) -> R {
    let (path_str, fmt) = get_path(&a[0], ctx)?;
    let new_name = get_str_arg(a, 1);
    if new_name.contains('/') || (fmt == PathFormat::Windows && new_name.contains('\\')) {
        return Err(ExpressionError::new(format!(
            "with_name: name must not contain path separators, got '{new_name}'"
        )));
    }
    let parent = pp::parent(&path_str, fmt);
    let sep = pp::sep(fmt);
    Ok(ExprValue::new_path(format!("{parent}{sep}{new_name}"), fmt))
}

pub fn with_stem_fn(ctx: Ctx, a: &[ExprValue]) -> R {
    let (path_str, fmt) = get_path(&a[0], ctx)?;
    let new_stem = get_str_arg(a, 1);
    if new_stem.contains('/') || (fmt == PathFormat::Windows && new_stem.contains('\\')) {
        return Err(ExpressionError::new(format!(
            "with_stem: name must not contain path separators, got '{new_stem}'"
        )));
    }
    let ext = pp::extension(&path_str, fmt);
    let parent = pp::parent(&path_str, fmt);
    let sep = pp::sep(fmt);
    Ok(ExprValue::new_path(
        format!("{parent}{sep}{new_stem}{ext}"),
        fmt,
    ))
}

pub fn with_suffix_fn(ctx: Ctx, a: &[ExprValue]) -> R {
    let (path_str, fmt) = get_path(&a[0], ctx)?;
    let new_suffix = get_str_arg(a, 1);
    ctx.count_string_ops(path_str.len())?;
    if crate::uri_path::is_uri(&path_str) {
        let stem = crate::uri_path::stem(&path_str);
        let parent = crate::uri_path::parent(&path_str);
        return Ok(ExprValue::new_path(
            format!("{parent}/{stem}{new_suffix}"),
            fmt,
        ));
    }
    let stem = pp::file_stem(&path_str, fmt);
    let parent = pp::parent(&path_str, fmt);
    let sep = pp::sep(fmt);
    Ok(ExprValue::new_path(
        format!("{parent}{sep}{stem}{new_suffix}"),
        fmt,
    ))
}

pub fn with_number_fn(ctx: Ctx, a: &[ExprValue]) -> R {
    let (path_str, fmt) = get_path(&a[0], ctx)?;
    let num = match &a[1] {
        ExprValue::Int(n) => *n,
        _ => return Err(ExpressionError::new("with_number() requires int argument")),
    };
    let is_string = matches!(&a[0], ExprValue::String(_));
    let (dir_part, filename) = pp::split(&path_str, fmt);
    let prefix = if dir_part.is_empty() {
        String::new()
    } else {
        format!("{}{}", dir_part, pp::sep(fmt))
    };
    let (stem, suffix) = match filename.rfind('.') {
        Some(i) if i > 0 => (&filename[..i], &filename[i..]),
        _ => (filename, ""),
    };
    let new_stem = with_number_replace(stem, num)?;
    let result = format!("{prefix}{new_stem}{suffix}");
    if is_string {
        Ok(ExprValue::String(result))
    } else {
        Ok(ExprValue::new_path(result, fmt))
    }
}

pub fn is_absolute_fn(ctx: Ctx, a: &[ExprValue]) -> R {
    let (path_str, fmt) = get_path(&a[0], ctx)?;
    Ok(ExprValue::Bool(is_absolute(&path_str, fmt)))
}

/// Cross-platform is_absolute that respects path_format regardless of host OS.
pub fn is_absolute(path_str: &str, fmt: PathFormat) -> bool {
    if crate::uri_path::is_uri(path_str) {
        return true;
    }
    let bytes = path_str.as_bytes();
    // UNC path: //server or \\server
    if bytes.len() >= 2
        && ((bytes[0] == b'/' && bytes[1] == b'/') || (bytes[0] == b'\\' && bytes[1] == b'\\'))
    {
        return true;
    }
    match fmt {
        PathFormat::Windows => {
            bytes.len() >= 3
                && bytes[0].is_ascii_alphabetic()
                && bytes[1] == b':'
                && (bytes[2] == b'\\' || bytes[2] == b'/')
        }
        PathFormat::Posix | PathFormat::Uri => bytes.first() == Some(&b'/'),
    }
}

/// Join two path strings using the separator and absoluteness rules for `fmt`.
///
/// If `right` is absolute (according to `fmt`), it replaces `left` entirely.
/// On Windows, if `right` starts with a single `/` or `\` (root-relative),
/// the drive letter from `left` is preserved (matching `ntpath.join` behavior).
/// Otherwise, `right` is appended to `left` with the appropriate separator.
pub fn join(left: &str, right: &str, fmt: PathFormat) -> String {
    if is_absolute(right, fmt) {
        return right.to_string();
    }
    // Windows root-relative: /foo or \foo (but not \\server) replaces the path
    // but keeps the root from left. Matches ntpath.join behavior.
    // For drive paths (C:\...), the root is "C:".
    // For UNC paths (\\server\share\...), the root is "\\server\share".
    if fmt == PathFormat::Windows {
        let rb = right.as_bytes();
        if rb.first() == Some(&b'/') || rb.first() == Some(&b'\\') {
            let lb = left.as_bytes();
            // Drive path: keep "C:" prefix
            if lb.len() >= 2 && lb[0].is_ascii_alphabetic() && lb[1] == b':' {
                return format!("{}{right}", &left[..2]);
            }
            // UNC path: keep "\\server\share" or "//server/share" prefix
            if let Some(unc_root) = extract_unc_root(left) {
                return format!("{unc_root}{right}");
            }
        }
    }
    let left_is_uri = crate::uri_path::is_uri(left);
    let (sep, trim_chars): (&str, &[char]) = if left_is_uri {
        ("/", &['/'])
    } else {
        match fmt {
            // On Windows, both / and \ are separators
            PathFormat::Windows => ("\\", &['/', '\\']),
            // On POSIX, only / is a separator (\ is a valid filename char)
            PathFormat::Posix | PathFormat::Uri => ("/", &['/']),
        }
    };
    let left = left.trim_end_matches(trim_chars);
    // When appending to a URI from a Windows context, normalize backslashes to forward slashes.
    // In POSIX context, backslashes are valid filename characters and must not be converted.
    let right = if left_is_uri && fmt == PathFormat::Windows {
        std::borrow::Cow::Owned(right.replace('\\', "/"))
    } else {
        std::borrow::Cow::Borrowed(right)
    };
    format!("{left}{sep}{right}")
}

/// Join two path strings without recognizing URIs as absolute.
///
/// Like [`join`], but does not check `is_absolute(right)`. Use when `right` has
/// already been determined to be non-absolute via a URI-unaware check (e.g.,
/// `is_absolute` without URI recognition). This prevents `scheme://...` strings
/// from being treated as absolute when URI support is disabled.
pub fn non_uri_join(left: &str, right: &str, fmt: PathFormat) -> String {
    // Windows root-relative: /foo or \foo keeps the root from left
    if fmt == PathFormat::Windows {
        let rb = right.as_bytes();
        if rb.first() == Some(&b'/') || rb.first() == Some(&b'\\') {
            let lb = left.as_bytes();
            if lb.len() >= 2 && lb[0].is_ascii_alphabetic() && lb[1] == b':' {
                return format!("{}{right}", &left[..2]);
            }
            if let Some(unc_root) = extract_unc_root(left) {
                return format!("{unc_root}{right}");
            }
        }
    }
    let (sep, trim_chars): (&str, &[char]) = match fmt {
        PathFormat::Windows => ("\\", &['/', '\\']),
        PathFormat::Posix | PathFormat::Uri => ("/", &['/']),
    };
    let left = left.trim_end_matches(trim_chars);
    format!("{left}{sep}{right}")
}

/// Extract the UNC root from a path: `\\server\share` or `//server/share`.
/// Returns the root portion (two components after the leading `\\` or `//`).
fn extract_unc_root(path: &str) -> Option<&str> {
    let bytes = path.as_bytes();
    if bytes.len() < 2 {
        return None;
    }
    let prefix_char = bytes[0];
    if !((prefix_char == b'\\' && bytes[1] == b'\\') || (prefix_char == b'/' && bytes[1] == b'/')) {
        return None;
    }
    // Find the separator after "server"
    let rest = &path[2..];
    let sep_after_server = rest.find(['/', '\\'])?;
    let after_server = sep_after_server + 3; // 2 for prefix + 1 for separator
                                             // Find the separator after "share" (or end of string)
    let share_start = after_server;
    let sep_after_share = path[share_start..]
        .find(['/', '\\'])
        .map(|i| share_start + i)
        .unwrap_or(path.len());
    Some(&path[..sep_after_share])
}

fn path_starts_with(path: &str, base: &str, fmt: PathFormat) -> bool {
    if fmt == PathFormat::Windows {
        path.len() >= base.len() && path[..base.len()].eq_ignore_ascii_case(base)
    } else {
        path.starts_with(base)
    }
}

pub fn is_relative_to_fn(ctx: Ctx, a: &[ExprValue]) -> R {
    let (path_str, fmt) = get_path(&a[0], ctx)?;
    let base = get_str_arg(a, 1);
    let is_rel = path_starts_with(&path_str, &base, fmt)
        && (path_str.len() == base.len()
            || base.ends_with('/')
            || base.ends_with('\\')
            || matches!(path_str.as_bytes().get(base.len()), Some(b'/' | b'\\')));
    Ok(ExprValue::Bool(is_rel))
}

pub fn relative_to_fn(ctx: Ctx, a: &[ExprValue]) -> R {
    let (path_str, fmt) = get_path(&a[0], ctx)?;
    let base = get_str_arg(a, 1);
    let is_rel = path_starts_with(&path_str, &base, fmt)
        && (path_str.len() == base.len()
            || base.ends_with('/')
            || base.ends_with('\\')
            || matches!(path_str.as_bytes().get(base.len()), Some(b'/' | b'\\')));
    if !is_rel {
        return Err(ExpressionError::new(format!(
            "relative_to failed: '{path_str}' is not relative to '{base}'"
        )));
    }
    let rel = path_str[base.len()..]
        .trim_start_matches('/')
        .trim_start_matches('\\');
    Ok(ExprValue::new_path(
        if rel.is_empty() {
            ".".to_string()
        } else {
            rel.to_string()
        },
        fmt,
    ))
}

/// Build a closure for `apply_path_mapping` that captures the given rules.
///
/// The rules are stored in an `Arc` so many `FunctionLibrary` clones can
/// share them cheaply. This factory is the only way to produce an
/// `apply_path_mapping` implementation; the host crate passes its rules
/// at library-construction time rather than plumbing them through the
/// evaluator on every call.
pub fn make_apply_path_mapping_fn(
    rules: std::sync::Arc<Vec<crate::path_mapping::PathMappingRule>>,
) -> impl Fn(&mut dyn EvalContext, &[ExprValue]) -> R + Send + Sync + 'static {
    move |ctx, a| {
        let (path_str, fmt) = get_path(&a[0], ctx)?;
        let mapped =
            crate::path_mapping::apply_rules_with_format(&rules, &path_str, ctx.path_format());
        if mapped == path_str {
            Ok(ExprValue::new_path(path_str, fmt))
        } else {
            Ok(ExprValue::new_path(mapped, fmt))
        }
    }
}

fn format_padded(num: i64, width: usize) -> String {
    if num < 0 {
        format!("-{:0>width$}", -num, width = width.saturating_sub(1))
    } else {
        format!("{:0>width$}", num, width = width)
    }
}

const MAX_PADDING_WIDTH: usize = 32;

fn with_number_replace(stem: &str, num: i64) -> Result<String, ExpressionError> {
    // 1. Printf %0Nd or %d
    if let Some(pct) = stem.rfind('%') {
        let after = &stem[pct + 1..];
        if after == "d" {
            return Ok(format!("{}{}", &stem[..pct], num));
        }
        if after.starts_with('0') && after.ends_with('d') {
            let width: usize = after[1..after.len() - 1].parse().unwrap_or(1);
            if width > MAX_PADDING_WIDTH {
                return Err(ExpressionError::new(format!(
                    "with_number: padding width {width} exceeds maximum of {MAX_PADDING_WIDTH}"
                )));
            }
            return Ok(format!("{}{}", &stem[..pct], format_padded(num, width)));
        }
    }
    // 2. Hash pattern ####
    if let Some(start) = stem.rfind('#') {
        let hash_start = stem[..=start]
            .rfind(|c: char| c != '#')
            .map(|i| i + 1)
            .unwrap_or(0);
        let width = start - hash_start + 1;
        if width > MAX_PADDING_WIDTH {
            return Err(ExpressionError::new(format!(
                "with_number: padding width {width} exceeds maximum of {MAX_PADDING_WIDTH}"
            )));
        }
        return Ok(format!(
            "{}{}",
            &stem[..hash_start],
            format_padded(num, width)
        ));
    }
    // 3. Trailing digits
    let digit_start = stem.len()
        - stem
            .chars()
            .rev()
            .take_while(|c| c.is_ascii_digit())
            .count();
    if digit_start < stem.len() {
        let width = stem.len() - digit_start;
        return Ok(format!(
            "{}{}",
            &stem[..digit_start],
            format_padded(num, width)
        ));
    }
    // 4. No pattern — append _NNNN
    Ok(format!("{}_{}", stem, format_padded(num, 4)))
}

// ── Path properties ──

pub fn prop_name(ctx: Ctx, a: &[ExprValue]) -> R {
    let (path_str, fmt) = get_path(&a[0], ctx)?;
    ctx.count_string_ops(path_str.len())?;
    if crate::uri_path::is_uri(&path_str) {
        return Ok(ExprValue::String(crate::uri_path::name(&path_str)));
    }
    Ok(ExprValue::String(pp::file_name(&path_str, fmt).to_string()))
}

pub fn prop_stem(ctx: Ctx, a: &[ExprValue]) -> R {
    let (path_str, fmt) = get_path(&a[0], ctx)?;
    ctx.count_string_ops(path_str.len())?;
    if crate::uri_path::is_uri(&path_str) {
        return Ok(ExprValue::String(crate::uri_path::stem(&path_str)));
    }
    Ok(ExprValue::String(pp::file_stem(&path_str, fmt).to_string()))
}

pub fn prop_suffix(ctx: Ctx, a: &[ExprValue]) -> R {
    let (path_str, fmt) = get_path(&a[0], ctx)?;
    ctx.count_string_ops(path_str.len())?;
    Ok(ExprValue::String(if crate::uri_path::is_uri(&path_str) {
        crate::uri_path::suffix(&path_str)
    } else {
        pp::extension(&path_str, fmt).to_string()
    }))
}

pub fn prop_suffixes(ctx: Ctx, a: &[ExprValue]) -> R {
    let (path_str, fmt) = get_path(&a[0], ctx)?;
    ctx.count_string_ops(path_str.len())?;
    if crate::uri_path::is_uri(&path_str) {
        let suffixes: Vec<ExprValue> = crate::uri_path::suffixes(&path_str)
            .into_iter()
            .map(ExprValue::String)
            .collect();
        return ExprValue::make_list_checked(ctx, suffixes, crate::types::ExprType::STRING);
    }
    let suffixes: Vec<ExprValue> = pp::suffixes(&path_str, fmt)
        .into_iter()
        .map(ExprValue::String)
        .collect();
    ExprValue::make_list_checked(ctx, suffixes, crate::types::ExprType::STRING)
}

pub fn prop_parent(ctx: Ctx, a: &[ExprValue]) -> R {
    let (path_str, fmt) = get_path(&a[0], ctx)?;
    ctx.count_string_ops(path_str.len())?;
    if crate::uri_path::is_uri(&path_str) {
        return Ok(ExprValue::new_path(crate::uri_path::parent(&path_str), fmt));
    }
    Ok(ExprValue::new_path(pp::parent(&path_str, fmt), fmt))
}

pub fn prop_parts(ctx: Ctx, a: &[ExprValue]) -> R {
    let (path_str, fmt) = get_path(&a[0], ctx)?;
    ctx.count_string_ops(path_str.len())?;
    if crate::uri_path::is_uri(&path_str) {
        let parts: Vec<ExprValue> = crate::uri_path::parts(&path_str)
            .into_iter()
            .map(ExprValue::String)
            .collect();
        return ExprValue::make_list_checked(ctx, parts, crate::types::ExprType::STRING);
    }
    let parts: Vec<ExprValue> = pp::parts(&path_str, fmt)
        .into_iter()
        .map(ExprValue::String)
        .collect();
    ExprValue::make_list_checked(ctx, parts, crate::types::ExprType::STRING)
}