mirror of
https://github.com/dexoron/dcr.git
synced 2026-10-21 22:09:35 +00:00
Added:
- `build.steps` for pre-build generators (e.g., `moc`/`uic`/`rcc`)
- `build.pkg_config` for `pkg-config`-driven cflags/ldflags resolution
- `[toolchain]` support for `uic`, `moc`, `rcc`
- Step command variables (`{uic}`, `{moc}`, `{rcc}`, `{cflags}`, `{stem}`, `{in}`, `{out}`)
- `{profile}` placeholder support for dependency paths
This commit is contained in:
480
src/cli/build.rs
480
src/cli/build.rs
@@ -6,9 +6,10 @@ use crate::core::workspace::parse_workspace;
|
||||
use crate::utils::fs::{check_dir, find_project_root};
|
||||
use crate::utils::log::{error, warn};
|
||||
use crate::utils::text::{BOLD_GREEN, colored};
|
||||
use glob::glob;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Instant;
|
||||
|
||||
pub fn build(args: &[String]) -> i32 {
|
||||
@@ -190,8 +191,14 @@ fn build_project_at(
|
||||
let tc_as = get_config_opt(&config, "toolchain.as");
|
||||
let tc_ar = get_config_opt(&config, "toolchain.ar");
|
||||
let tc_ld = get_config_opt(&config, "toolchain.ld");
|
||||
let tc_uic = get_config_opt(&config, "toolchain.uic");
|
||||
let tc_moc = get_config_opt(&config, "toolchain.moc");
|
||||
let tc_rcc = get_config_opt(&config, "toolchain.rcc");
|
||||
let build_cflags = get_config_list(&config, "build.cflags")?;
|
||||
let build_ldflags = get_config_list(&config, "build.ldflags")?;
|
||||
let pkg_configs = get_config_list(&config, "build.pkg_config")?;
|
||||
let build_generated = get_config_list(&config, "build.generated")?;
|
||||
let build_steps = get_build_steps(&config)?;
|
||||
|
||||
let resolved_compiler = resolve_compiler(
|
||||
&build_language,
|
||||
@@ -206,6 +213,8 @@ fn build_project_at(
|
||||
ensure_target_dirs(&items, profile, normalize_target(&build_target));
|
||||
|
||||
let resolved = resolve_deps(&config, profile, project_root)?;
|
||||
let (resolved_cflags, resolved_ldflags) =
|
||||
resolve_pkg_config_flags(&pkg_configs, &build_cflags, &build_ldflags)?;
|
||||
let ctx = BuildContext {
|
||||
profile,
|
||||
project_name: &project_name,
|
||||
@@ -221,14 +230,34 @@ fn build_project_at(
|
||||
include_dirs: &resolved.include_dirs,
|
||||
lib_dirs: &resolved.lib_dirs,
|
||||
libs: &resolved.libs,
|
||||
cflags: &build_cflags,
|
||||
ldflags: &build_ldflags,
|
||||
cflags: &resolved_cflags,
|
||||
ldflags: &resolved_ldflags,
|
||||
};
|
||||
if std::env::var("DCR_DEBUG").is_ok() {
|
||||
eprintln!("[dcr] debug: compiler={}", ctx.compiler);
|
||||
eprintln!("[dcr] debug: cflags={:?}", ctx.cflags);
|
||||
eprintln!("[dcr] debug: ldflags={:?}", ctx.ldflags);
|
||||
eprintln!("[dcr] debug: lib_dirs={:?}", ctx.lib_dirs);
|
||||
eprintln!("[dcr] debug: libs={:?}", ctx.libs);
|
||||
}
|
||||
let tool_execs = resolve_toolchain_execs(&tc_uic, &tc_moc, &tc_rcc, &pkg_configs);
|
||||
let step_flags =
|
||||
build_step_flags(&resolved_cflags, &resolved.include_dirs, &resolved_compiler);
|
||||
let steps_dirty = build_steps_need_run(&build_steps)?;
|
||||
if steps_dirty {
|
||||
clean_generated_files(&build_generated)?;
|
||||
run_build_steps(&build_steps, &tool_execs, &step_flags)?;
|
||||
}
|
||||
let sources = collect_sources(&ctx)?;
|
||||
let headers = collect_header_files(&ctx, project_root)?;
|
||||
let lib_files = collect_lib_files(&ctx);
|
||||
let fingerprint = compute_build_fingerprint(&ctx, &sources, &headers, &lib_files)?;
|
||||
if should_skip_build(&ctx, &fingerprint) {
|
||||
let mut skip = should_skip_build(&ctx, &fingerprint);
|
||||
if steps_dirty {
|
||||
skip = false;
|
||||
}
|
||||
let debug_enabled = std::env::var("DCR_DEBUG").is_ok();
|
||||
if skip && !debug_enabled {
|
||||
return Ok(());
|
||||
}
|
||||
println!(
|
||||
@@ -237,8 +266,10 @@ fn build_project_at(
|
||||
project_name,
|
||||
project_version
|
||||
);
|
||||
run_build(&ctx)?;
|
||||
write_build_fingerprint(&ctx, &fingerprint)?;
|
||||
if !skip {
|
||||
run_build(&ctx)?;
|
||||
write_build_fingerprint(&ctx, &fingerprint)?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
@@ -350,6 +381,443 @@ fn resolve_tool(env_key: &str, fallback: Option<&str>) -> Option<String> {
|
||||
fallback.map(|v| v.to_string())
|
||||
}
|
||||
|
||||
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();
|
||||
if pkgs.is_empty() {
|
||||
return Ok((cflags, ldflags));
|
||||
}
|
||||
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))
|
||||
}
|
||||
|
||||
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())
|
||||
}
|
||||
|
||||
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;
|
||||
continue;
|
||||
}
|
||||
if ch == '\\' {
|
||||
if let Some(next) = chars.next() {
|
||||
current.push(next);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
current.push(ch);
|
||||
continue;
|
||||
}
|
||||
if ch == '"' || ch == '\'' {
|
||||
quote = Some(ch);
|
||||
continue;
|
||||
}
|
||||
if ch.is_whitespace() {
|
||||
if !current.is_empty() {
|
||||
out.push(current.clone());
|
||||
current.clear();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if ch == '\\' {
|
||||
if let Some(next) = chars.next() {
|
||||
current.push(next);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
current.push(ch);
|
||||
}
|
||||
if !current.is_empty() {
|
||||
out.push(current);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
struct ToolchainExecs {
|
||||
uic: String,
|
||||
moc: String,
|
||||
rcc: String,
|
||||
}
|
||||
|
||||
fn resolve_toolchain_execs(
|
||||
uic: &Option<String>,
|
||||
moc: &Option<String>,
|
||||
rcc: &Option<String>,
|
||||
pkg_configs: &[String],
|
||||
) -> ToolchainExecs {
|
||||
let qt_bins = resolve_qt_host_bins(pkg_configs);
|
||||
ToolchainExecs {
|
||||
uic: resolve_qt_tool(uic, qt_bins.as_deref(), "uic"),
|
||||
moc: resolve_qt_tool(moc, qt_bins.as_deref(), "moc"),
|
||||
rcc: resolve_qt_tool(rcc, qt_bins.as_deref(), "rcc"),
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_qt_tool(configured: &Option<String>, qt_bins: Option<&Path>, tool: &str) -> String {
|
||||
if let Some(value) = configured {
|
||||
return value.clone();
|
||||
}
|
||||
if let Some(dir) = qt_bins {
|
||||
let candidate = dir.join(tool);
|
||||
if candidate.is_file() {
|
||||
return candidate.to_string_lossy().to_string();
|
||||
}
|
||||
if cfg!(target_os = "windows") {
|
||||
let candidate = dir.join(format!("{tool}.exe"));
|
||||
if candidate.is_file() {
|
||||
return candidate.to_string_lossy().to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(candidate) = detect_qt6_tool_variant(tool) {
|
||||
return candidate;
|
||||
}
|
||||
tool.to_string()
|
||||
}
|
||||
|
||||
fn resolve_qt_host_bins(pkgs: &[String]) -> Option<PathBuf> {
|
||||
let qt_pkgs: Vec<&String> = pkgs.iter().filter(|p| p.starts_with("Qt6")).collect();
|
||||
if qt_pkgs.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let preferred = ["Qt6Core", "Qt6Widgets", "Qt6Gui"];
|
||||
for name in preferred {
|
||||
if let Some(dir) = query_pkg_config_var(name, "host_bins") {
|
||||
return Some(dir);
|
||||
}
|
||||
if let Some(dir) = query_pkg_config_var(name, "libexecdir")
|
||||
&& let Some(bin) = qt_bins_from_libexec(&dir)
|
||||
{
|
||||
return Some(bin);
|
||||
}
|
||||
if let Some(dir) = query_pkg_config_var(name, "bindir") {
|
||||
return Some(dir);
|
||||
}
|
||||
}
|
||||
for pkg in qt_pkgs {
|
||||
if let Some(dir) = query_pkg_config_var(pkg, "host_bins") {
|
||||
return Some(dir);
|
||||
}
|
||||
if let Some(dir) = query_pkg_config_var(pkg, "libexecdir")
|
||||
&& let Some(bin) = qt_bins_from_libexec(&dir)
|
||||
{
|
||||
return Some(bin);
|
||||
}
|
||||
if let Some(dir) = query_pkg_config_var(pkg, "bindir") {
|
||||
return Some(dir);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn query_pkg_config_var(pkg: &str, var: &str) -> Option<PathBuf> {
|
||||
let output = std::process::Command::new("pkg-config")
|
||||
.arg(format!("--variable={var}"))
|
||||
.arg(pkg)
|
||||
.output()
|
||||
.ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
let value = String::from_utf8_lossy(&output.stdout).trim().to_string();
|
||||
if value.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let path = PathBuf::from(value);
|
||||
if path.is_dir() { Some(path) } else { None }
|
||||
}
|
||||
|
||||
fn qt_bins_from_libexec(libexec: &Path) -> Option<PathBuf> {
|
||||
for tool in ["moc", "uic", "rcc"] {
|
||||
if libexec.join(tool).is_file() {
|
||||
return Some(libexec.to_path_buf());
|
||||
}
|
||||
if cfg!(target_os = "windows") && libexec.join(format!("{tool}.exe")).is_file() {
|
||||
return Some(libexec.to_path_buf());
|
||||
}
|
||||
}
|
||||
let bin = libexec.join("bin");
|
||||
if bin.is_dir() { Some(bin) } else { None }
|
||||
}
|
||||
|
||||
fn detect_qt6_tool_variant(tool: &str) -> Option<String> {
|
||||
[format!("{tool}6"), format!("{tool}-qt6")]
|
||||
.into_iter()
|
||||
.find(|candidate| is_on_path(candidate))
|
||||
}
|
||||
|
||||
fn is_on_path(cmd: &str) -> bool {
|
||||
std::process::Command::new("sh")
|
||||
.arg("-c")
|
||||
.arg(format!("command -v {cmd}"))
|
||||
.output()
|
||||
.map(|o| o.status.success())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct BuildStep {
|
||||
name: String,
|
||||
input: String,
|
||||
output: String,
|
||||
cmd: String,
|
||||
}
|
||||
|
||||
fn get_build_steps(config: &Config) -> Result<Vec<BuildStep>, String> {
|
||||
let value = match config.get("build.steps") {
|
||||
Some(v) => v,
|
||||
None => return Ok(Vec::new()),
|
||||
};
|
||||
let arr = value
|
||||
.as_array()
|
||||
.ok_or_else(|| "build.steps must be an array".to_string())?;
|
||||
let mut out = Vec::new();
|
||||
for item in arr {
|
||||
let tbl = item
|
||||
.as_table()
|
||||
.ok_or_else(|| "build.steps entries must be tables".to_string())?;
|
||||
let name = tbl
|
||||
.get("name")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.trim()
|
||||
.to_string();
|
||||
let input = tbl
|
||||
.get("in")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.trim()
|
||||
.to_string();
|
||||
let output = tbl
|
||||
.get("out")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.trim()
|
||||
.to_string();
|
||||
let cmd = tbl
|
||||
.get("cmd")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.trim()
|
||||
.to_string();
|
||||
if name.is_empty() || input.is_empty() || output.is_empty() || cmd.is_empty() {
|
||||
return Err("build.steps entries must include name, in, out, cmd".to_string());
|
||||
}
|
||||
out.push(BuildStep {
|
||||
name,
|
||||
input,
|
||||
output,
|
||||
cmd,
|
||||
});
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn run_build_steps(
|
||||
steps: &[BuildStep],
|
||||
tools: &ToolchainExecs,
|
||||
step_flags: &str,
|
||||
) -> Result<(), String> {
|
||||
for step in steps {
|
||||
run_build_step(step, tools, step_flags)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run_build_step(
|
||||
step: &BuildStep,
|
||||
tools: &ToolchainExecs,
|
||||
step_flags: &str,
|
||||
) -> Result<(), String> {
|
||||
let inputs = expand_glob(&step.input)?;
|
||||
if inputs.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let needs_stem = step.output.contains("{stem}");
|
||||
if inputs.len() > 1 && !needs_stem {
|
||||
return Err(format!(
|
||||
"build.steps '{}' output must include {{stem}} for multiple inputs",
|
||||
step.name
|
||||
));
|
||||
}
|
||||
for input in inputs {
|
||||
let stem = input.file_stem().and_then(|v| v.to_str()).unwrap_or("");
|
||||
let out_path = PathBuf::from(step.output.replace("{stem}", stem));
|
||||
if !should_run_step(&input, &out_path) {
|
||||
continue;
|
||||
}
|
||||
if let Some(parent) = out_path.parent() {
|
||||
fs::create_dir_all(parent)
|
||||
.map_err(|err| format!("Failed to create step output dir: {err}"))?;
|
||||
}
|
||||
let cmd = substitute_step_cmd(&step.cmd, &input, &out_path, tools, step_flags, stem);
|
||||
let status = run_shell_command(&cmd)
|
||||
.map_err(|err| format!("Failed to run step '{}': {err}", step.name))?;
|
||||
if !status.success() {
|
||||
return Err(format!("Step '{}' failed", step.name));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn clean_generated_files(patterns: &[String]) -> Result<(), String> {
|
||||
for pattern in patterns {
|
||||
for path in expand_glob(pattern)? {
|
||||
if path.is_file() {
|
||||
let _ = fs::remove_file(&path);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn expand_glob(pattern: &str) -> Result<Vec<PathBuf>, String> {
|
||||
let mut out = Vec::new();
|
||||
let entries = glob(pattern).map_err(|err| format!("glob error: {err}"))?;
|
||||
for entry in entries {
|
||||
let path = entry.map_err(|err| format!("glob error: {err}"))?;
|
||||
out.push(path);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn should_run_step(input: &Path, output: &Path) -> bool {
|
||||
let in_time = fs::metadata(input).and_then(|m| m.modified());
|
||||
let out_time = fs::metadata(output).and_then(|m| m.modified());
|
||||
match (in_time, out_time) {
|
||||
(Ok(i), Ok(o)) => i > o,
|
||||
(Ok(_), Err(_)) => true,
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
fn substitute_step_cmd(
|
||||
template: &str,
|
||||
input: &Path,
|
||||
output: &Path,
|
||||
tools: &ToolchainExecs,
|
||||
step_flags: &str,
|
||||
stem: &str,
|
||||
) -> String {
|
||||
template
|
||||
.replace("{in}", &input.to_string_lossy())
|
||||
.replace("{out}", &output.to_string_lossy())
|
||||
.replace("{uic}", &tools.uic)
|
||||
.replace("{moc}", &tools.moc)
|
||||
.replace("{rcc}", &tools.rcc)
|
||||
.replace("{cflags}", step_flags)
|
||||
.replace("{stem}", stem)
|
||||
}
|
||||
|
||||
fn build_step_flags(cflags: &[String], include_dirs: &[String], compiler: &str) -> String {
|
||||
let mut out = Vec::new();
|
||||
let msvc_style = is_msvc_compiler(compiler) || cflags.iter().any(|f| f.starts_with('/'));
|
||||
for flag in cflags {
|
||||
if flag.starts_with("-I") || flag.starts_with("-D") {
|
||||
out.push(flag.clone());
|
||||
}
|
||||
if flag.starts_with("/I") || flag.starts_with("/D") {
|
||||
out.push(flag.clone());
|
||||
}
|
||||
if msvc_style && flag.starts_with("-D") {
|
||||
out.push(format!("/D{}", flag.trim_start_matches("-D")));
|
||||
}
|
||||
}
|
||||
for dir in include_dirs {
|
||||
out.push(format!("-I{dir}"));
|
||||
if msvc_style {
|
||||
out.push(format!("/I{dir}"));
|
||||
}
|
||||
}
|
||||
let mut dedup = Vec::new();
|
||||
for item in out {
|
||||
if !dedup.contains(&item) {
|
||||
dedup.push(item);
|
||||
}
|
||||
}
|
||||
dedup
|
||||
.into_iter()
|
||||
.map(quote_step_arg)
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
}
|
||||
|
||||
fn quote_step_arg(arg: String) -> String {
|
||||
if !arg.chars().any(|c| c.is_whitespace() || c == '"') {
|
||||
return arg;
|
||||
}
|
||||
let escaped = arg.replace('"', "\\\"");
|
||||
format!("\"{escaped}\"")
|
||||
}
|
||||
|
||||
fn is_msvc_compiler(compiler: &str) -> bool {
|
||||
let lower = compiler.to_lowercase();
|
||||
lower.contains("cl.exe")
|
||||
|| lower == "cl"
|
||||
|| lower.contains("clang-cl")
|
||||
|| lower.contains("msvc")
|
||||
}
|
||||
|
||||
fn run_shell_command(cmd: &str) -> Result<std::process::ExitStatus, std::io::Error> {
|
||||
if cfg!(target_os = "windows") {
|
||||
std::process::Command::new("cmd")
|
||||
.arg("/C")
|
||||
.arg(cmd)
|
||||
.status()
|
||||
} else {
|
||||
std::process::Command::new("sh").arg("-c").arg(cmd).status()
|
||||
}
|
||||
}
|
||||
|
||||
fn build_steps_need_run(steps: &[BuildStep]) -> Result<bool, String> {
|
||||
for step in steps {
|
||||
let inputs = expand_glob(&step.input)?;
|
||||
if inputs.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let needs_stem = step.output.contains("{stem}");
|
||||
if inputs.len() > 1 && !needs_stem {
|
||||
return Err(format!(
|
||||
"build.steps '{}' output must include {{stem}} for multiple inputs",
|
||||
step.name
|
||||
));
|
||||
}
|
||||
for input in inputs {
|
||||
let stem = input.file_stem().and_then(|v| v.to_str()).unwrap_or("");
|
||||
let out_path = PathBuf::from(step.output.replace("{stem}", stem));
|
||||
if should_run_step(&input, &out_path) {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
fn compute_build_fingerprint(
|
||||
ctx: &BuildContext,
|
||||
sources: &[String],
|
||||
|
||||
Reference in New Issue
Block a user