Files
git-repo-manager/src/config.rs
Hannes Körber f0c8805cf3 Refactor
This refactors a huge chunk of the code base to make it more maintainable.

Main points:

* Proper separation between bin and lib. Bin handles argument parsing &
  validation and (most of) the output. Lib provides interfaces for all
  opreations.

* Before, libgit2 internals were literred throughout the codebase,
  mainly the `Repository` struct and `git2::Error` in Results. They
  library is now properly wrapped in `repo.rs`, which exposes only the
  required functionality. It also standardizes the Error messages
  (they're just Strings for now) and handles stuff like the copious
  usage of Options to wrap maybe-invalid-utf-8 values. The program will
  still panic on non-utf-8 Strings e.g. in git remotes, but I guess this
  is acceptable. If you actually manage to hit this case, I promise I'll
  fix it :D

* Many unwraps() are now gone and properly handled.

* The table printing functionality is now confined to `table.rs`,
  instead of passing tables as parameters through the whole program.
2021-12-01 20:12:24 +01:00

75 lines
1.6 KiB
Rust

use serde::{Deserialize, Serialize};
use super::repo::RepoConfig;
#[derive(Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
pub trees: Trees,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Trees(Vec<Tree>);
impl Trees {
pub fn to_config(self) -> Config {
Config { trees: self }
}
pub fn from_vec(vec: Vec<Tree>) -> Self {
Trees(vec)
}
pub fn as_vec(self) -> Vec<Tree> {
self.0
}
pub fn as_vec_ref(&self) -> &Vec<Tree> {
self.0.as_ref()
}
}
impl Config {
pub fn as_toml(&self) -> Result<String, String> {
match toml::to_string(self) {
Ok(toml) => Ok(toml),
Err(error) => Err(error.to_string()),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Tree {
pub root: String,
pub repos: Option<Vec<RepoConfig>>,
}
pub fn read_config(path: &str) -> Result<Config, String> {
let content = match std::fs::read_to_string(&path) {
Ok(s) => s,
Err(e) => {
return Err(format!(
"Error reading configuration file \"{}\": {}",
path,
match e.kind() {
std::io::ErrorKind::NotFound => String::from("not found"),
_ => e.to_string(),
}
));
}
};
let config: Config = match toml::from_str(&content) {
Ok(c) => c,
Err(e) => {
return Err(format!(
"Error parsing configuration file \"{}\": {}",
path, e
))
}
};
Ok(config)
}