lumer 0.1.5

Lumer is a tool for managing Lumi projects
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
//! Lumi CLI lib entry point idk
//!
//! Provides commands to compile Lumi projects and manage packages.

pub mod config;

use clap::{Parser, Subcommand};
use config::PackageConfig;
use miette::{Context, IntoDiagnostic, Result};
use std::{
    env::{current_dir, current_exe},
    fs::{Metadata, create_dir_all, read_dir, write},
    io::ErrorKind,
    path::{Path, PathBuf},
    process::{Command as ProcessCommand, ExitCode, ExitStatus, exit},
    time::SystemTime,
};
/// Lumi command-line interface.
///
/// Provides subcommands to build, run, and manage Lumi packages. This layer
/// orchestrates the compiler binary (`lumic`) and performs basic project
/// discovery so common workflows require minimal flags.
#[derive(Debug, Parser)]
#[command(name = "lumer", about = "Lumi language toolchain (build & run)")]
pub struct Cli {
    #[command(subcommand)]
    cmd: CommandLine,
}

fn should_rebuild(input: &Path, output: &Path) -> bool {
    if !output.exists() {
        return true;
    }
    let Ok(out_meta) = output.metadata() else {
        return true;
    };
    let Ok(out_mtime) = out_meta.modified() else {
        return true;
    };

    let mut newest = latest_mtime(input);
    if let Some(root) = find_project_root() {
        let src_dir = root.join("src");
        if src_dir.exists() {
            newest = max_time(newest, latest_mtime_in_dir(&src_dir));
        }
    }
    newest.map(|t| t > out_mtime).unwrap_or(true)
}

fn latest_mtime(path: &Path) -> Option<SystemTime> {
    let meta = path.metadata().ok()?;
    meta.modified().ok()
}

fn latest_mtime_in_dir(dir: &Path) -> Option<SystemTime> {
    let mut newest: Option<SystemTime> = None;
    let entries = read_dir(dir).ok()?;
    for entry in entries.flatten() {
        let path = entry.path();
        let Ok(meta) = entry.metadata() else {
            continue;
        };
        newest = max_time(newest, newest_from_path(&path, &meta));
    }
    newest
}

fn newest_from_path(path: &Path, meta: &Metadata) -> Option<SystemTime> {
    if meta.is_dir() {
        return latest_mtime_in_dir(path);
    }
    if path.extension().and_then(|e| e.to_str()) != Some("lumi") {
        return None;
    }
    meta.modified().ok()
}

fn max_time(current: Option<SystemTime>, candidate: Option<SystemTime>) -> Option<SystemTime> {
    match (current, candidate) {
        (None, x) => x,
        (x, None) => x,
        (Some(x), Some(y)) => Some(if x > y { x } else { y }),
    }
}

/// Supported `lumi` subcommands.
///
/// Each subcommand models a common task: building a file or project,
/// running a binary, creating or initializing a package, and managing
/// dependencies in `Package.toml`.
#[derive(Debug, Clone, Subcommand)]
pub enum CommandLine {
    /// Build a Lumi source file
    Build {
        /// The input file
        #[arg(value_name = "INPUT")]
        input: Option<PathBuf>,
        /// The output file
        #[arg(short, long, value_name = "OUTPUT")]
        output: Option<PathBuf>,
        /// Build with release profile (target/release)
        #[arg(short, long)]
        release: bool,
        /// Enable verbose compiler output
        #[arg(short, long)]
        verbose: bool,
    },
    /// Build and run a Lumi source file
    Run {
        /// The input file
        #[arg(value_name = "INPUT")]
        input: Option<PathBuf>,
        /// The arguments to pass to the program
        #[arg(value_name = "ARGS", trailing_var_arg = true)]
        args: Vec<String>,
        /// Run with release profile (target/release)
        #[arg(short, long)]
        release: bool,
        /// Enable verbose compiler output
        #[arg(short, long)]
        verbose: bool,
        /// Force rebuild even if an output binary already exists
        #[arg(long)]
        force: bool,
    },
    /// Create a new Lumi package in a new directory
    New {
        /// The name of the new package and directory
        #[arg(value_name = "NAME")]
        name: String,
    },
    /// Initialize a new Lumi package
    Init {
        /// The name of the package
        #[arg(long)]
        name: Option<String>,
    },
}

