dcr 0.8.4

DCR is a utility for managing C/C++ projects in a Cargo-like style.
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
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
// DCR — Cargo-like C/C++ project manager.
//
// Copyright (C) 2026 Dexoron (Bezotechestvo Vladimir) <main@dexoron.su>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

use crate::core::build_config::Config;
use crate::utils::log::warn;
use std::path::{Path, PathBuf};

/// Version information parsed from a version string.
///
/// Contains the full version, major, minor, patch, suffix, and suffix_dash components.
pub struct VersionInfo {
    pub full: String,
    pub major: String,
    pub minor: String,
    pub patch: String,
    pub suffix: String,
    pub suffix_dash: String,
}

/// Parses a version string into VersionInfo struct.
pub fn parse_version_info(version: &str) -> VersionInfo {
    let mut full = version.trim().to_string();
    if full.is_empty() {
        full = "0.0.0".to_string();
    }
    let (base, suffix) = match full.split_once('-') {
        Some((head, tail)) => (head.to_string(), tail.to_string()),
        None => (full.clone(), String::new()),
    };
    let mut parts = base.split('.');
    let major = parts.next().unwrap_or("0").to_string();
    let minor = parts.next().unwrap_or("0").to_string();
    let patch = parts.next().unwrap_or("0").to_string();
    let suffix_dash = if suffix.is_empty() {
        String::new()
    } else {
        format!("-{suffix}")
    };
    VersionInfo {
        full,
        major,
        minor,
        patch,
        suffix,
        suffix_dash,
    }
}

/// Substitutes profile, name, and version variables into a template string.
pub fn substitute_vars(template: &str, info: &VersionInfo, profile: &str, name: &str) -> String {
    let s = template
        .replace("{profile}", profile)
        .replace("{name}", name);
    substitute_version_vars(&s, info)
}

/// Substitutes version-specific variables into a template string.
pub fn substitute_version_vars(template: &str, info: &VersionInfo) -> String {
    template
        .replace("{version}", &info.full)
        .replace("{version_major}", &info.major)
        .replace("{version_minor}", &info.minor)
        .replace("{version_patch}", &info.patch)
        .replace("{version_suffix}", &info.suffix)
        .replace("{version_suffix_dash}", &info.suffix_dash)
}

/// Normalizes a target string to a relative path for artifact output directory.
pub fn normalize_target(target: &str, profile: &str) -> Option<String> {
    let trimmed = normalize_target_os(target.trim());
    if trimmed.is_empty() {
        None
    } else {
        Some(format!("target/{trimmed}/{profile}"))
    }
}

/// Returns the native host target directory relative to project root for given profile.
pub fn native_host_target_rel(profile: &str) -> PathBuf {
    if cfg!(any(
        target_os = "linux",
        target_os = "freebsd",
        target_os = "openbsd",
        target_os = "netbsd",
        target_os = "dragonfly"
    )) {
        Path::new("target")
            .join(default_target_triple())
            .join(profile)
    } else {
        Path::new("target").join(profile)
    }
}

/// Resolves the artifact output directory for a project/workspace build.
///
/// # Parameters
/// - `project_root`: Package root.
/// - `workspace_root`: If set, artifacts go under the workspace `target/`.
/// - `profile`: Build profile directory segment.
/// - `build_target`: Target triple or short name (may be empty).
/// - `out_dir`: Explicit `out_dir` from config (wins when non-empty).
/// - `has_explicit_target`: Whether CLI/config set a target (changes layout).
///
/// # Returns
/// Absolute directory path as a string.
pub fn resolve_artifact_target_dir(
    project_root: &Path,
    workspace_root: Option<&Path>,
    profile: &str,
    build_target: &str,
    out_dir: &str,
    has_explicit_target: bool,
) -> String {
    if !out_dir.trim().is_empty() {
        let p = Path::new(out_dir.trim());
        return if p.is_absolute() {
            out_dir.trim().to_string()
        } else {
            project_root.join(p).to_string_lossy().into_owned()
        };
    }

    if let Some(ws) = workspace_root {
        let triple = if build_target.trim().is_empty() {
            default_target_triple()
        } else {
            let n = normalize_target_os(build_target.trim());
            if n.is_empty() {
                default_target_triple()
            } else {
                n.to_string()
            }
        };
        return ws
            .join("target")
            .join(triple)
            .join(profile)
            .to_string_lossy()
            .into_owned();
    }

    let base = if has_explicit_target {
        match normalize_target(build_target, profile) {
            Some(rel) => PathBuf::from(rel),
            None => native_host_target_rel(profile),
        }
    } else {
        native_host_target_rel(profile)
    };
    project_root.join(base).to_string_lossy().into_owned()
}

