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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
use miette::Result;
use miette::miette;
use mlua::prelude::*;
use regex::Regex;
use std::env;
use std::ffi::OsStr;
use std::ops::Deref;
use std::path::Path;
use std::process::Command;
use std::sync::LazyLock;
use tracing::debug;

use crate::error::FrorkError;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExpandedPath(String);

impl ExpandedPath {
    pub fn new(path: &str) -> Result<Self> {
        Ok(Self(Utils::expand_path(path)?))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }

    pub fn into_string(self) -> String {
        self.0
    }
}

impl From<ExpandedPath> for String {
    fn from(path: ExpandedPath) -> Self {
        path.0
    }
}

impl TryFrom<String> for ExpandedPath {
    type Error = miette::Report;

    fn try_from(path: String) -> Result<Self> {
        Self::new(&path)
    }
}

impl TryFrom<&str> for ExpandedPath {
    type Error = miette::Report;

    fn try_from(path: &str) -> Result<Self> {
        Self::new(path)
    }
}

impl FromLua for ExpandedPath {
    fn from_lua(value: LuaValue, lua: &Lua) -> LuaResult<Self> {
        let path_str = String::from_lua(value, lua)?;
        Self::new(&path_str).map_err(LuaError::external)
    }
}

impl Deref for ExpandedPath {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl AsRef<str> for ExpandedPath {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl AsRef<OsStr> for ExpandedPath {
    fn as_ref(&self) -> &OsStr {
        OsStr::new(&self.0)
    }
}

impl AsRef<Path> for ExpandedPath {
    fn as_ref(&self) -> &Path {
        Path::new(&self.0)
    }
}

impl std::fmt::Display for ExpandedPath {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

pub struct Utils;

impl Utils {
    pub fn chomp(s: &str) -> String {
        s.trim_end_matches('\n').trim_end_matches('\r').to_string()
    }

    pub fn dirname(path: &str) -> Result<Option<String>> {
        let expanded_path = Self::expand_path(path)?;
        let parent = Path::new(&expanded_path).parent();
        Ok(parent.and_then(|p| p.to_str().map(|s| s.to_string())))
    }

    pub fn expand_path(path: &str) -> Result<String> {
        // The pattern is a literal, so it either always compiles or never does.
        #[allow(clippy::unwrap_used)]
        static ENV_VAR_REGEX: LazyLock<Regex> =
            LazyLock::new(|| Regex::new(r"\$([A-Za-z_][A-Za-z0-9_]*)").unwrap());

        let mut expanded = path.to_string();

        // Expand tilde
        if expanded.starts_with('~') {
            let home =
                env::var("HOME").map_err(|_| miette!("HOME environment variable not set"))?;
            expanded = expanded.replacen('~', &home, 1);
        }

        // Expand environment variables
        let mut missing = Vec::new();
        // Groups 0 and 1 are non-optional in the pattern, so a match
        // guarantees both are present.
        #[allow(clippy::unwrap_used)]
        let replaced = ENV_VAR_REGEX.replace_all(&expanded, |caps: &regex::Captures| {
            let var_name = caps.get(1).unwrap().as_str();
            match env::var(var_name) {
                Ok(value) => value,
                Err(_) => {
                    missing.push(var_name.to_string());
                    caps.get(0).unwrap().as_str().to_string()
                }
            }
        });
        expanded = replaced.to_string();

        if !missing.is_empty() {
            return Err(miette!(
                "Environment variables not found: {}",
                missing.join(", ")
            ));
        }

        Ok(expanded)
    }

    pub fn platform() -> Result<String> {
        let (output, _status) = Self::sh("uname", &["-s"])?;
        Ok(Self::chomp(&output).to_lowercase())
    }

    pub fn sh<T: AsRef<str>>(cmd: &str, args: &[T]) -> Result<(String, i32)> {
        Self::sh_with_envs(cmd, args, &[])
    }

