nextsync-rust/src/commands/config.rs

110 lines
2.8 KiB
Rust

use std::fs::OpenOptions;
use std::io::{self, Write};
use crate::utils::{path, read};
pub fn add_remote(name: &str, url: &str) -> io::Result<()> {
let mut root = path::nextsync();
root.push("config");
// check if there is already a remote with this name
if get_remote(name).is_some()
{
eprintln!("error: remote {} already exists.", name);
std::process::exit(3);
}
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.append(true)
.open(root)?;
writeln!(file, "[remote \"{}\"]", name)?;
writeln!(file, "\turl = {}", url)?;
Ok(())
}
pub fn get_remote(name: &str) -> Option<String> {
let mut root = path::nextsync();
root.push("config");
let target = String::from(format!("[remote \"{}\"]", name));
if let Ok(mut lines) = read::read_lines(root) {
while let Some(line_res) = lines.next() {
if let Ok(line) = line_res {
if line == target {
// get the first line starting with 'url = '
while let Some(line_res) = lines.next() {
if let Ok(line) = line_res {
let mut splitted_res = line.split("=");
if let Some(splitted) = splitted_res.next() {
if splitted == "\turl " {
return Some(splitted_res.next().unwrap().to_owned());
}
}
}
}
}
}
}
}
return None;
}
pub fn add_core(name: &str, value: &str) -> io::Result<()> {
let mut root = path::nextsync();
root.push("config");
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.append(true)
.open(root)?;
writeln!(file, "[core]")?;
writeln!(file, "\t{} = {}", name, value)?;
Ok(())
}
pub fn set(var: &str, val: &str) -> io::Result<()> {
let mut root = path::nextsync();
root.push("config");
// todo check if exist
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.append(true)
.open(root)?;
let mut line = var.to_owned();
line.push_str(" ");
line.push_str(val);
writeln!(file, "{}", line)?;
Ok(())
}
pub fn get(var: &str) -> Option<String> {
let mut root = path::nextsync();
root.push("config");
if let Ok(lines) = read::read_lines(root) {
for line in lines {
if let Ok(l) = line {
if l.starts_with(var.clone()) {
let (_, val) = l.split_once(" ").unwrap();
return Some(val.to_owned());
}
}
}
}
None
}