/// Parses command-line arguments and applies project defaults.
///
/// Resolves missing inputs for `build`/`run` by detecting `Package.toml` and
/// defaulting to `src/main.lumi`. Errors are escalated to process exit when the
/// context is insufficient (e.g., neither input nor project root present).
pub fn parse_cli() -> Cli {
    let mut cli = Cli::parse();
    match &mut cli.cmd {
        CommandLine::Build { input, .. } => {
            if input.is_none() {
                *input = default_main_path().or_else(|| {
                    eprintln!(
                        "Missing input file. Provide a file or run inside a Lumi package with src/main.lumi"
                    );
                    exit(2);
                });
            }
        }
        CommandLine::Run { input, .. } => {
            if input.is_none() {
                *input = default_main_path().or_else(|| {
                    eprintln!(
                        "Missing input file. Provide a file or run inside a Lumi package with src/main.lumi"
                    );
                    exit(2);
                });
            }
        }
        _ => {}
    }
    cli
}
/// Runs the selected command.
///
/// Dispatches to build, run, and package-management operations. For `build`
/// and `run`, this function invokes the compiler (`lumic`) or falls back to a
/// cargo-driven launch when the compiler binary is not directly available.
///
/// # Errors
/// Returns an error if invoking subprocesses fails (e.g., launching `lumic`,
/// running `cargo`, or executing the produced binary). Subcommand-specific
/// operations (like publishing or installing) also propagate their own errors.
pub async fn run() -> Result<ExitCode> {
    let cli = parse_cli();
    match cli.cmd {
        CommandLine::Build {
            input,
            output,
            release,
            verbose,
        } => {
            let input = input.expect("input must be set by parse_cli");
            let out_path = output.unwrap_or_else(|| compute_output_path(&input, release));
            let in_string = input.to_string_lossy().into_owned();
            let out_string = out_path.to_string_lossy().into_owned();
            let mut args = vec![in_string, "-o".to_string(), out_string];
            if verbose {
                args.push("-v".to_string());
            }
            let status = invoke_lumic(args)?;
            Ok(if status.success() {
                ExitCode::SUCCESS
            } else {
                ExitCode::FAILURE
            })
        }
        CommandLine::Run {
            input,
            args,
            release,
            verbose,
            force,
        } => {
            let input = input.as_ref().expect("input must be set by parse_cli");
            let out_path = compute_output_path(input, release);
            if force || should_rebuild(input, &out_path) {
                let in_string = input.to_string_lossy().into_owned();
                let out_string = out_path.to_string_lossy().into_owned();
                let mut build_args = vec![in_string, "-o".to_string(), out_string];
                if verbose {
                    build_args.push("-v".to_string());
                }
                let status_build = invoke_lumic(build_args)?;
                if !status_build.success() {
                    return Ok(ExitCode::FAILURE);
                }
            }
            let status = ProcessCommand::new(&out_path)
                .args(&args)
                .status()
                .into_diagnostic()
                .wrap_err_with(|| format!("Failed to run {}", out_path.display()))?;
            Ok(if status.success() {
                ExitCode::SUCCESS
            } else {
                ExitCode::from(status.code().unwrap_or(1) as u8)
            })
        }
        CommandLine::New { name } => {
            init_package_at(Path::new(&name), &name)?;
            println!("Initialized new Lumi package: {}", name);
            Ok(ExitCode::SUCCESS)
        }
        CommandLine::Init { name } => {
            let package_name = name.unwrap_or_else(|| {
                current_dir()
                    .expect("Failed to get current directory")
                    .file_name()
                    .expect("Failed to get package name")
                    .to_string_lossy()
                    .to_string()
            });
            init_package(&package_name)?;
            Ok(ExitCode::SUCCESS)
        }
    }
}

/// Returns the default `src/main.lumi` path when inside a Lumi project.
///
/// Walks upward from the current directory to locate a `Package.toml`. When
/// found, resolves `src/main.lumi` within that directory if it exists.
fn default_main_path() -> Option<PathBuf> {
    let root = find_project_root()?;
    let main = root.join("src").join("main.lumi");
    if main.exists() { Some(main) } else { None }
}

