ribir_macros 0.4.0-alpha.65

A non-intrusive declarative GUI framework, to build modern native/wasm cross-platform applications.
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
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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
//! Asset processing framework for compile-time asset handling.
//!
//! This module provides the core infrastructure for the `asset!` and
//! `include_asset!` macros, enabling compile-time processing and runtime
//! loading of various asset types.
//!
//! # Architecture
//!
//! The framework separates concerns into two layers:
//!
//! - **Asset Trait**: Defines how specific asset types process data and
//!   generate load expressions. Implementors focus only on data transformation.
//! - **Framework Layer**: Handles all common logic including path resolution,
//!   file I/O, caching, embed/bundle decisions, and code generation.
//!
//! # Supported Asset Types
//!
//! | Type | Macro Syntax | Return Type | Description |
//! |------|--------------|-------------|-------------|
//! | Binary | `asset!("file.bin")` | `Vec<u8>` | Raw bytes, no processing |
//! | Text | `asset!("file.txt", "text")` | `String` | UTF-8 text |
//! | SVG | `asset!("file.svg", "svg")` | `Svg` | Compressed at compile-time |
//! | Image | `asset!("file.png", "image")` | `Image` | Converted to WebP |
//!
//! # Adding New Asset Types
//!
//! To add a new asset type, implement the [`Asset`] trait:
//!
//! ```ignore
//! struct MyAsset;
//!
//! impl Asset for MyAsset {
//!   fn process(&self, ctx: &AssetContext) -> syn::Result<Option<Vec<u8>>> {
//!     // Transform input data, or return None to use original
//!     let data = std::fs::read(&ctx.abs_input)?;
//!     Ok(Some(transform(data)))
//!   }
//!
//!   fn output_extension(&self) -> Option<&str> {
//!     Some("myext") // If output extension differs from input
//!   }
//!
//!   fn load_expr(&self, data_expr: TokenStream) -> TokenStream {
//!     quote! { MyType::from_bytes(#data_expr) }
//!   }
//! }
//! ```
//!
//! Then register it in [`AssetArgs::parse()`].

use std::{
  fs,
  path::{Path, PathBuf},
};

use proc_macro2::TokenStream;
use quote::quote;
use syn::{Ident, LitBool, LitStr, parse::Parse};

mod basic;
mod image;
mod svg;

use basic::{BinaryAsset, TextAsset};
use image::ImageAsset;
use svg::SvgAsset;

const RIBIR_BUNDLE_MODE_ENV: &str = "RIBIR_BUNDLE_MODE";

/// Controls how `asset!` chooses its runtime path strategy during compilation.
///
/// - `None`: normal build, generate absolute runtime paths.
/// - `Debug` / `Release`: bundle build, write outputs into the matching
///   `target/{debug|release}/assets/` dir and generate bundle-relative runtime
///   paths.
#[derive(Clone, Debug, Eq, PartialEq)]
enum BundleAssetMode {
  None,
  Debug,
  Release,
}

impl BundleAssetMode {
  fn from_env() -> syn::Result<Self> {
    match std::env::var(RIBIR_BUNDLE_MODE_ENV) {
      Ok(value) => match value.as_str() {
        "" | "none" => Ok(Self::None),
        "debug" => Ok(Self::Debug),
        "release" | "1" => Ok(Self::Release),
        other => Err(syn::Error::new(
          proc_macro2::Span::call_site(),
          format!(
            "Invalid {RIBIR_BUNDLE_MODE_ENV} value '{other}', expected one of: none, debug, \
             release"
          ),
        )),
      },
      Err(_) => Ok(Self::None),
    }
  }

  fn asset_dir_name(&self) -> Option<&'static str> {
    match self {
      Self::None => None,
      Self::Debug => Some("debug"),
      Self::Release => Some("release"),
    }
  }

  fn uses_bundle_runtime_path(&self) -> bool { !matches!(self, Self::None) }
}

// =============================================================================
// Public API
// =============================================================================

/// Generates asset loading code for the `asset!` macro.
///
/// Assets are copied to the target directory and loaded at runtime. The
/// original file is tracked via `include_bytes!` to trigger recompilation on
/// changes.
///
/// # Path Resolution
///
/// Paths are resolved relative to the source file containing the macro call,
/// similar to `include_str!` in Rust.
///
/// # Examples
///
/// ```ignore
/// // Binary (default)
/// let data: Vec<u8> = asset!("image.png");
///
/// // Text
/// let config: String = asset!("config.json", "text");
///
/// // SVG with parameters
/// let icon: Svg = asset!("icon.svg", "svg", inherit_fill = true);
///
/// // Image (auto-converted to WebP)
/// let img: Image = asset!("photo.jpg", "image");
/// ```
pub fn gen_asset(input: TokenStream) -> TokenStream { gen_asset_internal(input, false) }

/// Generates asset embedding code for the `include_asset!` macro.
///
/// Unlike `asset!`, this embeds the processed asset directly into the binary,
/// similar to `include_bytes!`. No external files are needed at runtime.
///
/// # Examples
///
/// ```ignore
/// // Embed SVG directly in binary
/// let icon: Svg = include_asset!("icon.svg", "svg");
///
/// // Embed image (converted to WebP, then embedded)
/// let img: Image = include_asset!("photo.png", "image");
/// ```
pub fn gen_include_asset(input: TokenStream) -> TokenStream { gen_asset_internal(input, true) }

// =============================================================================
// Asset Trait
// =============================================================================

/// Trait for defining asset type handlers.
///
/// Implementors only need to focus on:
/// - **Data processing**: Transform input bytes (compression, format
///   conversion, etc.)
/// - **Output extension**: Specify if the output file extension differs from
///   input
/// - **Load expression**: Generate code to construct the final value from bytes
///
/// The framework handles all common concerns: path resolution, file I/O,
/// caching, embed vs runtime loading, and change tracking.
pub(crate) trait Asset {
  /// Process input data and return transformed bytes.
  ///
  /// Return `Some(data)` with processed bytes, or `None` to use the original
  /// input unchanged (e.g., for binary assets that need no transformation).
  fn process(&self, ctx: &AssetContext) -> syn::Result<Option<Vec<u8>>>;

  /// Return the output file extension if it differs from the input.
  ///
  /// For example, `ImageAsset` returns `Some("webp")` because it converts
  /// all image formats to WebP. Return `None` to keep the original extension.
  fn output_extension(&self) -> Option<&str> { None }

  /// Generate the load expression that constructs the final asset value.
  ///
  /// # Arguments
  ///
  /// * `data_expr` - A `Cow<[u8]>` expression containing either:
  ///   - Embedded bytes: `Cow::Borrowed(&[...])`
  ///   - Runtime read: `Cow::Owned(std::fs::read(...))`
  ///
  /// # Returns
  ///
  /// A `TokenStream` that evaluates to the final asset type (e.g., `Svg`,
  /// `Image`).
  fn load_expr(&self, data_expr: TokenStream) -> TokenStream;
}

// =============================================================================
// Code Generation
// =============================================================================

fn gen_asset_internal(input: TokenStream, embed: bool) -> TokenStream {
  match syn::parse2::<AssetArgs>(input).and_then(|args| process_and_generate(args, embed)) {
    Ok(ts) => ts,
    Err(e) => e.to_compile_error(),
  }
}

fn process_and_generate(args: AssetArgs, embed: bool) -> syn::Result<TokenStream> {
  let ctx = prepare_asset_context(&args.input, embed)?;
  generate_for_asset(args.asset.as_ref(), &ctx)
}

