cnf-lib 0.6.0

Distribution-agnostic 'command not found'-handler
Documentation
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: (C) 2023 Andreas Hartmann <hartan@7x.de>
// This file is part of cnf-lib, available at <https://gitlab.com/hartang/rust/cnf>

//! # Distrobox Environment Handler
//!
//! [Distrobox][distrobox] is a collection of shell-scripts that serves the same purpose as
//! [toolbx][toolbx]: To provide pet-containers for e.g. development purposes
//!
//! [distrobox]: https://github.com/89luca89/distrobox
//! [toolbx]: https://containertoolbx.org/
use super::prelude::*;

use std::{io::IsTerminal, path::Path};

const DISTROBOX_ENV: &str = "/run/.containersetupdone";
const CONTAINER_ENV: &str = "/run/.containerenv";

/// Environment for distrobox containers.
#[derive(PartialEq, Eq, Debug, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Distrobox {
    name: String,
}

impl fmt::Display for Distrobox {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "distrobox '{}'", self.name)
    }
}

impl Distrobox {
    /// Start a Distrobox container with a given name.
    ///
    /// Checks if the Distrobox container exists and starts it, if necessary. If `None` is given as
    /// name, will fall back to the default Distrobox name and start that instead. Returns an error
    /// if unsuccessful.
    pub fn new(name: Option<String>) -> Result<Self, NewDistroboxError> {
        let name = match name {
            Some(name) if !name.is_empty() => name,
            _ => "my-distrobox".to_string(),
        };

        // Do an optimistic start:
        // - If the container exists and isn't started, it will be started
        // - If the container exists and is started, nothing happens
        // - If the container doesn't exist, we get an error and report that
        let ret = Self { name: name.clone() };
        ret.start()
            .map_err(|e| NewDistroboxError::CannotStart { source: e, name })?;
        Ok(ret)
    }

    /// Starts a given Distrobox container.
    ///
    /// This function is automatically called by `new()` above and should only ever be called when
    /// creating a `Distrobox` object without using the constructor. This is currently the case
    /// when executing aliases in `cnf`, as the `Distrobox` instance is deserialized from the
    /// config in that case.
    pub fn start(&self) -> Result<(), StartDistroboxError> {
        let output = std::process::Command::new("podman")
            .args(["start", &self.name])
            .output()
            .map_err(|e| match e.kind() {
                std::io::ErrorKind::NotFound => StartDistroboxError::NeedPodman,
                _ => StartDistroboxError::IoError(e),
            })?;
        if output.status.success() {
            // All good
            Ok(())
        } else {
            let matcher = OutputMatcher::new(&output);
            if matcher.starts_with("Error: no container with name or ID")
                && matcher.contains("found: no such container")
            {
                Err(StartDistroboxError::NonExistent(self.name.clone()))
            } else {
                Err(StartDistroboxError::Podman(output))
            }
        }
    }

    /// Get the Toolbx container currently executing CNF.
    ///
    /// Will return an error if the current execution environment isn't Toolbx.
    pub fn current() -> Result<Self, CurrentDistroboxError> {
        if !detect() {
            return Err(CurrentDistroboxError::NotAToolbx);
        }

        let content = std::fs::read_to_string(CONTAINER_ENV).map_err(|e| {
            CurrentDistroboxError::Environment {
                env_file: CONTAINER_ENV.to_string(),
                source: e,
            }
        })?;
        let name = content
            .lines()
            .find(|line| line.contains("name=\""))
            .ok_or_else(|| CurrentDistroboxError::Name(CONTAINER_ENV.to_string()))?
            .trim_start_matches("name=\"")
            .trim_end_matches('"');

        Ok(Self {
            name: name.to_string(),
        })
    }
}

#[async_trait]
impl environment::IsEnvironment for Distrobox {
    type Err = Error;

    async fn exists(&self) -> bool {
        if detect() {
            true
        } else if let Environment::Host(host) = environment::current() {
            // The result in this case is indeed `Infallible`, but switching an `if-let` for an
            // `unwrap` is outright stupid in my opinion.
            #[allow(irrefutable_let_patterns)]
            if let Ok(mut cmd) = host
                .execute(crate::environment::cmd!("distrobox", "--version"))
                .await
            {
                cmd.stdout(std::process::Stdio::null())
                    .stderr(std::process::Stdio::null())
                    .status()
                    .await
                    .map(|status| status.success())
                    .unwrap_or(false)
            } else {
                false
            }
        } else {
            false
        }
    }

