robomotion 0.1.3

Official Rust SDK for building Robomotion RPA packages
Documentation
//! Utility functions.

use std::path::PathBuf;

/// Check if a directory exists.
pub fn dir_exists(dir: &str) -> bool {
    std::fs::metadata(dir).map(|m| m.is_dir()).unwrap_or(false)
}

/// Check if a file exists.
pub fn file_exists(dir: &str, file_name: &str) -> bool {
    let path = PathBuf::from(dir).join(file_name);
    std::fs::metadata(&path)
        .map(|m| m.is_file())
        .unwrap_or(false)
}

/// Get the user's home directory.
pub fn user_home_dir() -> PathBuf {
    dirs::home_dir().unwrap_or_else(|| PathBuf::from("."))
}

/// Get the temp directory for Robomotion.
pub fn temp_dir() -> PathBuf {
    let home = user_home_dir();

    #[cfg(target_os = "windows")]
    {
        home.join("AppData").join("Local").join("Temp").join("Robomotion")
    }

    #[cfg(not(target_os = "windows"))]
    {
        PathBuf::from("/tmp/robomotion")
    }
}

/// Get the temp path for robot data.
pub fn get_temp_path() -> PathBuf {
    let home = user_home_dir();

    #[cfg(target_os = "windows")]
    {
        home.join("AppData").join("Local").join("Robomotion").join("temp")
    }

    #[cfg(not(target_os = "windows"))]
    {
        home.join(".config").join("robomotion").join("temp")
    }
}

/// Check if a version is less than another.
pub fn is_version_less_than(ver: &str, other: &str) -> bool {
    if ver.is_empty() || ver == "0.0" || ver == "0.0.0" {
        return true;
    }

    let parse_version = |s: &str| -> Vec<u32> {
        s.split('.')
            .filter_map(|p| p.parse().ok())
            .collect()
    };

    let v1 = parse_version(ver);
    let v2 = parse_version(other);

    for i in 0..std::cmp::max(v1.len(), v2.len()) {
        let a = v1.get(i).copied().unwrap_or(0);
        let b = v2.get(i).copied().unwrap_or(0);
        if a < b {
            return true;
        }
        if a > b {
            return false;
        }
    }

    false
}

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

    #[test]
    fn test_version_comparison() {
        assert!(is_version_less_than("1.0.0", "2.0.0"));
        assert!(is_version_less_than("1.0.0", "1.1.0"));
        assert!(is_version_less_than("1.0.0", "1.0.1"));
        assert!(!is_version_less_than("2.0.0", "1.0.0"));
        assert!(!is_version_less_than("1.0.0", "1.0.0"));
        assert!(is_version_less_than("", "1.0.0"));
        assert!(is_version_less_than("0.0", "1.0.0"));
    }
}