/// Normalizes kind string to standard value, defaulting to "bin" if empty.
pub fn normalize_kind(kind: &str) -> &str {
    let trimmed = kind.trim();
    if trimmed.is_empty() { "bin" } else { trimmed }
}

/// Checks if the kind is a flat binary artifact.
pub fn is_flat_bin(kind: &str) -> bool {
    kind == "flat-bin"
}

/// Returns true for kinds that skip the normal link/archive step: `none`, `custom`, or `flat-bin`.
///
/// Callers that still need a flat-binary path use [`is_flat_bin`] separately
/// (e.g. `is_compile_only(kind) && !is_flat_bin(kind)` before an early return).
///
/// # Parameters
/// - `kind`: Normalized artifact kind string.
///
/// # Returns
/// `true` for `none`, `custom`, or `flat-bin`.
///
/// Callers that still need a flat-binary link use [`is_flat_bin`] separately
/// (e.g. `is_compile_only(kind) && !is_flat_bin(kind)` before early return).
pub fn is_compile_only(kind: &str) -> bool {
    matches!(kind, "none" | "custom" | "flat-bin")
}

/// Normalizes platform string, returning None if empty.
pub fn normalize_platform(platform: &str) -> Option<&str> {
    let trimmed = platform.trim();
    if trimmed.is_empty() {
        None
    } else {
        Some(trimmed)
    }
}

/// Expands short OS names (`linux`/`macos`/`windows`) to default triples; leaves others as-is.
///
/// # Parameters
/// - `target`: Short name, full triple, or empty.
///
/// # Returns
/// Canonical triple string, empty input unchanged, unknown bare names returned with a warning.
pub fn normalize_target_os(target: &str) -> &str {
    match target {
        "" => "",
        "linux" => "x86_64-unknown-linux-gnu",
        "macos" => "x86_64-apple-darwin",
        "windows" => "x86_64-pc-windows-msvc",
        _ if target.contains('-') => target,
        _ => {
            warn(&format!(
                "Unknown target '{}', using as-is. Supported short names: linux, macos, windows",
                target
            ));
            target
        }
    }
}

/// Returns the default target triple for the current host platform.
pub fn default_target_triple() -> String {
    let arch = std::env::consts::ARCH;
    if cfg!(target_os = "linux") {
        let env = if cfg!(target_env = "musl") {
            "musl"
        } else {
            "gnu"
        };
        format!("{arch}-unknown-linux-{env}")
    } else if cfg!(target_os = "macos") {
        format!("{arch}-apple-darwin")
    } else if cfg!(target_os = "windows") {
        let env = if cfg!(target_env = "gnu") {
            "gnu"
        } else {
            "msvc"
        };
        format!("{arch}-pc-windows-{env}")
    } else if cfg!(any(
        target_os = "freebsd",
        target_os = "openbsd",
        target_os = "netbsd",
        target_os = "dragonfly"
    )) {
        format!("{arch}-unknown-{}", std::env::consts::OS)
    } else {
        "unknown".to_string()
    }
}

/// Prepends a --target flag to flags vector if using Clang and not already present.
pub fn prepend_clang_target_flag(flags: &mut Vec<String>, target: Option<&str>, tool: &str) {
    let Some(target) = target.map(str::trim).filter(|t| !t.is_empty()) else {
        return;
    };
    if !tool.to_lowercase().contains("clang") {
        return;
    }

    let target_flag = format!("--target={target}");
    if !flags
        .iter()
        .any(|f| f == &target_flag || f.starts_with("--target="))
    {
        flags.insert(0, target_flag);
    }
}

/// Retrieves a string value from config, falling back to empty string if missing.
pub fn get_config_str(config: &Config, key: &str) -> String {
    config
        .get(key)
        .and_then(|v| v.as_str())
        .unwrap_or("")
        .to_string()
}

/// Retrieves profile-specific table from config.
pub fn profile_table<'a>(config: &'a Config, profile: &str) -> Option<&'a toml::value::Table> {
    config
        .get("build")
        .and_then(|v| v.as_table())
        .and_then(|b| b.get(profile))
        .and_then(|v| v.as_table())
}

