cargo-telar 0.2.3

Cargo subcommand for Telar apps: dev server with hot reload, and packaging into native installers.
//! Packaging a Debian `.deb`.

use std::path::Path;
use std::process::Command;

use super::super::config::{Maintainer, MaintainerSource, TelarSection, resolve_package};
use super::{
    create_dir_or_exit, desktop_entry_file, dist_dir, doc_dir, run_bundler_tool, run_release_build,
    stage_binary, stage_icon_notice, write_or_exit,
};

// Maps Rust's target arch name to the Debian architecture label; unknown arches pass through unchanged.
fn deb_architecture(arch: &str) -> &str {
    match arch {
        "x86_64" => "amd64",
        "aarch64" => "arm64",
        other => other,
    }
}

fn deb_control_field(name: &str, value: &str) -> String {
    let mut lines = value.trim().lines();
    let mut field = format!("{name}: {}\n", lines.next().unwrap_or_default().trim_end());
    for line in lines {
        let line = line.trim_end();
        if line.is_empty() {
            field.push_str(" .\n");
        } else {
            field.push_str(&format!(" {line}\n"));
        }
    }
    field
}

fn validate_package_name(name: &str) -> Result<(), String> {
    let mut chars = name.chars();
    let valid_start = chars
        .next()
        .is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit());
    let valid_rest =
        chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || "+-.".contains(c));
    if name.len() >= 2 && valid_start && valid_rest {
        Ok(())
    } else {
        Err(format!(
            "`{name}` is not a valid Debian package name: use at least two characters from lowercase letters, digits, `+`, `-` and `.`, starting with a letter or digit. Rename the package in its Cargo.toml."
        ))
    }
}

fn validate_description(description: &str) -> Result<(), String> {
    let synopsis = description.trim().lines().next().unwrap_or_default();
    if synopsis.trim().is_empty() {
        return Err("the package `description` is empty; Debian needs a synopsis line.".into());
    }
    if unexpected_control_char(description, &['\n', '\r', '\t']).is_some() {
        return Err("the package `description` contains control characters, which a Debian control file cannot carry.".into());
    }
    Ok(())
}

fn unexpected_control_char(text: &str, allowed: &[char]) -> Option<char> {
    text.chars()
        .find(|c| c.is_control() && !allowed.contains(c))
}

fn validate_maintainer(maintainer: &Maintainer) -> Result<(), String> {
    let source = match maintainer.source {
        MaintainerSource::CargoAuthors => "`authors` in Cargo.toml",
        MaintainerSource::DebEnv => "`DEBFULLNAME`/`DEBEMAIL`",
    };
    match unexpected_control_char(&maintainer.value, &[]) {
        Some(c) => Err(format!(
            "the maintainer from {source} contains the control character {c:?}, which a Debian control file cannot carry."
        )),
        None => Ok(()),
    }
}

fn deb_control_file(
    name: &str,
    version: &str,
    arch: &str,
    maintainer: &str,
    description: &str,
) -> String {
    format!(
        "Package: {name}\nVersion: {version}\nArchitecture: {arch}\nMaintainer: {maintainer}\n{}",
        deb_control_field("Description", description)
    )
}

/// The tree `dpkg-deb` packs: the control file, the binary, its desktop entry, and the icon licence notice in the package's documentation directory.
fn stage_deb(
    staging: &Path,
    bin_path: &Path,
    package_dir: &Path,
    package_name: &str,
    control: &str,
) {
    // Clear any previous staging so stale files never leak into the package.
    let _ = std::fs::remove_dir_all(staging);

    let debian_dir = staging.join("DEBIAN");
    let bin_dir = staging.join("usr").join("bin");
    let apps_dir = staging.join("usr").join("share").join("applications");
    create_dir_or_exit(&debian_dir);
    create_dir_or_exit(&bin_dir);
    create_dir_or_exit(&apps_dir);

    write_or_exit(&debian_dir.join("control"), control);
    stage_binary(bin_path, &bin_dir.join(package_name));
    write_or_exit(
        &apps_dir.join(format!("{package_name}.desktop")),
        desktop_entry_file(package_name, false),
    );
    stage_icon_notice(package_dir, &doc_dir(staging, package_name));
}

pub(crate) fn build_deb(cargo_args: Vec<String>, config: TelarSection) -> ! {
    // Resolved before the build: failing on a missing manifest field after a full release compile wastes the one thing the author cannot get back.
    let manifest = resolve_package(&cargo_args).unwrap_or_else(|error| error.exit());
    let Some(maintainer) = manifest.maintainer() else {
        eprintln!(
            "[cargo-telar] --format deb needs a maintainer. Add `authors = [\"Name <email>\"]` to the package's Cargo.toml."
        );
        std::process::exit(1);
    };
    let manifest_description = manifest.description();
    let checked = validate_package_name(&manifest.name)
        .and(
            manifest_description
                .as_deref()
                .map_or(Ok(()), validate_description),
        )
        .and(validate_maintainer(&maintainer));
    if let Err(message) = checked {
        eprintln!("[cargo-telar] --format deb: {message}");
        std::process::exit(1);
    }
    let (bin_path, resolved) = run_release_build(cargo_args, config);
    let package_name = resolved.name.clone();
    let version = resolved.version.clone();
    let description = resolved
        .description()
        .unwrap_or_else(|| format!("{package_name} (built with rsx)"));
    let arch = deb_architecture(std::env::consts::ARCH);

    let dist_dir = dist_dir(&resolved.workspace_root);
    let staging = dist_dir.join("deb-staging").join(&package_name);
    stage_deb(
        &staging,
        &bin_path,
        &resolved.package_dir,
        &package_name,
        &deb_control_file(
            &package_name,
            &version,
            arch,
            &maintainer.value,
            &description,
        ),
    );

    let deb_path = dist_dir.join(format!("{package_name}_{version}_{arch}.deb"));
    let mut cmd = Command::new("dpkg-deb");
    cmd.arg("--build")
        .arg("--root-owner-group")
        .arg(&staging)
        .arg(&deb_path);
    run_bundler_tool(
        &mut cmd,
        "deb",
        &deb_path,
        Some(
            "[cargo-telar] `dpkg-deb` is required for --format deb but was not found on PATH. On NixOS: `nix shell nixpkgs#dpkg`.",
        ),
    )
}

#[cfg(test)]
#[path = "deb.test.rs"]
mod tests;