    pub fn sh_with_envs<T: AsRef<str>>(
        cmd: &str,
        args: &[T],
        env_vars: &[(&str, &str)],
    ) -> Result<(String, i32)> {
        let args_display: Vec<&str> = args.iter().map(|arg| arg.as_ref()).collect();
        debug!(
            "Executing command: {} with args: {} and envs: {:?}",
            cmd,
            args_display.join(" "),
            env_vars
        );

        let mut command = Command::new(cmd);
        command.args(args.iter().map(|arg| arg.as_ref()));
        command.envs(env_vars.iter().map(|(k, v)| (*k, *v)));

        let output = command
            .output()
            .map_err(|e| miette!("Failed to execute command '{}': {e}", cmd))?;

        // `sh` hands stdout to Fennel as a string, and scripts compare it as
        // text. Non-UTF-8 output would be unusable there either way.
        #[allow(clippy::disallowed_methods)]
        let stdout = String::from_utf8_lossy(&output.stdout).to_string();
        let status = output
            .status
            .code()
            .ok_or_else(|| miette!("Command '{}' terminated by signal", cmd))?;
        let trimmed = stdout.trim();
        debug!(
            "Command '{}' completed with status {}, stdout: {}",
            cmd, status, trimmed
        );
        Ok((stdout, status))
    }

    pub fn assert_bin(bin_name: &str) -> Result<()> {
        // Use 'which' command to check if binary exists in PATH
        let (_output, exit_code) = Self::sh("which", &[bin_name])?;

        if exit_code == 0 {
            debug!("Binary '{}' found in PATH", bin_name);
            Ok(())
        } else {
            Err(miette!("Required binary '{}' not found in PATH", bin_name))
        }
    }
}

impl IntoLua for Utils {
    fn into_lua(self, lua: &Lua) -> LuaResult<LuaValue> {
        let utils_table = lua.create_table()?;

        // Each function is bound before being set: a multi-line `set(...)?`
        // strands the `?` failure path on its own line, where it reads as an
        // uncovered line that no test can reach.
        let expand_path = lua.create_function(|_lua, path: String| {
            Utils::expand_path(&path).map_err(LuaError::external)
        })?;
        utils_table.set("expand-path", expand_path)?;

        let dirname = lua.create_function(|_lua, path: String| {
            Utils::dirname(&path).map_err(LuaError::external)
        })?;
        utils_table.set("dirname", dirname)?;

        let chomp = lua.create_function(|_lua, s: String| Ok(Utils::chomp(&s)))?;
        utils_table.set("chomp", chomp)?;

        let platform = Utils::platform().map_err(LuaError::external)?;
        utils_table.set("platform", platform)?;

        let sh = lua.create_function(|_lua, args: LuaVariadic<String>| {
            let mut args_iter = args.into_iter();
            let cmd = args_iter.next().ok_or_else(|| {
                LuaError::external(FrorkError::InvalidArguments(
                    "sh requires at least a command".to_string(),
                ))
            })?;
            let cmd_args: Vec<String> = args_iter.collect();

            Ok(Utils::sh(&cmd, &cmd_args)
                .map(|(stdout, status)| (Some(stdout), status))
                .unwrap_or((None, -1)))
        })?;
        utils_table.set("sh", sh)?;

        let sh_strict = lua.create_function(|_lua, args: LuaVariadic<String>| {
            let mut args_iter = args.into_iter();
            let cmd = args_iter.next().ok_or_else(|| {
                LuaError::external(FrorkError::InvalidArguments(
                    "sh requires at least a command".to_string(),
                ))
            })?;
            let cmd_args: Vec<String> = args_iter.collect();

            Utils::sh(&cmd, &cmd_args)
                .map(|(stdout, status)| (Some(stdout), status))
                .map_err(LuaError::external)
        })?;
        utils_table.set("sh!", sh_strict)?;

        let assert_bin = lua.create_function(|_lua, bin_name: String| {
            Utils::assert_bin(&bin_name).map_err(LuaError::external)
        })?;
        utils_table.set("assert-bin", assert_bin)?;

        Ok(LuaValue::Table(utils_table))
    }
}

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

    #[test]
    fn test_expand_path_no_variables() {
        let result = Utils::expand_path("/path/to/file");
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "/path/to/file");
    }