/// Retrieves an optional string value from config.
pub fn get_config_opt(config: &Config, key: &str) -> Option<String> {
    let value = config.get(key)?.as_str()?;
    let trimmed = value.trim();
    if trimmed.is_empty() {
        None
    } else {
        Some(trimmed.to_string())
    }
}

/// Retrieves string value with profile override support.
pub fn get_string_with_profile(config: &Config, field: &str, profile: &str) -> String {
    let base = get_config_str(config, &format!("build.{field}"));
    let Some(table) = profile_table(config, profile) else {
        return base;
    };
    let value = table.get(field).and_then(|v| v.as_str()).unwrap_or("");
    let trimmed = value.trim();
    if trimmed.is_empty() {
        base
    } else {
        trimmed.to_string()
    }
}

/// Retrieves list value from config.
pub fn get_config_list(config: &Config, key: &str) -> Vec<String> {
    config
        .get(key)
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str())
                .map(|s| s.to_string())
                .collect()
        })
        .unwrap_or_default()
}

/// Retrieves list value with profile override support.
pub fn get_list_with_profile(config: &Config, field: &str, profile: &str) -> Vec<String> {
    let mut out = get_config_list(config, &format!("build.{field}"));
    if let Some(table) = profile_table(config, profile)
        && let Some(extra) = table.get(field).and_then(|v| v.as_array())
    {
        out.extend(
            extra
                .iter()
                .filter_map(|v| v.as_str())
                .map(|s| s.to_string()),
        );
    }
    out
}

/// Helper function to check if a string contains a pattern ignoring case.
fn contains_ignore_case(text: &str, pattern: &str) -> bool {
    if pattern.len() > text.len() {
        return false;
    }
    text.as_bytes()
        .windows(pattern.len())
        .any(|w| w.eq_ignore_ascii_case(pattern.as_bytes()))
}

/// Checks if target is a bare-metal or embedded target.
pub fn is_bare_metal_target(target: Option<&str>) -> bool {
    match target {
        Some(t) => {
            contains_ignore_case(t, "none")
                || contains_ignore_case(t, "-elf")
                || contains_ignore_case(t, "eabi")
                || contains_ignore_case(t, "baremetal")
                || contains_ignore_case(t, "bare-metal")
        }
        None => false,
    }
}

/// Returns default flags for a given profile.
pub fn default_profile_flags(profile: &str) -> &'static [&'static str] {
    match profile {
        "release" => &["-O3", "-DNDEBUG"],
        "debug" => &[
            "-O0",
            "-g",
            "-Wall",
            "-Wextra",
            "-fno-omit-frame-pointer",
            "-DDCR_DEBUG",
        ],
        _ => &[],
    }
}

/// Retrieves boolean value with profile override support.
pub fn get_bool_with_profile(config: &Config, field: &str, profile: &str, default: bool) -> bool {
    let base = config
        .get(&format!("build.{field}"))
        .and_then(|v| v.as_bool());
    let profile_val =
        profile_table(config, profile).and_then(|t| t.get(field).and_then(|v| v.as_bool()));
    profile_val.or(base).unwrap_or(default)
}

/// Retrieves language from config with profile support.
pub fn get_language_with_profile(config: &Config, profile: &str) -> Result<String, String> {
    if let Some(table) = profile_table(config, profile)
        && let Some(value) = table.get("language")
    {
        return parse_language_value(value, "build.language");
    }
    match config.get("build.language") {
        Some(v) => parse_language_value(v, "build.language"),
        None => Ok("c".to_string()),
    }
}

/// Retrieves language from config with profile support, defaulting to "c" on error.
pub fn get_language_with_profile_or_default(config: &Config, profile: &str) -> String {
    get_language_with_profile(config, profile).unwrap_or_else(|_| "c".to_string())
}

/// Parses language value from config, supporting string or array format.
pub fn parse_language_value(value: &toml::Value, key: &str) -> Result<String, String> {
    if let Some(s) = value.as_str() {
        let trimmed = s.trim();
        if trimmed.is_empty() {
            return Err(format!("{key} is empty"));
        }
        return Ok(trimmed.to_string());
    }
    let arr = value
        .as_array()
        .ok_or_else(|| format!("{key} must be string or array of strings"))?;
    let mut parts = Vec::new();
    for item in arr {
        let s = item
            .as_str()
            .ok_or_else(|| format!("{key} must be string or array of strings"))?;
        let trimmed = s.trim();
        if trimmed.is_empty() {
            return Err(format!("{key} contains empty value"));
        }
        parts.push(trimmed.to_string());
    }
    if parts.is_empty() {
        return Err(format!("{key} is empty"));
    }
    Ok(parts.join(","))
}