/// Determines the output path for a build artifact.
///
/// When inside a Lumi project, derives the name from `Package.toml` and emits
/// to `target/<profile>/<name>`. Outside a project, derives from the input file
/// stem as `target/<profile>/<stem>` beside the input.
fn compute_output_path(input: &Path, release: bool) -> PathBuf {
    let profile = if release { "release" } else { "debug" };
    if let Some(root) = find_project_root() {
        let name = PackageConfig::load(root.join("Package.toml"))
            .map(|c| c.name)
            .unwrap_or_else(|_| "app".to_string());
        let out = root.join("target").join(profile).join(name);
        if let Some(parent) = out.parent() {
            let _ = create_dir_all(parent);
        }
        out
    } else {
        let base = input.parent().unwrap_or_else(|| Path::new("."));
        let stem = input.file_stem().and_then(|s| s.to_str()).unwrap_or("app");
        let out = base.join("target").join(profile).join(stem);
        if let Some(parent) = out.parent() {
            let _ = create_dir_all(parent);
        }
        out
    }
}

/// Locates the nearest project root containing `Package.toml`.
///
/// Walks parent directories starting at the current working directory and
/// returns the first directory where `Package.toml` is present.
fn find_project_root() -> Option<PathBuf> {
    let mut dir = current_dir().ok()?;
    loop {
        if dir.join("Package.toml").exists() {
            return Some(dir);
        }
        if !dir.pop() {
            break;
        }
    }
    None
}

/// Invokes the `lumic` compiler with the provided arguments.
///
/// Attempts to execute the `lumic` binary directly. If it is not found in the
/// environment, falls back to `cargo run -p lumic --bin lumic -- <args>` to
/// compile and execute the compiler from the workspace.
///
/// # Errors
/// Returns an error when `cargo` or `lumic` cannot be launched or when the
/// subprocess fails to be created. Note that a non-zero exit status is not an
/// error here; it is returned to the caller for interpretation.
fn invoke_lumic(args: Vec<String>) -> Result<ExitStatus> {
    let sibling_lumic = current_exe()
        .ok()
        .and_then(|exe| exe.parent().map(|dir| dir.join("lumic")));

    if let Some(path) = sibling_lumic
        && path.exists()
    {
        return ProcessCommand::new(&path)
            .args(&args)
            .status()
            .into_diagnostic()
            .wrap_err_with(|| format!("Failed to run sibling lumic at {}", path.display()));
    }

    match ProcessCommand::new("lumic").args(&args).status() {
        Ok(status) => Ok(status),
        Err(error) => {
            if error.kind() == ErrorKind::NotFound {
                let mut cargo_args: Vec<String> =
                    vec!["run", "-q", "-p", "lumic", "--bin", "lumic", "--"]
                        .into_iter()
                        .map(|s| s.to_string())
                        .collect();
                cargo_args.extend(args);
                let status = ProcessCommand::new("cargo")
                    .args(&cargo_args)
                    .status()
                    .into_diagnostic()
                    .wrap_err("Failed to run cargo to launch 'lumic'")?;
                Ok(status)
            } else {
                Err(error)
                    .into_diagnostic()
                    .wrap_err("Failed to launch 'lumic'")
            }
        }
    }
}

/// Initializes a new Lumi package in the current directory.
///
/// Writes `Package.toml`, creates `src/` and `tests/` directories, and writes
/// a simple `src/main.lumi` starter file.
///
/// # Errors
/// Returns an error when writing files or creating directories fails.
fn init_package(name: &str) -> Result<()> {
    let config = PackageConfig::new(name);
    config.save("Package.toml")?;
    create_dir_all("src").into_diagnostic()?;
    create_dir_all("tests").into_diagnostic()?;
    write(
        "src/main.lumi",
        format!(
            r#"fn main() {{
    println("Hello from {name}!");
}}
"#
        ),
    )
    .into_diagnostic()?;
    println!("Initialized new Lumi package: {name}");
    Ok(())
}

/// Initializes a new Lumi package at an arbitrary path.
///
/// Mirrors `init_package` but targets the given `path` instead of the current
/// working directory.
///
/// # Errors
/// Returns an error when writing files or creating directories fails.
fn init_package_at(path: &Path, name: &str) -> Result<()> {
    create_dir_all(path.join("src")).into_diagnostic()?;
    let config = PackageConfig::new(name);
    config.save(path.join("Package.toml"))?;
    write(
        path.join("src").join("main.lumi"),
        format!(
            r#"fn main() {{
    println("Hello from {name}!");
}}
"#
        ),
    )
    .into_diagnostic()?;
    Ok(())
}