diff --git a/src/clone.rs b/src/clone.rs index fe5f4bc053f7b144bc8d25338a2b5eff70fb1575..5a564a6ebcdfe7600df0db95be2c1e0bcabb2150 100644 --- a/src/clone.rs +++ b/src/clone.rs @@ -1,3 +1,96 @@ // SPDX-FileCopyrightText: 2023 Nicolas Fontrodona // // SPDX-License-Identifier: AGPL-3.0-or-later + +use std::{ + path::PathBuf, + process::{exit, Command}, +}; + +use colored::Colorize; + +use crate::{init, pull, push, remote}; + +/// Function used to get borg repository folder only if +/// the project is inside a git repository and a results folder exits +/// # Return +/// Absolute path to borg repository +pub fn get_borg_absolute_folder() -> PathBuf { + let output = Command::new("git") + .arg("rev-parse") + .arg("--show-cdup") + .output() + .unwrap(); + match output.status.code().unwrap() { + 128 => { + eprintln!("Not a git repository !"); + exit(128); + } + 127 => { + eprintln!("Git not found !"); + exit(127); + } + 0 => (), + num => { + eprintln!("{}", String::from_utf8(output.stderr).unwrap()); + exit(num) + } + } + let mut string_path = String::from_utf8(output.stdout).unwrap(); + if string_path.ends_with('\n') { + string_path.pop(); + } + if string_path.is_empty() { + string_path.push_str("./"); + } + let mut p = PathBuf::from(&string_path).canonicalize().unwrap(); + let mut results = p.clone(); + p.push(".borg"); + results.push("results"); + if !results.is_dir() { + eprintln!("{} not found !", results.to_str().unwrap()); + exit(1); + } + p +} + +/// Check if the input remote dir +fn check_remote_dir(url: &PathBuf, adress: &str) { + let archives = pull::get_archive_list(&url, &adress); + if archives.len() == 0 { + eprintln!( + "{}: No archives found in {}!", + "error".red(), + url.to_str().unwrap().yellow() + ); + exit(1); + } +} + +/// Create a push the tar achive on the selected remote path +/// # Arguments +/// - `path`: The path used to clone .borg repository +/// - `hooks`: a bolean indicating whether or not to use hooks +/// - `compression`: The compression that will be used when creating an archive +/// - `mode`: The mode used for checkout +pub fn clone(path: &str, hooks: bool, compression: &str, mode: &str) -> () { + let (adress, url) = push::split_path(path); + let borg_folder = get_borg_absolute_folder(); + if borg_folder.is_dir() { + eprintln!( + "{}: {} already exits.", + "error".red(), + &borg_folder.display() + ); + exit(1); + } + check_remote_dir(&url, &adress); + let full_url = if adress != "file" { + format!("{}:{}", &adress, &url.display()) + } else { + url.canonicalize().unwrap().to_str().unwrap().to_owned() + }; + init::init_and_hook(hooks, compression, mode); + remote::update_config("origin", &full_url, false); + pull::pull_all_archives("origin"); +}