init_rs/
lib.rs

1//! # init-rs
2//!
3//! Use the world's best Cargo to install software, bypassing GitHub.
4
5use std::fs;
6#[cfg(target_family = "unix")]
7use std::os::unix::fs::PermissionsExt;
8use std::path::{Path, PathBuf};
9
10/// Copy the binary file to the specified directory.
11///
12/// # Parameters
13///
14/// * `binary_name` - The name of the binary file to copy.
15/// * `source_dir` - The path to the source file directory.
16/// * `target_dir` - The path to the target directory.
17///
18/// # Return
19///
20/// If successful, return the target path `PathBuf`。
21/// On failure, returns a string describing the error.
22///
23/// # Example
24///
25/// ```
26/// # {
27/// let source_dir = std::path::Path::new(".");
28/// let target_dir = std::path::Path::new("/usr/local/bin");
29/// let result = init_rs::copy_binary("example_binary", source_dir, target_dir);
30/// assert!(result.is_ok());
31/// # }
32/// ```
33///
34pub fn copy_binary(
35    binary_name: &str,
36    source_dir: &Path,
37    target_dir: &Path,
38) -> Result<PathBuf, String> {
39    let source_path = source_dir.join(binary_name);
40    let target_path = target_dir.join(binary_name);
41
42    fs::copy(&source_path, &target_path)
43        .map_err(|e| format!("Failed to copy binary file '{}': {}", binary_name, e))?;
44
45    // chmod +x
46    #[cfg(target_family = "unix")]
47    {
48        let permissions = fs::Permissions::from_mode(0o755);
49        fs::set_permissions(&target_path, permissions)
50            .map_err(|e| format!("Failed to set permissions for '{}': {}", binary_name, e))?;
51    }
52
53    Ok(target_path)
54}
55
56#[cfg(test)]
57mod tests {
58    use super::*;
59    use std::fs::{self, File};
60    use std::io::Write;
61    use tempfile::TempDir;
62
63    /// Test the ability to copy binary files on a Linux system.
64    #[test]
65    fn test_copy_binary() {
66        let temp_dir = TempDir::new().unwrap();
67        let source_dir = temp_dir.path();
68        let target_temp_dir = TempDir::new().unwrap();
69        let target_dir = target_temp_dir.path();
70
71        let binary_name = "test_binary";
72        let source_file_path = source_dir.join(binary_name);
73
74        // Create a temporary binary file to simulate copying
75        let mut file = File::create(&source_file_path).unwrap();
76        writeln!(file, "binary content").unwrap();
77
78        let copy_result = copy_binary(binary_name, source_dir, &target_dir);
79
80        assert!(copy_result.is_ok());
81        assert!(target_dir.join(binary_name).exists());
82    }
83}