/// Resolves compiler name based on language, environment, and toolchain overrides.
pub fn resolve_compiler(
    language: &str,
    compiler: &str,
    tc_cc: Option<&str>,
    tc_cxx: Option<&str>,
    tc_as: Option<&str>,
) -> String {
    let lang = primary_language(language);
    let result = env_override_compiler(&lang)
        .or_else(|| toolchain_override_compiler(&lang, tc_cc, tc_cxx, tc_as))
        .unwrap_or_else(|| compiler.to_string());
    if lang == "asm" {
        map_asm_compiler(&result)
    } else {
        result
    }
}

/// Checks environment variables for compiler override.
fn env_override_compiler(lang: &str) -> Option<String> {
    if let Ok(value) = std::env::var("DCR_COMPILER") {
        let trimmed = value.trim();
        if !trimmed.is_empty() {
            return Some(trimmed.to_string());
        }
    }
    if lang == "asm" {
        if let Ok(value) = std::env::var("DCR_AS") {
            let trimmed = value.trim();
            if !trimmed.is_empty() {
                return Some(trimmed.to_string());
            }
        }
        return None;
    }
    if (lang == "c++" || lang == "cpp" || lang == "cxx")
        && let Ok(value) = std::env::var("DCR_CXX")
    {
        let trimmed = value.trim();
        if !trimmed.is_empty() {
            return Some(trimmed.to_string());
        }
    }
    if let Ok(value) = std::env::var("DCR_CC") {
        let trimmed = value.trim();
        if !trimmed.is_empty() {
            return Some(trimmed.to_string());
        }
    }
    None
}

/// Checks toolchain overrides for compiler.
fn toolchain_override_compiler(
    lang: &str,
    tc_cc: Option<&str>,
    tc_cxx: Option<&str>,
    tc_as: Option<&str>,
) -> Option<String> {
    if lang == "asm" {
        let as_compiler = tc_as.map(|v| v.to_string());
        return as_compiler.map(|v| map_asm_compiler(&v));
    }
    if (lang == "c++" || lang == "cpp" || lang == "cxx")
        && let Some(v) = tc_cxx
    {
        return Some(v.to_string());
    }
    tc_cc.map(|v| v.to_string())
}

/// Maps assembler compiler name to canonical form.
fn map_asm_compiler(compiler: &str) -> String {
    match compiler.to_lowercase().as_str() {
        "gas" | "gnu-as" => "as".to_string(),
        "nasm" => "nasm".to_string(),
        "fasm" | "fasm64" => "fasm".to_string(),
        "masm" | "ml" | "ml64" => "ml".to_string(),
        _ => compiler.to_string(),
    }
}

/// Determines primary language from comma-separated list.
pub fn primary_language(language: &str) -> String {
    let tokens: Vec<&str> = language
        .split(',')
        .map(|s| s.trim())
        .filter(|s| !s.is_empty())
        .collect();
    // Priority: c++ > c > asm.
    for id in ["cxx", "c", "asm"] {
        let hit = tokens.iter().any(|t| {
            crate::core::build::language::language_for_token(t).map(|l| l.id()) == Some(id)
        });
        if hit {
            return id.to_string();
        }
    }
    language.to_lowercase()
}

/// Resolves tool from environment variable or fallback.
pub fn resolve_tool(env_key: &str, fallback: Option<&str>) -> Option<String> {
    if let Ok(value) = std::env::var(env_key) {
        let trimmed = value.trim();
        if !trimmed.is_empty() {
            return Some(trimmed.to_string());
        }
    }
    fallback.map(|v| v.to_string())
}

/// Resolves pkg-config flags for packages.
pub fn resolve_pkg_config_flags(
    pkgs: &[String],
    base_cflags: &[String],
    base_ldflags: &[String],
) -> Result<(Vec<String>, Vec<String>), String> {
    let mut cflags = base_cflags.to_vec();
    let mut ldflags = base_ldflags.to_vec();
    for pkg in pkgs {
        let c_out = run_pkg_config(pkg, "--cflags")?;
        let l_out = run_pkg_config(pkg, "--libs")?;
        cflags.extend(split_flags(&c_out));
        ldflags.extend(split_flags(&l_out));
    }
    Ok((cflags, ldflags))
}

