1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97

use include_dir::{include_dir, Dir};
use std::path::{Path, PathBuf};
use std::env;
use dirs::config_dir;
use std::fs::{create_dir,create_dir_all};

use std::io::prelude::*;
use std::fs::File;

pub fn get_target_directory() -> PathBuf  {
    let target_dir = config_dir().unwrap();

    let name = env!("CARGO_PKG_NAME");

    let version: &str = env!("CARGO_PKG_VERSION");

    target_dir
        // .join("apps")
        .join(name)
        .join(version)
}

/// copies a directory to the OS default config directory eg for linux /home/<user>/.config/<CARGO_PKG_NAME>/<CARGO_PKG_VERSION>
/// if a target directory is specified it is recommended to use the get_target_directory coupled with a digest to uniquify your project configuration.
/// configurations will only be copied if they do not exist in the folder.
/// This allows users to modify the config after it has 
/// been placed without fear of the user changes being 
/// clobbered when a program gets re-run
pub fn copy_configs(source_directory: Dir, target_directory : Option<PathBuf>) {
    // dbg!(&source_directory.files);
    // dbg!(&target_dir);
    let target_dir = if let Some(td) = target_directory {
        td
    }else{
        get_target_directory()
    };

    let _ = create_dir_all(&target_dir);
    
    copy_recursive(source_directory, &target_dir).unwrap();
    
}

/// will attempt to read the configuration file.
pub fn read_file(file: &PathBuf) -> Result<usize, std::io::Error>{

    let mut f = File::open(file)?;
    let mut buffer = Vec::new();

    // read the whole file
    f.read_to_end(&mut buffer)

} 



pub fn copy_recursive(from: Dir, to: &PathBuf) -> Result<(), std::io::Error> {
    let files = from.files();

    dbg!(files);
    let dirs = from.dirs();

    for file in files {
        let dest_file = to.join(file.path);
        if dest_file.exists() == false {
            let mut buffer = File::create(&dest_file).unwrap();
            buffer.write(file.contents).unwrap();
            println!("Copied File to {}", &dest_file.to_str().unwrap());
        }else{
            println!("File already exists: {}", &dest_file.to_str().unwrap());
        }
    }

    for dir in dirs {
        dbg!(&dir);
        let new_target = to.join(dir.path);
        dbg!(&new_target);
        {
            let _ = create_dir(&new_target);
        }
        println!("Created Directory {}",new_target.to_str().unwrap());
        let _ = copy_recursive(*dir, to);
        
    }


    Ok(())
}

#[cfg(test)]

#[test]
fn test_configure(){
    let PROJECT_DIR: Dir = include_dir!("config");
    copy_configs(PROJECT_DIR, None);
}