use curl::easy::Easy;
use serde::{Deserialize, Serialize};
use spinners::{Spinner, Spinners};
use std::{fs::read_to_string, io::Write, path::Path};
use crate::{truncate_file, utils::shell_utils::home};
#[derive(Debug, Serialize, Deserialize)]
pub struct ShellInformation {
pub name: String,
pub config: String,
pub alias: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ProgramInfo {
pub stable: String,
pub shells: Vec<ShellInformation>,
}
const REPO: &str = "https://raw.githubusercontent.com/garcia-andy/aliasman-rs/main/shells.json";
const CFG: &str = "/.aliasman.json";
fn load_from_git() -> String {
let mut sp = Spinner::new(
Spinners::Dots9,
"Downloading the configuration content".into(),
);
let mut content = String::new();
let mut easy = Easy::new();
easy.url(REPO).expect("Error connecting to github");
{
let mut transfer = easy.transfer();
transfer
.write_function(|data| {
content.push_str(
String::from_utf8(Vec::from(data))
.expect("Error parsing data")
.as_str(),
);
Ok(data.len())
})
.expect("Error setting up the write function");
transfer
.perform()
.expect("Error in the Transfer perform action");
}
sp.stop_with_message("✅ Already download the configuration content".to_string());
content
}
pub fn load_content() -> ProgramInfo {
let config_file = home() + CFG;
let content = if Path::new(config_file.as_str()).exists() {
read_to_string(config_file).expect("Error reading config file")
} else {
update()
};
serde_json::from_str(content.as_str()).expect("Error parsing data")
}
pub fn update() -> String {
let config_file = home() + CFG;
let content = load_from_git();
let mut sp = Spinner::new(Spinners::Dots9, "Writing the configuration content".into());
let mut config_file = truncate_file(config_file.as_str()).expect("Unable to open config file");
config_file
.write_all(content.as_bytes())
.expect("Error to write content");
config_file.flush().expect("Error flushing datas");
sp.stop_with_message("✅ Already writed the configuration content".to_string());
content
}