|
| 1 | +use std::collections::hash_map::DefaultHasher; |
| 2 | +use std::fs::{self, create_dir, rename}; |
| 3 | +use std::hash::{Hash, Hasher}; |
| 4 | +use std::path::{Path, PathBuf}; |
| 5 | +use std::{env, panic}; |
| 6 | + |
| 7 | +use fs_extra::copy_items; |
| 8 | +use fs_extra::dir::CopyOptions; |
| 9 | + |
| 10 | +use crate::config_const::{CONFIG_FOLDER, CONFIG_LOCAL}; |
| 11 | + |
| 12 | +pub mod config_const { |
| 13 | + pub const CONFIG_FOLDER: &str = "config"; |
| 14 | + pub const CONFIG_LOCAL: &str = "local"; |
| 15 | +} |
| 16 | + |
| 17 | +fn main() { |
| 18 | + let config_folder = Path::new(CONFIG_FOLDER); |
| 19 | + let target_folder = env::var_os("OUT_DIR").map(PathBuf::from).unwrap().join("../../.."); |
| 20 | + let local_source = config_folder.join(CONFIG_LOCAL).with_extension("toml"); |
| 21 | + let local_backup_folder = config_folder.with_extension("backup"); |
| 22 | + let local_backup = local_backup_folder.join(CONFIG_LOCAL); |
| 23 | + |
| 24 | + let t = target_folder.canonicalize(); |
| 25 | + |
| 26 | + eprintln!("Target : {target_folder:?} : {t:?}"); |
| 27 | + |
| 28 | + // local setting |
| 29 | + if local_source.exists() { |
| 30 | + if local_backup_folder.exists() { |
| 31 | + if !local_backup_folder.is_dir() { |
| 32 | + panic!("Exists and is not a Folder!: {local_backup_folder:?}") |
| 33 | + } |
| 34 | + } else { |
| 35 | + create_dir(local_backup_folder).unwrap(); |
| 36 | + } |
| 37 | + |
| 38 | + let mut hasher = DefaultHasher::new(); |
| 39 | + |
| 40 | + fs::read_to_string(&local_source).unwrap().hash(&mut hasher); |
| 41 | + |
| 42 | + rename( |
| 43 | + local_source, |
| 44 | + local_backup.with_extension(format!("{}-{}", "toml", hasher.finish())), |
| 45 | + ) |
| 46 | + .unwrap(); |
| 47 | + } |
| 48 | + |
| 49 | + // Re-runs script if any files in config are changed |
| 50 | + println!("cargo:rerun-if-changed=config/*"); |
| 51 | + copy_to_target(config_folder, &target_folder).expect("Could not copy"); |
| 52 | +} |
| 53 | + |
| 54 | +pub fn copy_to_target(path: &Path, target: &Path) -> Result<u64, fs_extra::error::Error> { |
| 55 | + let mut options = CopyOptions::new(); |
| 56 | + let mut paths = Vec::new(); |
| 57 | + |
| 58 | + // Overwrite existing files with same name |
| 59 | + options.overwrite = true; |
| 60 | + |
| 61 | + paths.push(path); |
| 62 | + match copy_items(&paths, target, &options) { |
| 63 | + Ok(r) => Ok(r), |
| 64 | + Err(e) => { |
| 65 | + let f = path.canonicalize(); |
| 66 | + let t = target.canonicalize(); |
| 67 | + eprintln!("Tried to copy from: {f:?}"); |
| 68 | + eprintln!("Tried to copy to : {t:?}"); |
| 69 | + Err(e) |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments