herolib-code 0.3.13

Code analysis and parsing utilities for Rust source files
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
713
714
715
716
717
718
719
720
721
722
723
mod cargo;
mod error;

#[cfg(feature = "rhai")]
pub mod rhai;

pub use cargo::{BinaryTarget, CargoMetadata};
pub use error::{BuilderResult, RustBuilderError};

use cargo::{find_cargo_toml, get_target_dir, parse_cargo_toml};
use herolib_core::text::path_fix;
use std::path::{Path, PathBuf};
use std::process::Command;

/// Build profile selection.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum BuildProfile {
    /// Development build (faster compilation, no optimizations)
    #[default]
    Debug,
    /// Production build (optimized, slower compilation)
    Release,
}

impl BuildProfile {
    /// Returns the cargo flag for this profile
    pub fn cargo_flag(&self) -> &'static str {
        match self {
            BuildProfile::Debug => "",
            BuildProfile::Release => "--release",
        }
    }

    /// Returns the target subdirectory name
    pub fn target_subdir(&self) -> &'static str {
        match self {
            BuildProfile::Debug => "debug",
            BuildProfile::Release => "release",
        }
    }
}

/// Specifies what to build.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BuildTarget {
    /// Build a specific binary by name
    Bin(String),
    /// Build the library
    Lib,
    /// Build a specific example
    Example(String),
    /// Build all binaries
    AllBins,
    /// Build all (default cargo behavior)
    All,
}

impl BuildTarget {
    /// Converts this target to cargo command-line arguments
    pub fn to_cargo_args(&self) -> Vec<&str> {
        match self {
            BuildTarget::Bin(name) => vec!["--bin", name],
            BuildTarget::Lib => vec!["--lib"],
            BuildTarget::Example(name) => vec!["--example", name],
            BuildTarget::AllBins => vec!["--bins"],
            BuildTarget::All => vec![],
        }
    }
}

/// Result of a build operation.
#[derive(Debug, Clone)]
pub struct BuildResult {
    /// Whether the build succeeded
    pub success: bool,

    /// Exit code from cargo
    pub exit_code: i32,

    /// Stdout from cargo
    pub stdout: String,

    /// Stderr from cargo
    pub stderr: String,

    /// Path to the built artifact(s)
    pub artifacts: Vec<PathBuf>,

    /// Path where artifact was copied (if copy_to_hero_bin was set)
    pub copied_to: Option<PathBuf>,
}

/// Builder for Rust project compilation with smart defaults.
///
/// Discovers Cargo.toml by walking up from the starting path,
/// parses project metadata, and provides methods to build and
/// copy binaries to ~/hero/bin.
#[derive(Debug, Clone)]
pub struct RustBuilder {
    /// Starting path (file or directory) - walks up to find Cargo.toml
    start_path: PathBuf,

    /// Resolved path to Cargo.toml (found after discovery)
    cargo_toml_path: Option<PathBuf>,

    /// Parsed cargo metadata
    cargo_metadata: Option<CargoMetadata>,

    /// Build profile: Release or Debug
    profile: BuildProfile,

    /// Specific target to build (binary name, lib, example, etc.)
    target: Option<BuildTarget>,

    /// Additional cargo features to enable
    features: Vec<String>,

    /// Whether to use --all-features
    all_features: bool,

    /// Whether to use --no-default-features
    no_default_features: bool,

    /// Copy output to ~/hero/bin after build
    copy_to_hero_bin: bool,

    /// Custom output directory (overrides ~/hero/bin)
    output_dir: Option<PathBuf>,

    /// Additional cargo arguments
    extra_args: Vec<String>,

    /// Verbosity level
    verbose: bool,
}

impl Default for RustBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl RustBuilder {
    /// Creates a new RustBuilder starting from the current directory.
    pub fn new() -> Self {
        Self {
            start_path: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
            cargo_toml_path: None,
            cargo_metadata: None,
            profile: BuildProfile::Debug,
            target: None,
            features: Vec::new(),
            all_features: false,
            no_default_features: false,
            copy_to_hero_bin: false,
            output_dir: None,
            extra_args: Vec::new(),
            verbose: false,
        }
    }

    /// Creates a new RustBuilder starting from the given path.
    /// The path can be a file or directory - will walk up to find Cargo.toml.
    pub fn from_path<P: AsRef<Path>>(path: P) -> Self {
        let mut builder = Self::new();
        builder.start_path = path.as_ref().to_path_buf();
        builder
    }

    /// Sets the build profile to Release (production).
    pub fn release(mut self) -> Self {
        self.profile = BuildProfile::Release;
        self
    }

    /// Sets the build profile to Debug (development).
    pub fn debug(mut self) -> Self {
        self.profile = BuildProfile::Debug;
        self
    }

    /// Sets the build profile.
    pub fn profile(mut self, profile: BuildProfile) -> Self {
        self.profile = profile;
        self
    }

    /// Build a specific binary by name.
    pub fn bin(mut self, name: impl Into<String>) -> Self {
        self.target = Some(BuildTarget::Bin(name.into()));
        self
    }

    /// Build the library.
    pub fn lib(mut self) -> Self {
        self.target = Some(BuildTarget::Lib);
        self
    }

    /// Build a specific example.
    pub fn example(mut self, name: impl Into<String>) -> Self {
        self.target = Some(BuildTarget::Example(name.into()));
        self
    }

    /// Build all binaries.
    pub fn all_bins(mut self) -> Self {
        self.target = Some(BuildTarget::AllBins);
        self
    }

    /// Enable a specific feature.
    pub fn feature(mut self, feature: impl Into<String>) -> Self {
        self.features.push(feature.into());
        self
    }

    /// Enable multiple features.
    pub fn features(mut self, features: Vec<String>) -> Self {
        self.features.extend(features);
        self
    }

    /// Enable all features.
    pub fn all_features(mut self) -> Self {
        self.all_features = true;
        self
    }

    /// Disable default features.
    pub fn no_default_features(mut self) -> Self {
        self.no_default_features = true;
        self
    }

    /// Copy the built binary to ~/hero/bin after successful build.
    /// Removes existing file at destination before copying.
    pub fn copy_to_hero_bin(mut self) -> Self {
        self.copy_to_hero_bin = true;
        self
    }

    /// Set a custom output directory for copying (instead of ~/hero/bin).
    /// Tilde (~) in paths will be expanded to home directory.
    pub fn output_dir<P: AsRef<Path>>(mut self, path: P) -> Self {
        let path_str = path.as_ref().to_string_lossy();
        let expanded = path_fix(&path_str);
        self.output_dir = Some(PathBuf::from(expanded));
        self
    }

    /// Add extra arguments to pass to cargo.
    pub fn arg(mut self, arg: impl Into<String>) -> Self {
        self.extra_args.push(arg.into());
        self
    }

    /// Enable verbose output.
    pub fn verbose(mut self) -> Self {
        self.verbose = true;
        self
    }

    /// Discovers Cargo.toml and parses metadata.
    /// Called automatically by build() if not called explicitly.
    pub fn discover(&mut self) -> BuilderResult<&CargoMetadata> {
        // Find Cargo.toml
        let cargo_path = find_cargo_toml(&self.start_path).ok_or_else(|| {
            RustBuilderError::CargoTomlNotFound {
                path: self.start_path.clone(),
            }
        })?;

        // Parse metadata
        let metadata = parse_cargo_toml(&cargo_path)?;

        self.cargo_toml_path = Some(cargo_path);
        self.cargo_metadata = Some(metadata);

        Ok(self.cargo_metadata.as_ref().unwrap())
    }

    /// Returns the path to Cargo.toml (after discovery).
    pub fn cargo_toml_path(&self) -> Option<&Path> {
        self.cargo_toml_path.as_deref()
    }

    /// Returns the project root directory (parent of Cargo.toml).
    pub fn project_root(&self) -> Option<&Path> {
        self.cargo_toml_path.as_ref().and_then(|p| p.parent())
    }

    /// Returns parsed cargo metadata (after discovery).
    pub fn metadata(&self) -> Option<&CargoMetadata> {
        self.cargo_metadata.as_ref()
    }

    /// Lists all available binaries in the project.
    pub fn list_binaries(&mut self) -> BuilderResult<Vec<BinaryTarget>> {
        self.discover()?;
        Ok(self
            .cargo_metadata
            .as_ref()
            .map(|m| m.binaries.clone())
            .unwrap_or_default())
    }

    /// Executes the build with configured options.
    pub fn build(mut self) -> BuilderResult<BuildResult> {
        // Discover if not already done
        if self.cargo_metadata.is_none() {
            self.discover()?;
        }

        let project_root = self.project_root().unwrap();
        let metadata = self.cargo_metadata.as_ref().unwrap();

        // Debug: Print build information
        eprintln!("[rust_builder] Starting build...");
        eprintln!("[rust_builder] Project: {}", metadata.name);
        eprintln!("[rust_builder] Root: {}", project_root.display());
        eprintln!("[rust_builder] Profile: {:?}", self.profile);
        eprintln!("[rust_builder] Edition: {}", metadata.edition);

        // Construct cargo command
        let mut cmd = Command::new("cargo");
        cmd.current_dir(project_root);
        cmd.arg("build");

        // Add profile flag
        if !self.profile.cargo_flag().is_empty() {
            cmd.arg(self.profile.cargo_flag());
            eprintln!("[rust_builder] Profile flag: {}", self.profile.cargo_flag());
        }

        // Add target
        if let Some(target) = &self.target {
            let args = target.to_cargo_args();
            eprintln!("[rust_builder] Target: {:?}", target);
            for arg in args {
                cmd.arg(arg);
            }
        } else {
            eprintln!("[rust_builder] Target: all (default)");
        }

        // Add features
        if self.all_features {
            cmd.arg("--all-features");
            eprintln!("[rust_builder] Features: all");
        } else if !self.features.is_empty() {
            cmd.arg("--features");
            cmd.arg(self.features.join(","));
            eprintln!("[rust_builder] Features: {}", self.features.join(","));
        } else if self.no_default_features {
            eprintln!("[rust_builder] Features: none (no defaults)");
        } else {
            eprintln!("[rust_builder] Features: default");
        }

        if self.no_default_features {
            cmd.arg("--no-default-features");
        }

        // Add extra args
        for arg in &self.extra_args {
            cmd.arg(arg);
            eprintln!("[rust_builder] Extra arg: {}", arg);
        }

        eprintln!(
            "[rust_builder] Executing: cargo build {:?}",
            self.profile.cargo_flag()
        );

        // Execute build
        let output = cmd.output()?;

        let success = output.status.success();
        let exit_code = output.status.code().unwrap_or(-1);
        let stdout = String::from_utf8_lossy(&output.stdout).to_string();
        let stderr = String::from_utf8_lossy(&output.stderr).to_string();

        eprintln!("[rust_builder] Build exit code: {}", exit_code);
        eprintln!("[rust_builder] Build success: {}", success);

        if self.verbose {
            println!("STDOUT:\n{}", stdout);
            println!("STDERR:\n{}", stderr);
        }

        // Determine artifacts if build succeeded
        let artifacts = if success {
            eprintln!("[rust_builder] Finding artifacts...");
            let arts = self.find_artifacts()?;
            eprintln!("[rust_builder] Found {} artifacts", arts.len());
            for art in &arts {
                eprintln!("[rust_builder] - {}", art.display());
            }
            arts
        } else {
            eprintln!("[rust_builder] Build failed, not finding artifacts");
            return Err(RustBuilderError::BuildFailed {
                code: exit_code,
                stderr,
            });
        };

        // Copy artifacts if requested
        let copied_to = if self.copy_to_hero_bin || self.output_dir.is_some() {
            eprintln!("[rust_builder] Copying artifacts...");
            let dest = self.copy_artifacts(&artifacts)?;
            eprintln!("[rust_builder] Artifacts copied to: {}", dest.display());
            Some(dest)
        } else {
            eprintln!(
                "[rust_builder] Not copying artifacts (copy_to_hero_bin={}, output_dir={})",
                self.copy_to_hero_bin,
                self.output_dir.is_some()
            );
            None
        };

        eprintln!("[rust_builder] Build complete!");

        Ok(BuildResult {
            success,
            exit_code,
            stdout,
            stderr,
            artifacts,
            copied_to,
        })
    }

    /// Finds the built artifacts
    fn find_artifacts(&self) -> BuilderResult<Vec<PathBuf>> {
        let project_root = self.project_root().unwrap();
        let target_dir = get_target_dir(project_root);
        let profile_dir = target_dir.join(self.profile.target_subdir());
        let metadata = self.cargo_metadata.as_ref().unwrap();

        let mut artifacts = Vec::new();

        match &self.target {
            Some(BuildTarget::Bin(name)) | Some(BuildTarget::Example(name)) => {
                let artifact = self.find_binary(&profile_dir, name)?;
                artifacts.push(artifact);
            }
            Some(BuildTarget::Lib) => {
                let lib_name = metadata
                    .lib_name
                    .clone()
                    .unwrap_or_else(|| metadata.name.replace("-", "_"));
                let artifact = self.find_library(&profile_dir, &lib_name)?;
                artifacts.push(artifact);
            }
            Some(BuildTarget::AllBins) => {
                for bin in &metadata.binaries {
                    if let Ok(artifact) = self.find_binary(&profile_dir, &bin.name) {
                        artifacts.push(artifact);
                    }
                }
            }
            Some(BuildTarget::All) | None => {
                // Try to find all binaries
                for bin in &metadata.binaries {
                    if let Ok(artifact) = self.find_binary(&profile_dir, &bin.name) {
                        artifacts.push(artifact);
                    }
                }
                // Try to find library
                if metadata.has_lib {
                    let lib_name = metadata
                        .lib_name
                        .clone()
                        .unwrap_or_else(|| metadata.name.replace("-", "_"));
                    if let Ok(artifact) = self.find_library(&profile_dir, &lib_name) {
                        artifacts.push(artifact);
                    }
                }
            }
        }

        if artifacts.is_empty() {
            return Err(RustBuilderError::ArtifactNotFound { path: profile_dir });
        }

        Ok(artifacts)
    }

    /// Finds a binary artifact
    fn find_binary(&self, profile_dir: &Path, name: &str) -> BuilderResult<PathBuf> {
        let binary_name = if cfg!(windows) {
            format!("{}.exe", name)
        } else {
            name.to_string()
        };

        let artifact = profile_dir.join(&binary_name);
        if artifact.exists() {
            Ok(artifact)
        } else {
            Err(RustBuilderError::BinaryNotFound {
                name: name.to_string(),
            })
        }
    }

    /// Finds a library artifact
    fn find_library(&self, profile_dir: &Path, name: &str) -> BuilderResult<PathBuf> {
        // Try different library naming conventions
        let names = if cfg!(windows) {
            vec![format!("{}.lib", name), format!("{}.dll", name)]
        } else if cfg!(target_os = "macos") {
            vec![format!("lib{}.dylib", name), format!("lib{}.a", name)]
        } else {
            vec![format!("lib{}.so", name), format!("lib{}.a", name)]
        };

        for lib_name in names {
            let artifact = profile_dir.join(&lib_name);
            if artifact.exists() {
                return Ok(artifact);
            }
        }

        Err(RustBuilderError::ArtifactNotFound {
            path: profile_dir.to_path_buf(),
        })
    }

    /// Copies artifacts to the output directory
    fn copy_artifacts(&self, artifacts: &[PathBuf]) -> BuilderResult<PathBuf> {
        // Determine destination directory
        let dest_dir = if let Some(custom_dir) = &self.output_dir {
            custom_dir.clone()
        } else {
            // Expand ~/hero/bin
            let home = dirs::home_dir().ok_or_else(|| {
                RustBuilderError::InvalidConfig("Could not determine home directory".to_string())
            })?;
            home.join("hero").join("bin")
        };

        // Create destination directory if it doesn't exist
        std::fs::create_dir_all(&dest_dir)?;

        let mut last_dest = dest_dir.clone();

        // Copy each artifact
        for artifact in artifacts {
            let file_name = artifact.file_name().ok_or_else(|| {
                RustBuilderError::InvalidConfig(format!(
                    "Could not get filename for {:?}",
                    artifact
                ))
            })?;

            let dest_path = dest_dir.join(file_name);

            // Remove existing file if it exists
            if dest_path.exists() {
                std::fs::remove_file(&dest_path).map_err(|e| RustBuilderError::CopyFailed {
                    message: format!("Failed to remove existing file: {}", e),
                })?;
            }

            // Copy the file
            std::fs::copy(artifact, &dest_path).map_err(|e| RustBuilderError::CopyFailed {
                message: format!("Failed to copy {}: {}", file_name.to_string_lossy(), e),
            })?;

            // Set executable permissions on Unix
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                let perms = std::fs::Permissions::from_mode(0o755);
                std::fs::set_permissions(&dest_path, perms)?;
            }

            last_dest = dest_path;
        }

        Ok(last_dest)
    }
}

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

    fn create_test_cargo_toml(dir: &Path) {
        let content = r#"
[package]
name = "test-project"
version = "1.0.0"
edition = "2021"

[[bin]]
name = "test-app"
path = "src/main.rs"
"#;
        fs::write(dir.join("Cargo.toml"), content).unwrap();
    }

    #[test]
    fn test_builder_new() {
        let builder = RustBuilder::new();
        assert_eq!(builder.profile, BuildProfile::Debug);
        assert_eq!(builder.target, None);
        assert!(!builder.copy_to_hero_bin);
    }

    #[test]
    fn test_builder_from_path() {
        let temp_dir = tempdir().unwrap();
        let builder = RustBuilder::from_path(temp_dir.path());
        assert_eq!(builder.start_path, temp_dir.path());
    }

    #[test]
    fn test_builder_profile_options() {
        let builder = RustBuilder::new().release();
        assert_eq!(builder.profile, BuildProfile::Release);

        let builder = RustBuilder::new().debug();
        assert_eq!(builder.profile, BuildProfile::Debug);
    }

    #[test]
    fn test_builder_target_options() {
        let builder = RustBuilder::new().bin("myapp");
        assert_eq!(builder.target, Some(BuildTarget::Bin("myapp".to_string())));

        let builder = RustBuilder::new().lib();
        assert_eq!(builder.target, Some(BuildTarget::Lib));

        let builder = RustBuilder::new().example("demo");
        assert_eq!(
            builder.target,
            Some(BuildTarget::Example("demo".to_string()))
        );
    }

    #[test]
    fn test_builder_features() {
        let builder = RustBuilder::new().feature("async").feature("tls");
        assert_eq!(builder.features.len(), 2);

        let builder = RustBuilder::new().all_features();
        assert!(builder.all_features);

        let builder = RustBuilder::new().no_default_features();
        assert!(builder.no_default_features);
    }

    #[test]
    fn test_builder_discover() {
        let temp_dir = tempdir().unwrap();
        create_test_cargo_toml(temp_dir.path());

        let mut builder = RustBuilder::from_path(temp_dir.path());
        let metadata = builder.discover().unwrap();

        assert_eq!(metadata.name, "test-project");
        assert_eq!(metadata.version, "1.0.0");
    }

    #[test]
    fn test_builder_cargo_toml_path() {
        let temp_dir = tempdir().unwrap();
        create_test_cargo_toml(temp_dir.path());

        let mut builder = RustBuilder::from_path(temp_dir.path());
        builder.discover().unwrap();

        let cargo_path = builder.cargo_toml_path().unwrap();
        assert!(cargo_path.exists());
        assert_eq!(cargo_path.file_name().unwrap(), "Cargo.toml");
    }

    #[test]
    fn test_builder_project_root() {
        let temp_dir = tempdir().unwrap();
        create_test_cargo_toml(temp_dir.path());

        let mut builder = RustBuilder::from_path(temp_dir.path());
        builder.discover().unwrap();

        let root = builder.project_root().unwrap();
        assert_eq!(root, temp_dir.path());
    }

    #[test]
    fn test_build_target_to_cargo_args() {
        let bin_target = BuildTarget::Bin("myapp".to_string());
        let args = bin_target.to_cargo_args();
        assert_eq!(args, vec!["--bin", "myapp"]);

        let lib_target = BuildTarget::Lib;
        let args = lib_target.to_cargo_args();
        assert_eq!(args, vec!["--lib"]);

        let all_bins_target = BuildTarget::AllBins;
        let args = all_bins_target.to_cargo_args();
        assert_eq!(args, vec!["--bins"]);

        let all_target = BuildTarget::All;
        let args = all_target.to_cargo_args();
        assert!(args.is_empty());
    }

    #[test]
    fn test_build_profile_flags() {
        assert_eq!(BuildProfile::Debug.cargo_flag(), "");
        assert_eq!(BuildProfile::Release.cargo_flag(), "--release");
        assert_eq!(BuildProfile::Debug.target_subdir(), "debug");
        assert_eq!(BuildProfile::Release.target_subdir(), "release");
    }
}