    #[test]
    fn test_expand_path_with_tilde() {
        let home = env::var("HOME").unwrap();
        let result = Utils::expand_path("~/file");
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), format!("{}/file", home));
    }

    #[test]
    fn test_expand_path_with_multiple_env_vars() {
        unsafe {
            env::set_var("TEST_VAR1", "value1");
            env::set_var("TEST_VAR2", "value2");
        }
        let result = Utils::expand_path("/$TEST_VAR1/path/$TEST_VAR2/file");
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "/value1/path/value2/file");
        unsafe {
            env::remove_var("TEST_VAR1");
            env::remove_var("TEST_VAR2");
        }
    }

    #[test]
    fn test_expand_path_with_multiple_missing_env_vars() {
        let result = Utils::expand_path("/$MISSING1/path/$MISSING2/file");
        assert!(result.is_err());
        let error = result.unwrap_err();
        let error_str = error.to_string();
        assert!(error_str.contains("Environment variables not found:"));
        assert!(error_str.contains("MISSING1"));
        assert!(error_str.contains("MISSING2"));
    }

    #[test]
    fn test_expand_path_mixed_existing_and_missing() {
        unsafe {
            env::set_var("EXISTING_VAR", "exists");
        }
        let result = Utils::expand_path("/$EXISTING_VAR/path/$MISSING_VAR/file");
        assert!(result.is_err());
        let error = result.unwrap_err();
        assert!(
            error
                .to_string()
                .contains("Environment variables not found: MISSING_VAR")
        );
        unsafe {
            env::remove_var("EXISTING_VAR");
        }
    }

    #[test]
    fn test_expand_path_tilde_and_env_var() {
        let home = env::var("HOME").unwrap();
        unsafe {
            env::set_var("TEST_VAR", "test");
        }
        let result = Utils::expand_path("~/$TEST_VAR/file");
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), format!("{}/test/file", home));
        unsafe {
            env::remove_var("TEST_VAR");
        }
    }

    #[test]
    fn test_sh_through_lua() {
        let lua = mlua::Lua::new();
        let utils = Utils {};
        let utils_table = utils.into_lua(&lua).unwrap();

        lua.globals().set("utils", utils_table).unwrap();

        // Test successful command
        let result: (Option<String>, i32) = lua
            .load(r#"return utils.sh("echo", "hello", "world")"#)
            .eval()
            .unwrap();

        assert_eq!(result.0.unwrap().trim(), "hello world");
        assert_eq!(result.1, 0);

        // Test command with non-zero exit
        let result: (Option<String>, i32) = lua.load(r#"return utils.sh("false")"#).eval().unwrap();

        assert_eq!(result.1, 1);

        // Test sh! with non-zero exit
        let result: (Option<String>, i32) = lua
            .load(r#"return utils["sh!"]("sh", "-c", "exit 42")"#)
            .eval()
            .unwrap();

        assert_eq!(result.1, 42);
    }

    #[test]
    fn test_sh_through_lua_invalid_arguments() {
        let lua = mlua::Lua::new();
        let utils = Utils {};
        let utils_table = utils.into_lua(&lua).unwrap();

        lua.globals().set("utils", utils_table).unwrap();

        // Test with no arguments - should fail
        let result = lua
            .load(r#"return utils.sh()"#)
            .eval::<(Option<String>, i32)>();
        assert!(result.is_err());

        let error = result.unwrap_err();
        assert!(error.to_string().contains("sh requires at least a command"));

        // `sh!` shares the argument check but propagates instead of returning nil.
        let result = lua
            .load(r#"return utils["sh!"]()"#)
            .eval::<(Option<String>, i32)>();
        assert!(result.is_err());
    }

    #[test]
    fn test_expanded_path_conversions() {
        unsafe {
            env::set_var("EXPANDED_PATH_VAR", "expanded");
        }

        let path = ExpandedPath::new("/tmp/$EXPANDED_PATH_VAR").unwrap();

        assert_eq!(path.as_str(), "/tmp/expanded");
        assert_eq!(&*path, "/tmp/expanded");
        assert_eq!(AsRef::<str>::as_ref(&path), "/tmp/expanded");
        assert_eq!(AsRef::<OsStr>::as_ref(&path), OsStr::new("/tmp/expanded"));
        assert_eq!(AsRef::<Path>::as_ref(&path), Path::new("/tmp/expanded"));
        assert_eq!(path.to_string(), "/tmp/expanded");

        assert_eq!(
            ExpandedPath::try_from("/tmp/$EXPANDED_PATH_VAR").unwrap(),
            path
        );
        assert_eq!(
            ExpandedPath::try_from("/tmp/$EXPANDED_PATH_VAR".to_string()).unwrap(),
            path
        );

        assert_eq!(String::from(path.clone()), "/tmp/expanded");
        assert_eq!(path.into_string(), "/tmp/expanded");

        unsafe {
            env::remove_var("EXPANDED_PATH_VAR");
        }
    }

    #[test]
    fn test_expanded_path_from_lua() {
        let lua = mlua::Lua::new();
        let echo = lua
            .create_function(|_lua, path: ExpandedPath| Ok(path.into_string()))
            .unwrap();
        lua.globals().set("echo_path", echo).unwrap();

        let expanded: String = lua
            .load(r#"return echo_path("/tmp/plain")"#)
            .eval()
            .unwrap();
        assert_eq!(expanded, "/tmp/plain");

        // Expansion failures surface as Lua errors rather than panicking.
        let result = lua
            .load(r#"return echo_path("/tmp/$EXPANDED_PATH_MISSING")"#)
            .eval::<String>();
        assert!(result.is_err());
    }

    #[test]
    fn test_dirname() {
        assert_eq!(
            Utils::dirname("/tmp/a/b.txt").unwrap().as_deref(),
            Some("/tmp/a")
        );
        // The filesystem root has no parent.
        assert_eq!(Utils::dirname("/").unwrap(), None);
    }

    #[test]
    fn test_assert_bin() {
        assert!(Utils::assert_bin("sh").is_ok());

        let error = Utils::assert_bin("frork-does-not-exist").unwrap_err();
        assert!(error.to_string().contains("not found in PATH"));
    }

    /// `uname -s`, lowercased — what `Utils::platform` is expected to report.
    #[cfg(target_os = "macos")]
    fn expected_platform() -> &'static str {
        "darwin"
    }

    #[cfg(not(target_os = "macos"))]
    fn expected_platform() -> &'static str {
        "linux"
    }

    #[test]
    fn test_platform() {
        assert_eq!(Utils::platform().unwrap(), expected_platform());
    }

    #[test]
    fn test_sh_reports_minus_one_when_the_command_cannot_spawn() {
        let lua = mlua::Lua::new();
        let utils_table = Utils {}.into_lua(&lua).unwrap();
        lua.globals().set("utils", utils_table).unwrap();

        // A missing binary fails to spawn, which is distinct from running and
        // exiting non-zero: `sh` reports nil and the -1 sentinel.
        let (stdout, exit_code): (Option<String>, i32) = lua
            .load(r#"return utils.sh("frork-does-not-exist")"#)
            .eval()
            .unwrap();

        assert_eq!(stdout, None);
        assert_eq!(exit_code, -1);
    }

    #[test]
    fn test_utils_lua_bindings() {
        let lua = mlua::Lua::new();
        let utils_table = Utils {}.into_lua(&lua).unwrap();
        lua.globals().set("utils", utils_table).unwrap();

        unsafe {
            env::set_var("LUA_BINDING_VAR", "bound");
        }
        let expanded: String = lua
            .load(r#"return utils["expand-path"]("/tmp/$LUA_BINDING_VAR")"#)
            .eval()
            .unwrap();
        assert_eq!(expanded, "/tmp/bound");
        unsafe {
            env::remove_var("LUA_BINDING_VAR");
        }

        let dir: String = lua
            .load(r#"return utils.dirname("/tmp/a/b.txt")"#)
            .eval()
            .unwrap();
        assert_eq!(dir, "/tmp/a");

        let chomped: String = lua.load("return utils.chomp('line\\n')").eval().unwrap();
        assert_eq!(chomped, "line");

        let platform: String = lua.load(r#"return utils.platform"#).eval().unwrap();
        assert_eq!(platform, expected_platform());

        lua.load(r#"utils["assert-bin"]("sh")"#).exec().unwrap();

        let missing = lua
            .load(r#"utils["assert-bin"]("frork-does-not-exist")"#)
            .exec();
        assert!(missing.is_err());
    }

    #[test]
    fn test_sh_debug_logging() {
        // The debug! arguments are evaluated lazily, so they only run with a
        // subscriber active at DEBUG level.
        let subscriber = tracing_subscriber::fmt()
            .with_max_level(tracing::Level::DEBUG)
            .with_test_writer()
            .finish();

        tracing::subscriber::with_default(subscriber, || {
            let (stdout, status) =
                Utils::sh_with_envs("sh", &["-c", "echo $LOGGED"], &[("LOGGED", "value")]).unwrap();
            assert_eq!(stdout.trim(), "value");
            assert_eq!(status, 0);
        });
    }
}