    async fn execute(&self, command: CommandLine) -> Result<Command, Self::Err> {
        debug!("preparing execution: {}", command);
        let mut cmd: Command;

        match environment::current() {
            Environment::Distrobox(t) => {
                if self == &t {
                    // This is the Toolbx container we are currently running in
                    // We expect Toolbx containers to *always* run a unix OS, or at least something
                    // that has `sudo`.
                    if command.get_privileged() {
                        cmd = Command::new("sudo");
                        if !command.get_interactive() {
                            cmd.arg("-n");
                        }

                        cmd.arg(command.command());
                    } else {
                        cmd = Command::new(command.command());
                    }

                    cmd.args(command.args());
                } else {
                    return Err(Error::Unimplemented(
                        "running in a distrobox from another distrobox".to_string(),
                    ));
                }
            }
            Environment::Toolbx(_) => {
                return Err(Error::Unimplemented(
                    "running in a distrobox from a toolbx".to_string(),
                ));
            }
            Environment::Host(_) => {
                cmd = Command::new("distrobox");
                cmd.args(["enter", "--name", &self.name]);

                // Only attach to the TTY if we really have a TTY, too
                if std::io::stdout().is_terminal() && std::io::stdin().is_terminal() {
                    cmd.arg("-T");
                }
                cmd.arg("--");

                // This is the real command we're looking for (with arguments)
                if command.get_privileged() {
                    cmd.args(["sudo", "-S", "-E"]);
                }

                cmd.arg(command.command()).args(command.args());
            }
            #[cfg(test)]
            Environment::Mock(_) => unimplemented!(),
        }

        trace!("full command: {:?}", cmd);
        Ok(cmd)
    }
}

/// Detect if the current execution environment is a Toolbx container.
///
/// Checks for the presence of the `.toolboxenv` files.
pub fn detect() -> bool {
    Path::new(DISTROBOX_ENV).exists()
}

/// Errors related to starting concrete Distrobox instances.
#[derive(Debug, ThisError, Display)]
pub enum StartDistroboxError {
    /// working with distrobox containers requires the 'podman' executable
    NeedPodman,

    /// podman exited with non-zero code: {0:#?}
    Podman(std::process::Output),

    /// no distrobox with name {0} exists
    NonExistent(String),

    /// unknown I/O error occured
    IoError(#[from] std::io::Error),
}

/// Errors related to starting a named distrobox instance.
#[derive(Debug, ThisError, Display)]
pub enum NewDistroboxError {
    /// failed to determine default distrobox name
    UnknownDefault(#[from] DefaultToolbxError),

    /// failed to start distrobox container with name '{name}': {source}
    CannotStart {
        /// Underlying error source.
        source: StartDistroboxError,
        /// Name of the distrobox that failed to start.
        name: String,
    },
}

/// Errors related to distrobox as environment that launched `cnf`.
#[derive(Debug, ThisError, Display)]
pub enum CurrentDistroboxError {
    /// cannot read distrobox info from environment file '{env_file}': {source}
    Environment {
        /// environment file that couldn't be read.
        env_file: String,
        /// Error from trying to read the environment file.
        source: std::io::Error,
    },

    /// program currently isn't run from a toolbx
    NotAToolbx,

    /// failed to read distrobox name from environment file '{0}'
    Name(String),
}

/// Errors related to the configured default distrobox container.
#[derive(Debug, ThisError, Display)]
pub enum DefaultToolbxError {
    /// failed to read OS information from '{file}': {source}
    UnknownOs {
        /// File that couldn't be read.
        file: String,
        /// Error from trying to read the file.
        source: std::io::Error,
    },

    /// cannot determine OS ID from os-release info
    Id,

    /// cannot determine OS VERSION_ID from os-release info
    VersionId,
}

/// Error type for environment impl.
#[derive(Debug, ThisError, Display)]
pub enum Error {
    /// cannot determine current working directory
    UnknownCwd(#[from] std::io::Error),

    /// not implemented: {0}
    Unimplemented(String),
}