mirror of
https://github.com/Dasemu/Grove.git
synced 2026-11-27 07:46:13 +00:00
chore: rename project to grove and add MIT license
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
126acb4b57
commit
c935d779e1
29 files changed
+99
-76
No files matched your search
@@ -0,0 +1,280 @@
|
||||
//! `config.toml` model, loading and validation (section 6 of the plan).
|
||||
|
||||
use serde::Deserialize;
|
||||
use std::collections::BTreeMap;
|
||||
use std::fmt;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Deserialize)]
|
||||
pub struct Config {
|
||||
pub machine: Machine,
|
||||
pub root: Root,
|
||||
#[serde(default)]
|
||||
pub providers: BTreeMap<String, Provider>,
|
||||
#[serde(default)]
|
||||
pub groups: Vec<Group>,
|
||||
#[serde(default)]
|
||||
pub sync: Sync,
|
||||
pub config_repo: Option<ConfigRepo>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Deserialize)]
|
||||
pub struct Machine {
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Deserialize)]
|
||||
pub struct Root {
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ProviderKind {
|
||||
Gitea,
|
||||
Forgejo,
|
||||
Github,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Deserialize)]
|
||||
pub struct Provider {
|
||||
pub kind: ProviderKind,
|
||||
pub url: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum Layout {
|
||||
#[default]
|
||||
BareWorktrees,
|
||||
Plain,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Deserialize)]
|
||||
pub struct Group {
|
||||
pub name: String,
|
||||
pub primary: String,
|
||||
#[serde(default)]
|
||||
pub mirror_to: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub layout: Layout,
|
||||
#[serde(default = "yes")]
|
||||
pub auto_materialize: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Deserialize)]
|
||||
pub struct Sync {
|
||||
#[serde(default = "default_debounce")]
|
||||
pub snapshot_debounce_ms: u64,
|
||||
#[serde(default = "default_fetch")]
|
||||
pub fetch_interval_s: u64,
|
||||
#[serde(default)]
|
||||
pub ignore_extra: Vec<String>,
|
||||
}
|
||||
|
||||
impl Default for Sync {
|
||||
fn default() -> Self {
|
||||
Sync {
|
||||
snapshot_debounce_ms: default_debounce(),
|
||||
fetch_interval_s: default_fetch(),
|
||||
ignore_extra: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Deserialize)]
|
||||
pub struct ConfigRepo {
|
||||
pub provider: String,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
fn yes() -> bool {
|
||||
true
|
||||
}
|
||||
fn default_debounce() -> u64 {
|
||||
2000
|
||||
}
|
||||
fn default_fetch() -> u64 {
|
||||
60
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ConfigError {
|
||||
Io(PathBuf, std::io::Error),
|
||||
Parse(String),
|
||||
Invalid(String),
|
||||
}
|
||||
|
||||
impl fmt::Display for ConfigError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
ConfigError::Io(p, e) => write!(f, "cannot read {}: {e}", p.display()),
|
||||
ConfigError::Parse(m) => write!(f, "invalid config syntax: {m}"),
|
||||
ConfigError::Invalid(m) => write!(f, "invalid config: {m}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ConfigError {}
|
||||
|
||||
impl Config {
|
||||
pub fn parse(text: &str) -> Result<Config, ConfigError> {
|
||||
let cfg: Config = toml::from_str(text).map_err(|e| ConfigError::Parse(e.to_string()))?;
|
||||
cfg.validate()?;
|
||||
Ok(cfg)
|
||||
}
|
||||
|
||||
pub fn load(path: &Path) -> Result<Config, ConfigError> {
|
||||
let text =
|
||||
std::fs::read_to_string(path).map_err(|e| ConfigError::Io(path.to_path_buf(), e))?;
|
||||
Config::parse(&text)
|
||||
}
|
||||
|
||||
/// Default location: `$XDG_CONFIG_HOME/grove/config.toml` or `~/.config/...`.
|
||||
pub fn default_path() -> Option<PathBuf> {
|
||||
let base = std::env::var_os("XDG_CONFIG_HOME")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))?;
|
||||
Some(base.join("grove/config.toml"))
|
||||
}
|
||||
|
||||
/// Local state directory: `$XDG_STATE_HOME/grove` or `~/.local/state/grove`.
|
||||
pub fn state_dir() -> Option<PathBuf> {
|
||||
let base = std::env::var_os("XDG_STATE_HOME")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local/state")))?;
|
||||
Some(base.join("grove"))
|
||||
}
|
||||
|
||||
/// `root.path` with a leading `~` expanded.
|
||||
pub fn root_path(&self) -> PathBuf {
|
||||
expand_home(&self.root.path)
|
||||
}
|
||||
|
||||
fn validate(&self) -> Result<(), ConfigError> {
|
||||
let bad = |m: String| Err(ConfigError::Invalid(m));
|
||||
// The machine name is embedded in ref names: keep it ref-safe.
|
||||
let n = &self.machine.name;
|
||||
if n.is_empty()
|
||||
|| !n
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
|
||||
{
|
||||
return bad(format!(
|
||||
"machine.name {n:?} must be non-empty and use only letters, digits, '-' or '_'"
|
||||
));
|
||||
}
|
||||
for g in &self.groups {
|
||||
if !self.providers.contains_key(&g.primary) {
|
||||
return bad(format!(
|
||||
"group {:?}: unknown primary provider {:?}",
|
||||
g.name, g.primary
|
||||
));
|
||||
}
|
||||
if let Some(m) = g
|
||||
.mirror_to
|
||||
.iter()
|
||||
.find(|m| !self.providers.contains_key(*m))
|
||||
{
|
||||
return bad(format!("group {:?}: unknown mirror provider {m:?}", g.name));
|
||||
}
|
||||
if g.mirror_to.contains(&g.primary) {
|
||||
return bad(format!(
|
||||
"group {:?}: primary cannot also be a mirror target",
|
||||
g.name
|
||||
));
|
||||
}
|
||||
}
|
||||
if let Some(c) = &self.config_repo
|
||||
&& !self.providers.contains_key(&c.provider)
|
||||
{
|
||||
return bad(format!("config_repo: unknown provider {:?}", c.provider));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn expand_home(p: &str) -> PathBuf {
|
||||
match (p.strip_prefix("~/"), std::env::var_os("HOME")) {
|
||||
(Some(rest), Some(home)) => PathBuf::from(home).join(rest),
|
||||
_ if p == "~" => std::env::var_os("HOME").map_or_else(|| PathBuf::from(p), PathBuf::from),
|
||||
_ => PathBuf::from(p),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const FULL: &str = r#"
|
||||
[machine]
|
||||
name = "desktop"
|
||||
[root]
|
||||
path = "~/Hacking"
|
||||
[providers.gitea-main]
|
||||
kind = "gitea"
|
||||
url = "https://git.example.com"
|
||||
[providers.github]
|
||||
kind = "github"
|
||||
[[groups]]
|
||||
name = "work"
|
||||
primary = "gitea-main"
|
||||
mirror_to = ["github"]
|
||||
[sync]
|
||||
fetch_interval_s = 30
|
||||
[config_repo]
|
||||
provider = "gitea-main"
|
||||
name = "grove-config"
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
fn parses_full_config_with_defaults() {
|
||||
let c = Config::parse(FULL).unwrap();
|
||||
assert_eq!(c.machine.name, "desktop");
|
||||
assert_eq!(c.groups[0].layout, Layout::BareWorktrees);
|
||||
assert!(c.groups[0].auto_materialize);
|
||||
assert_eq!(c.sync.fetch_interval_s, 30);
|
||||
assert_eq!(c.sync.snapshot_debounce_ms, 2000);
|
||||
assert_eq!(c.providers["github"].kind, ProviderKind::Github);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn minimal_config_is_valid() {
|
||||
let c = Config::parse("[machine]\nname=\"a\"\n[root]\npath=\"/x\"\n").unwrap();
|
||||
assert!(c.groups.is_empty());
|
||||
assert_eq!(c.root_path(), PathBuf::from("/x"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_unsafe_machine_name() {
|
||||
for n in ["", "a/b", "a b", "a..b"] {
|
||||
let t = format!("[machine]\nname=\"{n}\"\n[root]\npath=\"/x\"\n");
|
||||
assert!(
|
||||
matches!(Config::parse(&t), Err(ConfigError::Invalid(_))),
|
||||
"{n:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_unknown_providers_and_self_mirror() {
|
||||
let base = "[machine]\nname=\"a\"\n[root]\npath=\"/x\"\n[providers.p]\nkind=\"gitea\"\n";
|
||||
let unknown = format!("{base}[[groups]]\nname=\"g\"\nprimary=\"nope\"\n");
|
||||
assert!(matches!(
|
||||
Config::parse(&unknown),
|
||||
Err(ConfigError::Invalid(_))
|
||||
));
|
||||
let selfm = format!("{base}[[groups]]\nname=\"g\"\nprimary=\"p\"\nmirror_to=[\"p\"]\n");
|
||||
assert!(matches!(
|
||||
Config::parse(&selfm),
|
||||
Err(ConfigError::Invalid(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_bad_syntax_and_unknown_kind() {
|
||||
assert!(matches!(Config::parse("["), Err(ConfigError::Parse(_))));
|
||||
let t = "[machine]\nname=\"a\"\n[root]\npath=\"/x\"\n[providers.p]\nkind=\"gitlab\"\n";
|
||||
assert!(matches!(Config::parse(t), Err(ConfigError::Parse(_))));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user