/// Resolves pkg-config flags, falling back on error.
pub fn resolve_pkg_config_flags_lossy(
    pkgs: &[String],
    base_cflags: &[String],
    base_ldflags: &[String],
) -> (Vec<String>, Vec<String>) {
    match resolve_pkg_config_flags(pkgs, base_cflags, base_ldflags) {
        Ok(flags) => flags,
        Err(err) => {
            eprintln!("Warning: {err}");
            (base_cflags.to_vec(), base_ldflags.to_vec())
        }
    }
}

/// Runs pkg-config command and returns output.
pub fn run_pkg_config(pkg: &str, arg: &str) -> Result<String, String> {
    let output = std::process::Command::new("pkg-config")
        .arg(arg)
        .arg(pkg)
        .output()
        .map_err(|err| format!("Failed to run pkg-config: {err}"))?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(format!("pkg-config failed for {pkg}: {stderr}"));
    }
    Ok(String::from_utf8_lossy(&output.stdout).to_string())
}

// The split_flags function parses pkg-config output, handling quoted strings and whitespace to split into individual flags.
fn split_flags(value: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut current = String::new();
    let mut chars = value.chars().peekable();
    let mut quote: Option<char> = None;
    while let Some(ch) = chars.next() {
        if let Some(q) = quote {
            if ch == q {
                quote = None;
            } else {
                current.push(ch);
            }
            continue;
        }
        match ch {
            '\'' | '"' => quote = Some(ch),
            '\\' => {
                if let Some(next) = chars.next() {
                    current.push(next);
                }
            }
            c if c.is_whitespace() => {
                if !current.is_empty() {
                    out.push(std::mem::take(&mut current));
                }
            }
            c => current.push(c),
        }
    }
    if !current.is_empty() {
        out.push(current);
    }
    out
}

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

    /// Test for normalize_target_short_names function.
    #[test]
    fn normalize_target_short_names() {
        assert_eq!(normalize_target_os(""), "");
        assert_eq!(normalize_target_os("linux"), "x86_64-unknown-linux-gnu");
        assert_eq!(normalize_target_os("macos"), "x86_64-apple-darwin");
        assert_eq!(normalize_target_os("windows"), "x86_64-pc-windows-msvc");
        assert_eq!(
            normalize_target_os("x86_64-unknown-linux-gnu"),
            "x86_64-unknown-linux-gnu"
        );
        assert_eq!(normalize_target_os("unknown"), "unknown");
    }

    /// Test for default_target_triple_uses_host_arch function.
    #[test]
    fn default_target_triple_uses_host_arch() {
        let target = default_target_triple();
        if cfg!(target_os = "linux") {
            let env = if cfg!(target_env = "musl") {
                "musl"
            } else {
                "gnu"
            };
            assert_eq!(
                target,
                format!("{}-unknown-linux-{env}", std::env::consts::ARCH)
            );
        } else if cfg!(target_os = "macos") {
            assert_eq!(target, format!("{}-apple-darwin", std::env::consts::ARCH));
        } else if cfg!(target_os = "windows") {
            let env = if cfg!(target_env = "gnu") {
                "gnu"
            } else {
                "msvc"
            };
            assert_eq!(
                target,
                format!("{}-pc-windows-{env}", std::env::consts::ARCH)
            );
        } else if cfg!(any(
            target_os = "freebsd",
            target_os = "openbsd",
            target_os = "netbsd",
            target_os = "dragonfly"
        )) {
            assert_eq!(
                target,
                format!(
                    "{}-unknown-{}",
                    std::env::consts::ARCH,
                    std::env::consts::OS
                )
            );
        } else {
            assert_eq!(target, "unknown");
        }
    }

    /// Test for resolve_artifact_target_dir_native_and_workspace function.
    #[test]
    fn resolve_artifact_target_dir_native_and_workspace() {
        let root = Path::new("/proj");
        let ws = Path::new("/ws");
        let host = default_target_triple();
        let native = resolve_artifact_target_dir(root, None, "debug", &host, "", false);
        let expected_native = root.join(native_host_target_rel("debug"));
        assert_eq!(native, expected_native.to_string_lossy());

        let explicit =
            resolve_artifact_target_dir(root, None, "debug", "x86_64-unknown-linux-gnu", "", true);
        assert!(explicit.contains("x86_64-unknown-linux-gnu"));

        let ws_dir = resolve_artifact_target_dir(root, Some(ws), "debug", &host, "", false);
        assert!(ws_dir.starts_with("/ws") || ws_dir.contains("ws"));
        assert!(ws_dir.contains(&host) || cfg!(windows));
        let out = resolve_artifact_target_dir(root, None, "debug", "", "dist", false);
        assert!(out.contains("dist"));
    }

    /// Test for prepend_clang_target_flag_adds_once_for_clang function.
    #[test]
    fn prepend_clang_target_flag_adds_once_for_clang() {
        let mut flags = vec!["-O2".to_string()];
        prepend_clang_target_flag(&mut flags, Some("aarch64-apple-darwin"), "clang");
        prepend_clang_target_flag(&mut flags, Some("aarch64-apple-darwin"), "clang");
        assert_eq!(
            flags,
            vec![
                "--target=aarch64-apple-darwin".to_string(),
                "-O2".to_string()
            ]
        );
    }

    /// Test for prepend_clang_target_flag_ignores_non_clang_tools function.
    #[test]
    fn prepend_clang_target_flag_ignores_non_clang_tools() {
        let mut flags = vec!["-O2".to_string()];
        prepend_clang_target_flag(&mut flags, Some("aarch64-apple-darwin"), "gcc");
        assert_eq!(flags, vec!["-O2".to_string()]);
    }

    /// Test for parse_version_parts function.
    #[test]
    fn parse_version_parts() {
        let info = parse_version_info("1.2.3-beta");
        assert_eq!(info.full, "1.2.3-beta");
        assert_eq!(info.major, "1");
        assert_eq!(info.minor, "2");
        assert_eq!(info.patch, "3");
        assert_eq!(info.suffix, "beta");
        assert_eq!(info.suffix_dash, "-beta");
    }

    /// Test for normalize_target_with_profile function.
    #[test]
    fn normalize_target_with_profile() {
        let linux = normalize_target_os("linux");
        assert_eq!(
            normalize_target("linux", "debug"),
            Some(format!("target/{linux}/debug"))
        );
        assert_eq!(
            normalize_target(linux, "release"),
            Some(format!("target/{linux}/release"))
        );
        assert_eq!(normalize_target("", "debug"), None);
    }

    /// Test for normalize_kind_empty_defaults_to_bin function.
    #[test]
    fn normalize_kind_empty_defaults_to_bin() {
        assert_eq!(normalize_kind(""), "bin");
        assert_eq!(normalize_kind("  "), "bin");
        assert_eq!(normalize_kind("staticlib"), "staticlib");
        assert_eq!(normalize_kind("  elf  "), "elf");
    }

    /// Test for normalize_platform_empty_is_none function.
    #[test]
    fn normalize_platform_empty_is_none() {
        assert_eq!(normalize_platform(""), None);
        assert_eq!(normalize_platform("  "), None);
        assert_eq!(normalize_platform("native"), Some("native"));
        assert_eq!(normalize_platform(" efi "), Some("efi"));
    }

    /// Test for default_profile_flags_by_profile function.
    #[test]
    fn default_profile_flags_by_profile() {
        assert!(default_profile_flags("debug").contains(&"-O0"));
        assert!(default_profile_flags("debug").contains(&"-g"));
        assert!(default_profile_flags("release").contains(&"-O3"));
        assert!(default_profile_flags("release").contains(&"-DNDEBUG"));
        assert!(default_profile_flags("unknown").is_empty());
    }

    /// Test for is_bare_metal_detects_embedded_targets function.
    #[test]
    fn is_bare_metal_detects_embedded_targets() {
        assert!(is_bare_metal_target(Some("aarch64-none-elf")));
        assert!(is_bare_metal_target(Some("i686-elf")));
        assert!(is_bare_metal_target(Some("armv7e-m-none-eabi")));
        assert!(is_bare_metal_target(Some("riscv32-unknown-none-elf")));
        assert!(!is_bare_metal_target(Some("x86_64-unknown-linux-gnu")));
        assert!(!is_bare_metal_target(None));
    }
}