mirror of
https://github.com/Dasemu/Grove.git
synced 2026-11-27 07:46:13 +00:00
feat: manage namespaces/providers and open worktrees in editors
- grove group add|remove|list and grove provider add|remove|list edit config.toml (validated first, previous file kept as config.toml.bak) - grove open [group/]repo[@branch] launches Zed, VS Code, Claude Code (in a terminal) or Claude Desktop; [open] config for defaults, terminal and own launchers; grove new --open - GUI: provider/namespace forms and removal in Settings, Open buttons on repos and worktrees, open-after-create on New repository - docs/phase8.md, DECISIONS 10-11 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011GZUAGhGYoiLvmfXweQnDY
This commit is contained in:
13 files changed
+2075
-25
No files matched your search
+271
-13
@@ -1,6 +1,6 @@
|
||||
use anyhow::{Context, Result, bail};
|
||||
use clap::{Parser, Subcommand};
|
||||
use grove_core::config::{Config, ProviderKind};
|
||||
use grove_core::config::Config;
|
||||
use grove_core::git::Git;
|
||||
use grove_core::inspect::{state, worktrees};
|
||||
use grove_core::migrate::migrate;
|
||||
@@ -13,6 +13,7 @@ use grove_core::sync::{Options, SyncReport, git_dir_for, sync_repo};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
mod namespace;
|
||||
mod secrets;
|
||||
#[cfg(test)]
|
||||
#[path = "../../../test-support/tmp.rs"]
|
||||
@@ -111,6 +112,34 @@ enum Cmd {
|
||||
name: String,
|
||||
#[arg(long)]
|
||||
public: bool,
|
||||
/// Open the new worktree afterwards (with LAUNCHER, or the default one)
|
||||
#[arg(long, value_name = "LAUNCHER", num_args = 0..=1, default_missing_value = "")]
|
||||
open: Option<String>,
|
||||
},
|
||||
/// Open a worktree in an editor or tool (Zed, VS Code, Claude Code, ...)
|
||||
Open {
|
||||
/// A path, or `[group/]repo[@branch]` under the root (default: the current directory)
|
||||
#[arg(default_value = ".")]
|
||||
target: String,
|
||||
/// Launcher name (see --list; default: `open.default`, else the first installed)
|
||||
#[arg(long = "with", short = 'w', value_name = "LAUNCHER")]
|
||||
with: Option<String>,
|
||||
/// List the launchers and whether they are installed
|
||||
#[arg(long)]
|
||||
list: bool,
|
||||
/// Print the command instead of running it
|
||||
#[arg(long)]
|
||||
print: bool,
|
||||
},
|
||||
/// Manage namespaces: the groups of repos under `<root>/<name>` and where they live
|
||||
Group {
|
||||
#[command(subcommand)]
|
||||
action: GroupCmd,
|
||||
},
|
||||
/// Manage forge accounts (Gitea, Forgejo, GitHub)
|
||||
Provider {
|
||||
#[command(subcommand)]
|
||||
action: ProviderCmd,
|
||||
},
|
||||
/// List (or, with names, clone) remote repos that are not on this machine
|
||||
Import { group: String, names: Vec<String> },
|
||||
@@ -130,6 +159,66 @@ enum Cmd {
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum GroupCmd {
|
||||
/// List the namespaces
|
||||
List,
|
||||
/// Add a namespace (or change one with --replace) and create its directory
|
||||
Add {
|
||||
name: String,
|
||||
/// Provider the repos are created on
|
||||
#[arg(long)]
|
||||
primary: String,
|
||||
/// Provider(s) the repos are mirrored to (repeatable)
|
||||
#[arg(long = "mirror-to", value_name = "PROVIDER")]
|
||||
mirror_to: Vec<String>,
|
||||
/// Owning account or organisation: `PROVIDER=OWNER`, or `OWNER` for the primary
|
||||
/// (repeatable; default: your own account)
|
||||
#[arg(long = "owner", value_name = "[PROVIDER=]OWNER")]
|
||||
owners: Vec<String>,
|
||||
/// Public repos go to this provider instead (then --primary is for private ones)
|
||||
#[arg(long, value_name = "PROVIDER")]
|
||||
public_primary: Option<String>,
|
||||
/// Mirrors of public repos (repeatable; needs --public-primary)
|
||||
#[arg(long = "public-mirror-to", value_name = "PROVIDER")]
|
||||
public_mirror_to: Vec<String>,
|
||||
/// WIP snapshot policy for this namespace: private-only, all, none
|
||||
#[arg(long)]
|
||||
snapshots: Option<String>,
|
||||
/// Do not create worktrees for new remote branches automatically
|
||||
#[arg(long)]
|
||||
no_materialize: bool,
|
||||
/// Replace an existing namespace of that name
|
||||
#[arg(long)]
|
||||
replace: bool,
|
||||
},
|
||||
/// Remove a namespace from the config (its directory and repos stay on disk, unsynced)
|
||||
Remove { name: String },
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum ProviderCmd {
|
||||
/// List the providers
|
||||
List,
|
||||
/// Add a provider (or change one with --replace); then `grove login ID`
|
||||
Add {
|
||||
id: String,
|
||||
/// gitea, forgejo or github
|
||||
#[arg(long)]
|
||||
kind: String,
|
||||
/// Base URL (required for gitea/forgejo)
|
||||
#[arg(long)]
|
||||
url: Option<String>,
|
||||
/// How git talks to it: https (API token) or ssh (your keys)
|
||||
#[arg(long, default_value = "https")]
|
||||
protocol: String,
|
||||
#[arg(long)]
|
||||
replace: bool,
|
||||
},
|
||||
/// Remove a provider no namespace uses
|
||||
Remove { id: String },
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum SecretsCmd {
|
||||
/// Create this machine's age key and publish the public half
|
||||
@@ -260,6 +349,160 @@ fn daemon(action: &DaemonCmd) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Opens `dir` with the launcher `with` (or the default one); `print` only shows the command.
|
||||
fn open_dir(cfg: &Config, dir: &Path, with: Option<&str>, print: bool) -> Result<()> {
|
||||
use grove_core::launch::{System, argv, launchers, pick, spawn};
|
||||
let all = launchers(&cfg.open, &System);
|
||||
let l = pick(&all, &cfg.open, with).map_err(anyhow::Error::msg)?;
|
||||
let cmd = argv(l, dir, &cfg.open, &System).map_err(anyhow::Error::msg)?;
|
||||
if print {
|
||||
println!("{}", cmd.join(" "));
|
||||
return Ok(());
|
||||
}
|
||||
spawn(&cmd, dir).map_err(anyhow::Error::msg)?;
|
||||
println!("opened {} in {}", dir.display(), l.label);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn list_launchers(cfg: &Config) -> Result<()> {
|
||||
let all = grove_core::launch::launchers(&cfg.open, &grove_core::launch::System);
|
||||
let default = grove_core::launch::pick(&all, &cfg.open, None)
|
||||
.ok()
|
||||
.map(|l| l.name.clone());
|
||||
for l in &all {
|
||||
println!(
|
||||
"{} {:<16} {:<16} {}{}",
|
||||
if Some(&l.name) == default.as_ref() {
|
||||
"*"
|
||||
} else {
|
||||
" "
|
||||
},
|
||||
l.name,
|
||||
l.label,
|
||||
if l.available {
|
||||
l.command[0].as_str()
|
||||
} else {
|
||||
"(not installed)"
|
||||
},
|
||||
if l.terminal { " [terminal]" } else { "" }
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn config_path(arg: &Option<PathBuf>) -> Result<PathBuf> {
|
||||
arg.clone()
|
||||
.or_else(Config::default_path)
|
||||
.context("cannot determine config path (set --config)")
|
||||
}
|
||||
|
||||
/// Saves an edited config and says what to do next.
|
||||
fn save_edited(cfg: &Config, path: &Path) -> Result<()> {
|
||||
let bak = namespace::save(cfg, path)?;
|
||||
println!(
|
||||
"saved {} (previous version: {})",
|
||||
path.display(),
|
||||
bak.display()
|
||||
);
|
||||
if grove_daemon::ipc::default_socket_path().exists() {
|
||||
println!("restart the daemon to apply it: systemctl --user restart groved");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn group_cmd(arg: &Option<PathBuf>, action: &GroupCmd) -> Result<()> {
|
||||
let path = config_path(arg)?;
|
||||
let mut cfg = load_config(arg)?;
|
||||
match action {
|
||||
GroupCmd::List => {
|
||||
for l in namespace::describe_groups(&cfg) {
|
||||
println!("{l}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
GroupCmd::Add {
|
||||
name,
|
||||
primary,
|
||||
mirror_to,
|
||||
owners,
|
||||
public_primary,
|
||||
public_mirror_to,
|
||||
snapshots,
|
||||
no_materialize,
|
||||
replace,
|
||||
} => {
|
||||
let snapshots = snapshots
|
||||
.as_deref()
|
||||
.map(namespace::parse_snapshots)
|
||||
.transpose()?;
|
||||
namespace::add_group(
|
||||
&mut cfg,
|
||||
namespace::GroupArgs {
|
||||
name: name.clone(),
|
||||
primary: primary.clone(),
|
||||
mirror_to: mirror_to.clone(),
|
||||
owners: owners.clone(),
|
||||
public_primary: public_primary.clone(),
|
||||
public_mirror_to: public_mirror_to.clone(),
|
||||
snapshots,
|
||||
no_materialize: *no_materialize,
|
||||
},
|
||||
*replace,
|
||||
)?;
|
||||
save_edited(&cfg, &path)?;
|
||||
let dir = cfg.root_path().join(name);
|
||||
std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
|
||||
println!("namespace {name}: {}", dir.display());
|
||||
Ok(())
|
||||
}
|
||||
GroupCmd::Remove { name } => {
|
||||
namespace::remove_group(&mut cfg, name)?;
|
||||
save_edited(&cfg, &path)?;
|
||||
println!(
|
||||
"removed namespace {name}; {} stays on disk and is no longer synced",
|
||||
cfg.root_path().join(name).display()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn provider_cmd(arg: &Option<PathBuf>, action: &ProviderCmd) -> Result<()> {
|
||||
let path = config_path(arg)?;
|
||||
let mut cfg = load_config(arg)?;
|
||||
match action {
|
||||
ProviderCmd::List => {
|
||||
for l in namespace::describe_providers(&cfg) {
|
||||
println!("{l}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
ProviderCmd::Add {
|
||||
id,
|
||||
kind,
|
||||
url,
|
||||
protocol,
|
||||
replace,
|
||||
} => {
|
||||
let p = grove_core::config::Provider {
|
||||
kind: namespace::parse_kind(kind)?,
|
||||
protocol: namespace::parse_protocol(protocol)?,
|
||||
url: url.clone().filter(|u| !u.is_empty()),
|
||||
};
|
||||
namespace::add_provider(&mut cfg, id, p, *replace)?;
|
||||
save_edited(&cfg, &path)?;
|
||||
println!("next: `grove login {id}` (tokens from `tea`/`gh` are used if present)");
|
||||
Ok(())
|
||||
}
|
||||
ProviderCmd::Remove { id } => {
|
||||
namespace::remove_provider(&mut cfg, id)?;
|
||||
save_edited(&cfg, &path)?;
|
||||
println!("removed provider {id} (its stored token stays in the keyring)");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let cli = Cli::parse();
|
||||
match &cli.cmd {
|
||||
@@ -395,22 +638,13 @@ fn main() -> Result<()> {
|
||||
config_repo,
|
||||
force,
|
||||
} => {
|
||||
let protocol = match protocol.as_str() {
|
||||
"https" => grove_core::config::Protocol::Https,
|
||||
"ssh" => grove_core::config::Protocol::Ssh,
|
||||
p => bail!("unknown protocol {p:?} (https, ssh)"),
|
||||
};
|
||||
let protocol = namespace::parse_protocol(protocol)?;
|
||||
let path = cli
|
||||
.config
|
||||
.clone()
|
||||
.or_else(Config::default_path)
|
||||
.context("cannot determine config path (set --config)")?;
|
||||
let kind = match kind.as_str() {
|
||||
"gitea" => ProviderKind::Gitea,
|
||||
"forgejo" => ProviderKind::Forgejo,
|
||||
"github" => ProviderKind::Github,
|
||||
k => bail!("unknown provider kind {k:?} (gitea, forgejo, github)"),
|
||||
};
|
||||
let kind = namespace::parse_kind(kind)?;
|
||||
let machine = machine
|
||||
.clone()
|
||||
.or_else(|| {
|
||||
@@ -451,11 +685,35 @@ fn main() -> Result<()> {
|
||||
group,
|
||||
name,
|
||||
public,
|
||||
open,
|
||||
} => {
|
||||
let wt = workflow::new_repo(&load_config(&cli.config)?, group, name, !public)?;
|
||||
let cfg = load_config(&cli.config)?;
|
||||
let wt = workflow::new_repo(&cfg, group, name, !public)?;
|
||||
println!("ready: {}", wt.display());
|
||||
if let Some(with) = open {
|
||||
let with = (!with.is_empty()).then_some(with.as_str());
|
||||
if let Err(e) = open_dir(&cfg, &wt, with, false) {
|
||||
println!("warning: not opened: {e:#}");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Cmd::Open {
|
||||
target,
|
||||
with,
|
||||
list,
|
||||
print,
|
||||
} => {
|
||||
let cfg = load_config(&cli.config)?;
|
||||
if *list {
|
||||
return list_launchers(&cfg);
|
||||
}
|
||||
let dir =
|
||||
grove_core::launch::resolve_target(&cfg, target).map_err(anyhow::Error::msg)?;
|
||||
open_dir(&cfg, &dir, with.as_deref(), *print)
|
||||
}
|
||||
Cmd::Group { action } => group_cmd(&cli.config, action),
|
||||
Cmd::Provider { action } => provider_cmd(&cli.config, action),
|
||||
Cmd::Import { group, names } => workflow::import(&load_config(&cli.config)?, group, names),
|
||||
Cmd::ConfigRepoInit => {
|
||||
let n = workflow::config_repo_init(&load_config(&cli.config)?)?;
|
||||
|
||||
@@ -0,0 +1,362 @@
|
||||
//! Editing namespaces (`[[groups]]`) and providers in `config.toml` from the CLI and GUI, so
|
||||
//! nobody has to hand-edit TOML. Every change is validated before anything is written, and the
|
||||
//! previous file is kept as `config.toml.bak` (the TOML writer drops comments).
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use grove_core::config::{
|
||||
Config, Group, Layout, Protocol, Provider, ProviderKind, Route, SnapshotPolicy, is_plain_name,
|
||||
};
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub struct GroupArgs {
|
||||
pub name: String,
|
||||
pub primary: String,
|
||||
pub mirror_to: Vec<String>,
|
||||
/// `PROVIDER=OWNER`, or a bare `OWNER` for the primary provider.
|
||||
pub owners: Vec<String>,
|
||||
pub public_primary: Option<String>,
|
||||
pub public_mirror_to: Vec<String>,
|
||||
pub snapshots: Option<SnapshotPolicy>,
|
||||
pub no_materialize: bool,
|
||||
}
|
||||
|
||||
pub fn parse_kind(k: &str) -> Result<ProviderKind> {
|
||||
Ok(match k {
|
||||
"gitea" => ProviderKind::Gitea,
|
||||
"forgejo" => ProviderKind::Forgejo,
|
||||
"github" => ProviderKind::Github,
|
||||
k => bail!("unknown provider kind {k:?} (gitea, forgejo, github)"),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn parse_protocol(p: &str) -> Result<Protocol> {
|
||||
Ok(match p {
|
||||
"https" => Protocol::Https,
|
||||
"ssh" => Protocol::Ssh,
|
||||
p => bail!("unknown protocol {p:?} (https, ssh)"),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn parse_snapshots(s: &str) -> Result<SnapshotPolicy> {
|
||||
Ok(match s {
|
||||
"private-only" => SnapshotPolicy::PrivateOnly,
|
||||
"all" => SnapshotPolicy::All,
|
||||
"none" => SnapshotPolicy::None,
|
||||
s => bail!("unknown snapshot policy {s:?} (private-only, all, none)"),
|
||||
})
|
||||
}
|
||||
|
||||
fn kind_str(k: ProviderKind) -> &'static str {
|
||||
match k {
|
||||
ProviderKind::Gitea => "gitea",
|
||||
ProviderKind::Forgejo => "forgejo",
|
||||
ProviderKind::Github => "github",
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds the namespace `a.name` (or replaces it with `replace`, keeping its layout).
|
||||
pub fn add_group(cfg: &mut Config, a: GroupArgs, replace: bool) -> Result<()> {
|
||||
let existing = cfg.groups.iter().position(|g| g.name == a.name);
|
||||
if existing.is_some() && !replace {
|
||||
bail!(
|
||||
"namespace {:?} already exists (use --replace to change it)",
|
||||
a.name
|
||||
);
|
||||
}
|
||||
let mut owners = BTreeMap::new();
|
||||
for o in &a.owners {
|
||||
let (p, who) = o
|
||||
.split_once('=')
|
||||
.map_or((a.primary.as_str(), o.as_str()), |(p, w)| (p, w));
|
||||
owners.insert(p.trim().to_string(), who.trim().to_string());
|
||||
}
|
||||
let public = a.public_primary.map(|primary| Route {
|
||||
primary,
|
||||
mirror_to: a.public_mirror_to.clone(),
|
||||
});
|
||||
if public.is_none() && !a.public_mirror_to.is_empty() {
|
||||
bail!("--public-mirror-to needs --public-primary");
|
||||
}
|
||||
let g = Group {
|
||||
name: a.name,
|
||||
primary: a.primary,
|
||||
mirror_to: a.mirror_to,
|
||||
layout: existing.map_or(Layout::BareWorktrees, |i| cfg.groups[i].layout),
|
||||
auto_materialize: !a.no_materialize,
|
||||
snapshots: a.snapshots,
|
||||
owners,
|
||||
public,
|
||||
};
|
||||
match existing {
|
||||
Some(i) => cfg.groups[i] = g,
|
||||
None => cfg.groups.push(g),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn remove_group(cfg: &mut Config, name: &str) -> Result<()> {
|
||||
let before = cfg.groups.len();
|
||||
cfg.groups.retain(|g| g.name != name);
|
||||
if cfg.groups.len() == before {
|
||||
bail!("no namespace {name:?}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn add_provider(cfg: &mut Config, id: &str, p: Provider, replace: bool) -> Result<()> {
|
||||
if !is_plain_name(id) {
|
||||
bail!("provider id {id:?} must use only letters, digits, '-' or '_'");
|
||||
}
|
||||
if p.kind != ProviderKind::Github && p.url.as_deref().is_none_or(str::is_empty) {
|
||||
bail!("a {} provider needs --url", kind_str(p.kind));
|
||||
}
|
||||
if let Some(u) = &p.url
|
||||
&& !u.starts_with("https://")
|
||||
&& !u.starts_with("http://")
|
||||
{
|
||||
bail!("--url must start with https:// (got {u:?})");
|
||||
}
|
||||
if cfg.providers.contains_key(id) && !replace {
|
||||
bail!("provider {id:?} already exists (use --replace to change it)");
|
||||
}
|
||||
cfg.providers.insert(id.to_string(), p);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Removes a provider no namespace or the config repo still uses.
|
||||
pub fn remove_provider(cfg: &mut Config, id: &str) -> Result<()> {
|
||||
if !cfg.providers.contains_key(id) {
|
||||
bail!("no provider {id:?}");
|
||||
}
|
||||
let users: Vec<&str> = cfg
|
||||
.groups
|
||||
.iter()
|
||||
.filter(|g| {
|
||||
let routes = [Some(g.route(true)), g.public.clone()];
|
||||
routes
|
||||
.iter()
|
||||
.flatten()
|
||||
.any(|r| r.primary == id || r.mirror_to.iter().any(|m| m == id))
|
||||
|| g.owners.contains_key(id)
|
||||
})
|
||||
.map(|g| g.name.as_str())
|
||||
.collect();
|
||||
if !users.is_empty() {
|
||||
bail!(
|
||||
"provider {id:?} is used by namespace(s) {}; change or remove them first",
|
||||
users.join(", ")
|
||||
);
|
||||
}
|
||||
if cfg.config_repo.as_ref().is_some_and(|c| c.provider == id) {
|
||||
bail!("provider {id:?} holds the config repo; it cannot be removed");
|
||||
}
|
||||
cfg.providers.remove(id);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validates `cfg`, keeps the current file as `<path>.bak` and writes the new one.
|
||||
pub fn save(cfg: &Config, path: &Path) -> Result<PathBuf> {
|
||||
let text = toml::to_string_pretty(cfg)?;
|
||||
Config::parse(&text)?;
|
||||
let bak = path.with_extension("toml.bak");
|
||||
if path.exists() {
|
||||
std::fs::copy(path, &bak).with_context(|| format!("backing up {}", path.display()))?;
|
||||
}
|
||||
cfg.save(path)?;
|
||||
Ok(bak)
|
||||
}
|
||||
|
||||
/// One line per namespace: `name primary -> mirrors [public: ...] owners`.
|
||||
pub fn describe_groups(cfg: &Config) -> Vec<String> {
|
||||
cfg.groups
|
||||
.iter()
|
||||
.map(|g| {
|
||||
let mut s = format!("{:<16} {}", g.name, route_str(&g.route(true)));
|
||||
if let Some(p) = &g.public {
|
||||
s.push_str(&format!(" public: {}", route_str(p)));
|
||||
}
|
||||
if !g.owners.is_empty() {
|
||||
let o: Vec<String> = g.owners.iter().map(|(p, w)| format!("{p}={w}")).collect();
|
||||
s.push_str(&format!(" owners: {}", o.join(",")));
|
||||
}
|
||||
if let Some(sp) = g.snapshots {
|
||||
let name = match sp {
|
||||
SnapshotPolicy::PrivateOnly => "private-only",
|
||||
SnapshotPolicy::All => "all",
|
||||
SnapshotPolicy::None => "none",
|
||||
};
|
||||
s.push_str(&format!(" snapshots: {name}"));
|
||||
}
|
||||
s
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn route_str(r: &Route) -> String {
|
||||
if r.mirror_to.is_empty() {
|
||||
r.primary.clone()
|
||||
} else {
|
||||
format!("{} -> {}", r.primary, r.mirror_to.join(", "))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn describe_providers(cfg: &Config) -> Vec<String> {
|
||||
cfg.providers
|
||||
.iter()
|
||||
.map(|(id, p)| {
|
||||
format!(
|
||||
"{id:<16} {:<8} {:<6} {}",
|
||||
kind_str(p.kind),
|
||||
p.protocol.as_str(),
|
||||
p.url.as_deref().unwrap_or("https://github.com")
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn cfg() -> Config {
|
||||
Config::parse(
|
||||
"[machine]\nname=\"m\"\n[root]\npath=\"/x\"\n\
|
||||
[providers.gitea]\nkind=\"gitea\"\nurl=\"https://git.example.es\"\n\
|
||||
[providers.gh]\nkind=\"github\"\n\
|
||||
[[groups]]\nname=\"work\"\nprimary=\"gitea\"\nlayout=\"plain\"\n",
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn args(name: &str, primary: &str) -> GroupArgs {
|
||||
GroupArgs {
|
||||
name: name.into(),
|
||||
primary: primary.into(),
|
||||
mirror_to: vec![],
|
||||
owners: vec![],
|
||||
public_primary: None,
|
||||
public_mirror_to: vec![],
|
||||
snapshots: None,
|
||||
no_materialize: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn valid(c: &Config) -> bool {
|
||||
Config::parse(&toml::to_string_pretty(c).unwrap()).is_ok()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_group_with_mirror_owners_and_public_route() {
|
||||
let mut c = cfg();
|
||||
let mut a = args("oss", "gitea");
|
||||
a.mirror_to = vec!["gh".into()];
|
||||
a.owners = vec!["Zenvairo".into(), "gh=zenvairo-gh".into()];
|
||||
a.public_primary = Some("gh".into());
|
||||
a.public_mirror_to = vec!["gitea".into()];
|
||||
a.snapshots = Some(SnapshotPolicy::None);
|
||||
add_group(&mut c, a, false).unwrap();
|
||||
assert!(valid(&c));
|
||||
let g = &c.groups[1];
|
||||
assert_eq!(g.owner("gitea"), Some("Zenvairo"));
|
||||
assert_eq!(g.owner("gh"), Some("zenvairo-gh"));
|
||||
assert_eq!(g.route(false).primary, "gh");
|
||||
assert_eq!(c.snapshot_policy("oss"), SnapshotPolicy::None);
|
||||
let lines = describe_groups(&c);
|
||||
assert!(lines[1].contains("gitea -> gh") && lines[1].contains("public: gh -> gitea"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replacing_a_group_needs_the_flag_and_keeps_its_layout() {
|
||||
let mut c = cfg();
|
||||
assert!(add_group(&mut c, args("work", "gh"), false).is_err());
|
||||
add_group(&mut c, args("work", "gh"), true).unwrap();
|
||||
assert_eq!(c.groups.len(), 1);
|
||||
assert_eq!(c.groups[0].primary, "gh");
|
||||
assert_eq!(c.groups[0].layout, Layout::Plain);
|
||||
let mut bad = args("x", "gitea");
|
||||
bad.public_mirror_to = vec!["gh".into()];
|
||||
assert!(add_group(&mut c, bad, false).is_err());
|
||||
// Unknown providers are caught by validation before saving.
|
||||
add_group(&mut c, args("y", "nope"), false).unwrap();
|
||||
assert!(!valid(&c));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn providers_in_use_cannot_be_removed() {
|
||||
let mut c = cfg();
|
||||
assert!(
|
||||
remove_provider(&mut c, "gitea")
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("work")
|
||||
);
|
||||
remove_provider(&mut c, "gh").unwrap();
|
||||
assert!(remove_provider(&mut c, "gh").is_err());
|
||||
remove_group(&mut c, "work").unwrap();
|
||||
assert!(remove_group(&mut c, "work").is_err());
|
||||
remove_provider(&mut c, "gitea").unwrap();
|
||||
assert!(valid(&c));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_provider_checks_id_url_and_duplicates() {
|
||||
let mut c = cfg();
|
||||
let p = |kind, url: Option<&str>| Provider {
|
||||
kind,
|
||||
protocol: Protocol::Ssh,
|
||||
url: url.map(String::from),
|
||||
};
|
||||
assert!(add_provider(&mut c, "a b", p(ProviderKind::Github, None), false).is_err());
|
||||
assert!(add_provider(&mut c, "fj", p(ProviderKind::Forgejo, None), false).is_err());
|
||||
assert!(
|
||||
add_provider(&mut c, "fj", p(ProviderKind::Forgejo, Some("git.x")), false).is_err()
|
||||
);
|
||||
add_provider(
|
||||
&mut c,
|
||||
"fj",
|
||||
p(ProviderKind::Forgejo, Some("https://git.x")),
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(add_provider(&mut c, "fj", p(ProviderKind::Github, None), false).is_err());
|
||||
add_provider(&mut c, "fj", p(ProviderKind::Github, None), true).unwrap();
|
||||
assert!(valid(&c));
|
||||
assert!(
|
||||
describe_providers(&c)
|
||||
.iter()
|
||||
.any(|l| l.starts_with("fj") && l.contains("ssh"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_keeps_a_backup() {
|
||||
let tmp = crate::test_tmp::TempDir::new("ns-save");
|
||||
let path = tmp.path().join("config.toml");
|
||||
std::fs::write(
|
||||
&path,
|
||||
"# my comment\n[machine]\nname=\"m\"\n[root]\npath=\"/x\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
let mut c = Config::load(&path).unwrap();
|
||||
c.providers.insert(
|
||||
"gh".into(),
|
||||
Provider {
|
||||
kind: ProviderKind::Github,
|
||||
protocol: Protocol::Https,
|
||||
url: None,
|
||||
},
|
||||
);
|
||||
let bak = save(&c, &path).unwrap();
|
||||
assert!(
|
||||
std::fs::read_to_string(bak)
|
||||
.unwrap()
|
||||
.contains("# my comment")
|
||||
);
|
||||
assert_eq!(Config::load(&path).unwrap(), c);
|
||||
// An invalid config is never written.
|
||||
add_group(&mut c, args("g", "nope"), false).unwrap();
|
||||
assert!(save(&c, &path).is_err());
|
||||
assert!(Config::load(&path).unwrap().groups.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -182,6 +182,7 @@ pub fn init(path: &Path, a: InitArgs, force: bool) -> Result<Config> {
|
||||
public: None,
|
||||
}],
|
||||
sync: Default::default(),
|
||||
open: Default::default(),
|
||||
config_repo: a.config_repo.map(|name| grove_core::config::ConfigRepo {
|
||||
provider: a.provider,
|
||||
name,
|
||||
|
||||
Reference in new issue
Block a user