/// Unified code generation for all asset types.
///
/// This function handles the common logic:
/// 1. Calculate output path (with potential extension change)
/// 2. Process and cache the asset if outdated
/// 3. Generate either embedded bytes or runtime load code
/// 4. Wrap with `include_bytes!` for change tracking
fn generate_for_asset(asset: &dyn Asset, ctx: &AssetContext) -> syn::Result<TokenStream> {
  // Calculate output path (considering extension change)
  let output_path = match asset.output_extension() {
    Some(ext) => ctx.abs_output.with_extension(ext),
    None => ctx.abs_output.clone(),
  };

  // Process and write if needed
  let processed = if ctx.needs_update(&output_path) {
    let data = asset.process(ctx)?;
    match &data {
      Some(bytes) => {
        fs::write(&output_path, bytes).map_err(|e| ctx.error(format!("Write failed: {e}")))?;
      }
      None => {
        fs::copy(&ctx.abs_input, &output_path)
          .map_err(|e| ctx.error(format!("Copy failed: {e}")))?;
      }
    }
    data
  } else {
    None // Will read from cache if embedding
  };

  // Generate data expression (Cow<[u8]>)
  let data_expr = if ctx.embed {
    let bytes = match processed {
      Some(data) => data,
      None => fs::read(&output_path).map_err(|e| ctx.error(format!("Read cached: {e}")))?,
    };
    quote! { std::borrow::Cow::Borrowed(&[#(#bytes),*][..]) }
  } else {
    let path = ctx.runtime_path_tokens(asset.output_extension());
    quote! { std::borrow::Cow::<[u8]>::Owned(std::fs::read(#path).expect("Failed to read asset")) }
  };

  // Record in manifest for bundle packaging (skip for embedded assets)
  if !ctx.embed {
    append_to_manifest(
      &ctx.abs_input.to_string_lossy(),
      &output_path,
      &ctx.relative_output_with_ext(asset.output_extension()),
      ctx.input_span,
    )?;
  }

  // Generate final expression with include_bytes for change tracking
  let abs_input = ctx.abs_input.to_string_lossy().into_owned();
  let load = asset.load_expr(data_expr);

  Ok(quote! {
    {
      // This ensures recompilation when the source file changes
      const _: &[u8] = include_bytes!(#abs_input);
      #load
    }
  })
}

// =============================================================================
// Macro Argument Parsing
// =============================================================================

/// Parsed arguments from `asset!` or `include_asset!` macro invocation.
pub struct AssetArgs {
  /// The input file path literal.
  pub input: LitStr,
  /// The asset handler for processing and code generation.
  asset: Box<dyn Asset>,
}

impl Parse for AssetArgs {
  fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
    let input_str = input.parse::<LitStr>()?;

    let asset: Box<dyn Asset> = if input.parse::<syn::Token![,]>().is_ok() {
      let type_str = input.parse::<LitStr>()?;
      match type_str.value().to_lowercase().as_str() {
        "text" => Box::new(TextAsset),
        "svg" => {
          let params = parse_key_value_params(input)?;
          let inherit_fill = get_bool_param(&params, "inherit_fill", type_str.span())?;
          let inherit_stroke = get_bool_param(&params, "inherit_stroke", type_str.span())?;
          Box::new(SvgAsset { inherit_fill, inherit_stroke })
        }
        "image" => Box::new(ImageAsset),
        _ => Box::new(BinaryAsset),
      }
    } else {
      Box::new(BinaryAsset)
    };

    Ok(AssetArgs { input: input_str, asset })
  }
}

/// Parsed parameter value (bool or string literal).
enum ParamValue {
  Bool(bool),
  String(String),
}

/// Parse optional key=value parameters after the type string.
fn parse_key_value_params(
  input: syn::parse::ParseStream,
) -> syn::Result<std::collections::HashMap<String, ParamValue>> {
  let mut params = std::collections::HashMap::new();

  while input.parse::<syn::Token![,]>().is_ok() {
    let key: Ident = input.parse()?;
    input.parse::<syn::Token![=]>()?;

    let value = if let Ok(b) = input.parse::<LitBool>() {
      ParamValue::Bool(b.value)
    } else if let Ok(s) = input.parse::<LitStr>() {
      ParamValue::String(s.value())
    } else {
      return Err(syn::Error::new(key.span(), "Expected bool or string literal"));
    };
    params.insert(key.to_string(), value);
  }
  Ok(params)
}

/// Extract a boolean parameter from the parsed params map.
fn get_bool_param(
  params: &std::collections::HashMap<String, ParamValue>, name: &str, span: proc_macro2::Span,
) -> syn::Result<bool> {
  params
    .get(name)
    .map(|v| match v {
      ParamValue::Bool(b) => Ok(*b),
      ParamValue::String(s) => {
        Err(syn::Error::new(span, format!("Expected bool for `{name}`, got string: `{s}`")))
      }
    })
    .transpose()
    .map(|opt| opt.unwrap_or(false))
}

// =============================================================================
// Asset Context
// =============================================================================

/// Context passed to asset handlers during processing.
///
/// Contains all path information and utilities needed by [`Asset`]
/// implementations.
pub(crate) struct AssetContext {
  /// Original input path from the macro (as written by user).
  pub input_path: String,
  /// Absolute path to the input file.
  pub abs_input: PathBuf,
  /// Absolute path to the output file in target directory.
  pub abs_output: PathBuf,
  /// Relative output path (for bundle mode).
  pub relative_output: String,
  /// Span for error reporting.
  pub input_span: proc_macro2::Span,
  /// How runtime paths and asset output dirs should behave during bundling.
  bundle_mode: BundleAssetMode,
  /// Whether embedding (include_asset!) vs runtime loading (asset!).
  pub embed: bool,
}

impl AssetContext {
  /// Create a `syn::Error` with input path context.
  pub fn error(&self, msg: impl std::fmt::Display) -> syn::Error {
    syn::Error::new(self.input_span, format!("{} for '{}'", msg, self.input_path))
  }

  /// Check if processing is needed (source newer than output).
  pub fn needs_update(&self, output: &Path) -> bool {
    match (self.abs_input.metadata(), output.metadata()) {
      (Ok(i), Ok(o)) => match (i.modified(), o.modified()) {
        (Ok(it), Ok(ot)) => it > ot,
        _ => true,
      },
      _ => true,
    }
  }

  pub fn relative_output_with_ext(&self, new_ext: Option<&str>) -> String {
    match new_ext {
      Some(ext) => Path::new(&self.relative_output)
        .with_extension(ext)
        .to_string_lossy()
        .into_owned(),
      None => self.relative_output.clone(),
    }
  }

  /// Generate runtime path expression for loading the asset.
  ///
  /// In bundle mode, generates path relative to executable.
  /// In debug mode, generates absolute path to target directory.
  pub fn runtime_path_tokens(&self, new_ext: Option<&str>) -> TokenStream {
    let relative = self.relative_output_with_ext(new_ext);

    if self.bundle_mode.uses_bundle_runtime_path() {
      #[cfg(target_os = "macos")]
      {
        quote! {
          std::env::current_exe()
            .unwrap()
            .parent()
            .unwrap()
            .parent()
            .unwrap()
            .join("Resources")
            .join(&#relative)
        }
      }

      #[cfg(not(target_os = "macos"))]
      {
        quote! {
          std::env::current_exe()
            .unwrap()
            .parent()
            .unwrap()
            .join(&#relative)
        }
      }
    } else {
      let output = match new_ext {
        Some(ext) => self.abs_output.with_extension(ext),
        None => self.abs_output.clone(),
      };
      let abs = output.to_string_lossy().into_owned();
      quote! { std::path::PathBuf::from(#abs) }
    }
  }
}

// =============================================================================
// Path Resolution & Utilities
// =============================================================================

/// Prepare the asset context from macro input.
fn prepare_asset_context(input: &LitStr, embed: bool) -> syn::Result<AssetContext> {
  let input_path = input.value();
  let span = input.span();
  let bundle_mode = BundleAssetMode::from_env()?;

  let abs_input = resolve_caller_relative_path(&input_path, span)?;

  if !abs_input.exists() {
    return Err(syn::Error::new(span, format!("Asset not found: {abs_input:?}")));
  }
  if !abs_input.is_file() {
    return Err(syn::Error::new(span, format!("Not a file: '{input_path}'")));
  }

  let filename = abs_input
    .file_name()
    .and_then(|n| n.to_str())
    .ok_or_else(|| syn::Error::new(span, "Invalid filename"))?;

  // Generate unique output filename using path hash
  // Use absolute path for hash to ensure same file = same cache regardless of how
  // it's referenced
  let abs_input_str = abs_input.to_string_lossy();
  let path_hash = hash_path(&abs_input_str);
  let hashed_filename = format!("{path_hash}_{filename}");

  // Bundle builds pass an explicit assets dir mode because PROFILE is not
  // guaranteed to be available to proc-macro execution.
  let cargo_profile = bundle_mode
    .asset_dir_name()
    .map(str::to_owned)
    .unwrap_or_else(|| std::env::var("PROFILE").unwrap_or_else(|_| "debug".into()));

  let (manifest_path, workspace_opt) = get_workspace_base(span)?;
  let root = workspace_opt.unwrap_or(manifest_path);
  let base_target = std::env::var_os("CARGO_TARGET_DIR")
    .map(PathBuf::from)
    .map(|p| if p.is_absolute() { p } else { root.join(p) })
    .unwrap_or_else(|| root.join("target"));

  let target_assets_dir = base_target.join(cargo_profile).join("assets");

  if !target_assets_dir.exists() {
    fs::create_dir_all(&target_assets_dir)
      .map_err(|e| syn::Error::new(span, format!("Failed to create dir: {e}")))?;
  }

  let abs_output = target_assets_dir.join(&hashed_filename);
  let relative_output = format!("assets/{hashed_filename}");

  Ok(AssetContext {
    input_path,
    abs_input,
    abs_output,
    relative_output,
    input_span: span,
    bundle_mode,
    embed,
  })
}

fn resolve_caller_relative_path(input_path: &str, span: proc_macro2::Span) -> syn::Result<PathBuf> {
  let path = PathBuf::from(input_path);
  if path.is_absolute() {
    return Ok(path);
  }

  if input_path.starts_with("~/") || input_path == "~" {
    let home = std::env::var("HOME")
      .or_else(|_| std::env::var("USERPROFILE"))
      .map_err(|_| syn::Error::new(span, "Could not find home directory"))?;
    let tail = if input_path.len() > 1 { &input_path[2..] } else { "" };
    return Ok(PathBuf::from(home).join(tail));
  }

  let caller_file = span
    .unwrap()
    .local_file()
    .ok_or_else(|| syn::Error::new(span, "Cannot get source file path from span"))?;

  let caller_dir = caller_file
    .parent()
    .ok_or_else(|| syn::Error::new(span, format!("Invalid source path: {caller_file:?}")))?;

  let resolved = caller_dir.join(input_path);

  if resolved.is_absolute() {
    return Ok(resolved);
  }

  // When resolved is relative, we need to find the right base directory.
  // The span.local_file() behavior differs between contexts:
  // - In workspace: returns path relative to workspace root (e.g.,
  //   "core/src/file.rs")
  // - In cargo package: returns path relative to crate root (e.g., "src/file.rs")
  //
  // Strategy: Try CARGO_MANIFEST_DIR first, then workspace root as fallback.
  let manifest_dir = std::env::var("CARGO_MANIFEST_DIR")
    .map_err(|_| syn::Error::new(span, "CARGO_MANIFEST_DIR not set"))?;
  let manifest_path = PathBuf::from(&manifest_dir);

  // First try: resolve relative to CARGO_MANIFEST_DIR (works for cargo package)
  let candidate = manifest_path.join(&resolved);
  if candidate.exists() {
    return Ok(candidate);
  }

  // Second try: resolve relative to workspace root (works for workspace builds)
  if let Some(workspace_root) = find_workspace_root(&manifest_path) {
    let candidate = workspace_root.join(&resolved);
    if candidate.exists() {
      return Ok(candidate);
    }
  }

  // Return the manifest-based path for error reporting
  Ok(manifest_path.join(&resolved))
}

/// Get manifest directory and workspace root.
fn get_workspace_base(span: proc_macro2::Span) -> syn::Result<(PathBuf, Option<PathBuf>)> {
  let manifest_dir = std::env::var("CARGO_MANIFEST_DIR")
    .map_err(|_| syn::Error::new(span, "CARGO_MANIFEST_DIR not set"))?;
  let manifest_path = PathBuf::from(&manifest_dir);
  Ok((manifest_path.clone(), find_workspace_root(&manifest_path)))
}

/// Generate a short hash of the path for unique filenames.
fn hash_path(path: &str) -> String {
  // Use FNV-1a 64-bit hash for stability across builds
  const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
  const FNV_PRIME: u64 = 0x100_0000_01b3;

  let mut hash = FNV_OFFSET_BASIS;
  for byte in path.bytes() {
    hash ^= byte as u64;
    hash = hash.wrapping_mul(FNV_PRIME);
  }
  format!("{hash:016x}")
}

/// Append asset mapping to manifest file for bundle packaging.
///
/// Manifest format (pipe-separated):
/// source_absolute_path | build_absolute_path | bundle_relative_path |
/// call_location
fn append_to_manifest(
  source_abs: &str, build_abs: &Path, bundle_relative: &str, span: proc_macro2::Span,
) -> syn::Result<()> {
  use std::io::Write;
  let path = build_abs
    .parent()
    .ok_or_else(|| syn::Error::new(span, "Invalid build path"))?
    .join(".asset_manifest.txt");

  let caller_file = span
    .unwrap()
    .local_file()
    .map(|p| p.to_string_lossy().into_owned())
    .unwrap_or_else(|| "unknown".to_string());
  let line = span.unwrap().start().line();
  let col = span.unwrap().start().column();
  let location = format!("{caller_file}:{line}:{col}");

  let mut file = fs::OpenOptions::new()
    .create(true)
    .append(true)
    .open(&path)
    .map_err(|e| syn::Error::new(span, format!("Manifest open failed: {e}")))?;
  writeln!(file, "{source_abs} | {} | {bundle_relative} | {location}", build_abs.display())
    .map_err(|e| syn::Error::new(span, format!("Manifest write failed: {e}")))?;
  Ok(())
}

/// Find workspace root by searching for Cargo.toml with [workspace].
fn find_workspace_root(start: &Path) -> Option<PathBuf> {
  let mut cur = Some(start);
  while let Some(p) = cur {
    let toml = p.join("Cargo.toml");
    if toml.exists() && fs::read_to_string(&toml).is_ok_and(|c| c.contains("[workspace]")) {
      return Some(p.to_path_buf());
    }
    cur = p.parent();
  }
  None
}

#[cfg(test)]
mod tests {
  use std::sync::Mutex;

  use super::{BundleAssetMode, RIBIR_BUNDLE_MODE_ENV};

  static ENV_LOCK: Mutex<()> = Mutex::new(());

  fn with_bundle_mode_env<T>(value: Option<&str>, f: impl FnOnce() -> T) -> T {
    let _guard = ENV_LOCK.lock().unwrap();
    let old = std::env::var(RIBIR_BUNDLE_MODE_ENV).ok();

    match value {
      Some(value) => unsafe { std::env::set_var(RIBIR_BUNDLE_MODE_ENV, value) },
      None => unsafe { std::env::remove_var(RIBIR_BUNDLE_MODE_ENV) },
    }

    let result = f();

    match old {
      Some(value) => unsafe { std::env::set_var(RIBIR_BUNDLE_MODE_ENV, value) },
      None => unsafe { std::env::remove_var(RIBIR_BUNDLE_MODE_ENV) },
    }

    result
  }

  #[test]
  fn bundle_asset_mode_defaults_to_none() {
    with_bundle_mode_env(None, || {
      assert_eq!(BundleAssetMode::from_env().unwrap(), BundleAssetMode::None);
    });
  }

  #[test]
  fn bundle_asset_mode_accepts_explicit_profile_dirs() {
    with_bundle_mode_env(Some("debug"), || {
      assert_eq!(BundleAssetMode::from_env().unwrap(), BundleAssetMode::Debug);
    });
    with_bundle_mode_env(Some("release"), || {
      assert_eq!(BundleAssetMode::from_env().unwrap(), BundleAssetMode::Release);
    });
    with_bundle_mode_env(Some("none"), || {
      assert_eq!(BundleAssetMode::from_env().unwrap(), BundleAssetMode::None);
    });
  }

  #[test]
  fn bundle_asset_mode_rejects_unknown_values() {
    with_bundle_mode_env(Some("bundle"), || {
      let err = BundleAssetMode::from_env().unwrap_err();
      assert!(
        err
          .to_string()
          .contains("Invalid RIBIR_BUNDLE_MODE value")
      );
    });
  }
}