From 138404df6fc6076067dab7b49399ee92da79a55c Mon Sep 17 00:00:00 2001 From: Lorenz Leutgeb Date: Sat, 29 Aug 2026 23:22:01 +0200 Subject: [PATCH] =?UTF-8?q?radicle:=20Rely=20less=20on=20`=E2=80=A6.projec?= =?UTF-8?q?t`=20payload?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Many codepaths error if the `xyz.radicle.project` payload is not present in the identity document. Change these to fall back gracefully. Loading of payloads is unified in `GetPayload`. An important detail is that `PayloadError::NotFound` is removed, and `Option` is used instead. --- crates/radicle-cli/examples/rad-block.md | 10 +- .../examples/rad-seed-and-follow.md | 10 +- crates/radicle-cli/examples/rad-seed-scope.md | 30 +++--- crates/radicle-cli/src/commands/checkout.rs | 25 +++-- crates/radicle-cli/src/commands/clone.rs | 46 ++++++--- crates/radicle-cli/src/commands/inbox.rs | 21 ++-- crates/radicle-cli/src/commands/init.rs | 36 ++++--- crates/radicle-cli/src/commands/ls.rs | 30 +++--- crates/radicle-cli/src/commands/remote.rs | 13 ++- crates/radicle-cli/src/commands/seed.rs | 17 +++- crates/radicle-node/src/tests/e2e.rs | 11 ++- crates/radicle/src/cob/identity.rs | 11 ++- .../radicle/src/cob/identity/test/property.rs | 4 +- crates/radicle/src/git.rs | 1 + crates/radicle/src/identity/doc.rs | 97 ++++++++----------- crates/radicle/src/identity/doc/update.rs | 27 +++--- crates/radicle/src/identity/project.rs | 4 + crates/radicle/src/rad.rs | 72 ++++++++------ crates/radicle/src/storage.rs | 5 +- crates/radicle/src/storage/git.rs | 24 ++--- crates/radicle/src/storage/refs.rs | 3 +- crates/radicle/src/test/storage.rs | 2 +- 22 files changed, 284 insertions(+), 215 deletions(-) diff --git a/crates/radicle-cli/examples/rad-block.md b/crates/radicle-cli/examples/rad-block.md index a29630cda..71ef29028 100644 --- a/crates/radicle-cli/examples/rad-block.md +++ b/crates/radicle-cli/examples/rad-block.md @@ -35,11 +35,11 @@ And a 'block' policy was added: ``` $ rad seed -╭───────────────────────────────────────────────────────────╮ -│ Repository Name Policy Scope │ -├───────────────────────────────────────────────────────────┤ -│ rad:z42hL2jL4XNk6K8oHQaSWfMgCL7ji block │ -╰───────────────────────────────────────────────────────────╯ +╭──────────────────────────────────────────────────────────────────────────────╮ +│ Repository Name Policy Scope │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ rad:z42hL2jL4XNk6K8oHQaSWfMgCL7ji Error determining name. block │ +╰──────────────────────────────────────────────────────────────────────────────╯ ``` If we want to reverse the blocking of the RID we can use `rad unblock`: diff --git a/crates/radicle-cli/examples/rad-seed-and-follow.md b/crates/radicle-cli/examples/rad-seed-and-follow.md index ae6d4ff8d..a01b22456 100644 --- a/crates/radicle-cli/examples/rad-seed-and-follow.md +++ b/crates/radicle-cli/examples/rad-seed-and-follow.md @@ -29,9 +29,9 @@ We can list the repositories we are seeding by omitting the RID: ``` $ rad seed -╭──────────────────────────────────────────────────────────────╮ -│ Repository Name Policy Scope │ -├──────────────────────────────────────────────────────────────┤ -│ rad:z42hL2jL4XNk6K8oHQaSWfMgCL7ji allow followed │ -╰──────────────────────────────────────────────────────────────╯ +╭─────────────────────────────────────────────────────────────────────────────────╮ +│ Repository Name Policy Scope │ +├─────────────────────────────────────────────────────────────────────────────────┤ +│ rad:z42hL2jL4XNk6K8oHQaSWfMgCL7ji Error determining name. allow followed │ +╰─────────────────────────────────────────────────────────────────────────────────╯ ``` diff --git a/crates/radicle-cli/examples/rad-seed-scope.md b/crates/radicle-cli/examples/rad-seed-scope.md index a50233690..2652fc7db 100644 --- a/crates/radicle-cli/examples/rad-seed-scope.md +++ b/crates/radicle-cli/examples/rad-seed-scope.md @@ -4,11 +4,11 @@ By default `rad seed` should add a seeding policy with the `followed` scope: $ rad seed --no-fetch rad:z42hL2jL4XNk6K8oHQaSWfMgCL7ji ✓ Seeding policy updated for rad:z42hL2jL4XNk6K8oHQaSWfMgCL7ji with scope 'followed' $ rad seed -╭──────────────────────────────────────────────────────────────╮ -│ Repository Name Policy Scope │ -├──────────────────────────────────────────────────────────────┤ -│ rad:z42hL2jL4XNk6K8oHQaSWfMgCL7ji allow followed │ -╰──────────────────────────────────────────────────────────────╯ +╭─────────────────────────────────────────────────────────────────────────────────╮ +│ Repository Name Policy Scope │ +├─────────────────────────────────────────────────────────────────────────────────┤ +│ rad:z42hL2jL4XNk6K8oHQaSWfMgCL7ji Error determining name. allow followed │ +╰─────────────────────────────────────────────────────────────────────────────────╯ ``` The policy can be updated by explicitly specifying a different scope: @@ -17,11 +17,11 @@ The policy can be updated by explicitly specifying a different scope: $ rad seed --no-fetch rad:z42hL2jL4XNk6K8oHQaSWfMgCL7ji --scope all ✓ Seeding policy updated for rad:z42hL2jL4XNk6K8oHQaSWfMgCL7ji with scope 'all' $ rad seed -╭───────────────────────────────────────────────────────────╮ -│ Repository Name Policy Scope │ -├───────────────────────────────────────────────────────────┤ -│ rad:z42hL2jL4XNk6K8oHQaSWfMgCL7ji allow all │ -╰───────────────────────────────────────────────────────────╯ +╭──────────────────────────────────────────────────────────────────────────────╮ +│ Repository Name Policy Scope │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ rad:z42hL2jL4XNk6K8oHQaSWfMgCL7ji Error determining name. allow all │ +╰──────────────────────────────────────────────────────────────────────────────╯ ``` Running `rad seed` again without an explicit scope parameter should not change the existing policy: @@ -30,9 +30,9 @@ Running `rad seed` again without an explicit scope parameter should not change t $ rad seed --no-fetch rad:z42hL2jL4XNk6K8oHQaSWfMgCL7ji ✓ Seeding policy exists for rad:z42hL2jL4XNk6K8oHQaSWfMgCL7ji with scope 'all' $ rad seed -╭───────────────────────────────────────────────────────────╮ -│ Repository Name Policy Scope │ -├───────────────────────────────────────────────────────────┤ -│ rad:z42hL2jL4XNk6K8oHQaSWfMgCL7ji allow all │ -╰───────────────────────────────────────────────────────────╯ +╭──────────────────────────────────────────────────────────────────────────────╮ +│ Repository Name Policy Scope │ +├──────────────────────────────────────────────────────────────────────────────┤ +│ rad:z42hL2jL4XNk6K8oHQaSWfMgCL7ji Error determining name. allow all │ +╰──────────────────────────────────────────────────────────────────────────────╯ ``` diff --git a/crates/radicle-cli/src/commands/checkout.rs b/crates/radicle-cli/src/commands/checkout.rs index 3b8a1b1f5..4cb69a92e 100644 --- a/crates/radicle-cli/src/commands/checkout.rs +++ b/crates/radicle-cli/src/commands/checkout.rs @@ -6,6 +6,7 @@ use anyhow::Context as _; use anyhow::anyhow; use radicle::git; +use radicle::identity::doc::GetPayload as _; use radicle::node::AliasStore; use radicle::prelude::*; use radicle::storage::git::transport; @@ -25,12 +26,24 @@ pub fn run(args: Args, ctx: impl term::Context) -> anyhow::Result<()> { fn execute(args: Args, profile: &Profile) -> anyhow::Result { let storage = &profile.storage; let remote = args.remote.unwrap_or(profile.did()); - let doc = storage - .repository(args.repo)? - .identity_doc() + + let repo = storage + .repository(args.repo) .context("repository could not be found in local storage")?; - let payload = doc.project()?; - let path = PathBuf::from(payload.name()); + + let doc = repo.identity_doc()?; + + let default_branch_name = doc.default_branch_name().ok(); + + let path = PathBuf::from( + doc.project() + .transpose() + .ok() + .flatten() + .as_ref() + .map(|project| project.name().to_string()) + .unwrap_or_else(|| repo.id().to_string()), + ); transport::local::register(storage.clone()); @@ -66,7 +79,7 @@ fn execute(args: Args, profile: &Profile) -> anyhow::Result { setup_remotes( project::SetupRemote { rid: args.repo, - tracking: Some(payload.default_branch().clone()), + tracking: default_branch_name, repo: &repo, fetch: true, }, diff --git a/crates/radicle-cli/src/commands/clone.rs b/crates/radicle-cli/src/commands/clone.rs index e0adfdce0..954791823 100644 --- a/crates/radicle-cli/src/commands/clone.rs +++ b/crates/radicle-cli/src/commands/clone.rs @@ -7,8 +7,8 @@ use radicle::patch::cache::Patches as _; use thiserror::Error; use radicle::git::raw; -use radicle::identity::doc; use radicle::identity::doc::RepoId; +use radicle::identity::doc::{self, GetPayload as _}; use radicle::node; use radicle::node::policy; use radicle::node::policy::Scope; @@ -42,7 +42,7 @@ pub fn run(args: Args, ctx: impl term::Context) -> anyhow::Result<()> { working_copy: working, repository: repo, doc, - project: proj, + project, } = clone( args.repo, args.directory.clone(), @@ -60,7 +60,9 @@ pub fn run(args: Args, ctx: impl term::Context) -> anyhow::Result<()> { .map(|d| **d) .filter(|id| id != profile.id()) .collect::>(); - let default_branch = proj.default_branch().clone(); + + let default_branch = repo.identity_doc()?.default_branch_name().ok(); + let path = if !args.bare { working.workdir().unwrap() } else { @@ -72,7 +74,7 @@ pub fn run(args: Args, ctx: impl term::Context) -> anyhow::Result<()> { checkout::setup_remotes( project::SetupRemote { rid: args.repo, - tracking: Some(default_branch), + tracking: default_branch, repo: &working, fetch: true, }, @@ -86,8 +88,11 @@ pub fn run(args: Args, ctx: impl term::Context) -> anyhow::Result<()> { ); let mut info: term::Table<1, term::Line> = term::Table::new(term::TableOptions::bordered()); - info.push([term::format::bold(proj.name()).into()]); - info.push([term::format::italic(proj.description()).into()]); + + if let Some(project) = project.as_ref() { + info.push([term::format::bold(project.name()).into()]); + info.push([term::format::italic(project.description()).into()]); + } let issues = term::cob::issues(&profile, &repo)?.counts()?; let patches = term::cob::patches(&profile, &repo)?.counts()?; @@ -101,9 +106,14 @@ pub fn run(args: Args, ctx: impl term::Context) -> anyhow::Result<()> { ])]); info.print(); - let location = args - .directory - .map_or(proj.name().to_string(), |loc| loc.display().to_string()); + let location = args.directory.map_or( + project + .as_ref() + .map(|project| project.name().to_string()) + .unwrap_or_else(|| repo.rid().to_string()), + |loc| loc.display().to_string(), + ); + term::info!( "Run {} to go to the repository directory.", term::format::command(format!("cd ./{location}")), @@ -132,7 +142,7 @@ struct Checkout { path: PathBuf, repository: storage::git::Repository, doc: Doc, - project: Project, + project: Option, bare: bool, } @@ -147,10 +157,16 @@ impl Checkout { let doc = repository .identity_doc() .map_err(|err| CheckoutFailure::Identity { rid, err })?; - let proj = doc - .project() - .map_err(|err| CheckoutFailure::Payload { rid, err })?; - let path = directory.unwrap_or_else(|| PathBuf::from(proj.name())); + let proj = doc.project().transpose().ok().flatten(); + + let path = directory.unwrap_or_else(|| { + PathBuf::from( + proj.as_ref() + .map(|project| project.name().to_owned()) + .unwrap_or_else(|| rid.to_string()), + ) + }); + // N.b. fail if the path exists and is not empty if path.exists() && path.read_dir().map_or(true, |mut dir| dir.next().is_some()) { return Err(CheckoutFailure::Exists { rid, path }); @@ -288,7 +304,7 @@ struct Success { working_copy: raw::Repository, repository: storage::git::Repository, doc: Doc, - project: Project, + project: Option, } impl CloneResult { diff --git a/crates/radicle-cli/src/commands/inbox.rs b/crates/radicle-cli/src/commands/inbox.rs index 1395f55a1..66ed1e029 100644 --- a/crates/radicle-cli/src/commands/inbox.rs +++ b/crates/radicle-cli/src/commands/inbox.rs @@ -9,7 +9,7 @@ use localtime::LocalTime; use radicle::cob::TypedId; use radicle::git::BranchName; use radicle::git::fmt::{Component, Qualified}; -use radicle::identity::Identity; +use radicle::identity::{Identity, doc::GetPayload as _}; use radicle::issue::cache::Issues as _; use radicle::node::notifications; use radicle::node::notifications::*; @@ -145,9 +145,8 @@ where ::Repository: cob::Store, { let repo = storage.repository(rid)?; - let (_, head) = repo.head()?; + let head = repo.head().ok().map(|(_, head)| head); let doc = repo.identity_doc()?; - let proj = doc.project()?; let issues = term::cob::issues(profile, &repo)?; let patches = term::cob::patches(profile, &repo)?; @@ -186,9 +185,13 @@ where state, name, } = match &n.kind { - NotificationKind::Branch { name } => match NotificationRow::branch(name, head, &n, &repo) { - Err(e) => return Some(Err(e)), - Ok(b) => b, + NotificationKind::Branch { name } => + match head { + Some(head) => match NotificationRow::branch(name, head, &n, &repo) { + Err(e) => return Some(Err(e)), + Ok(b) => b, + }, + None => return None }, NotificationKind::Cob { typed_id } => { match NotificationRow::cob(typed_id, &n, &issues, &patches, &repo) { @@ -234,7 +237,11 @@ where Ok(Some( term::VStack::default() .border(Some(term::colors::FAINT)) - .child(term::label(term::format::bold(proj.name()))) + .child(term::label(match doc.project() { + Some(Ok(project)) => term::format::bold(project.name().to_string()), + Some(Err(_)) => term::format::negative("Error determining name.".to_string()), + None => term::format::dim("No name provided.".to_string()), + })) .divider() .child(table), )) diff --git a/crates/radicle-cli/src/commands/init.rs b/crates/radicle-cli/src/commands/init.rs index 18cc903c5..ac95b979b 100644 --- a/crates/radicle-cli/src/commands/init.rs +++ b/crates/radicle-cli/src/commands/init.rs @@ -16,10 +16,10 @@ use radicle::git::fmt::RefString; use radicle::git::raw; use radicle::git::raw::ErrorExt as _; use radicle::identity::project::ProjectName; -use radicle::identity::{Doc, RepoId, Visibility}; +use radicle::identity::{Doc, RepoId, Visibility, doc::GetPayload as _}; use radicle::node::events::UploadPack; use radicle::node::{DEFAULT_SUBSCRIBE_TIMEOUT, Event, Handle, NodeId}; -use radicle::storage::ReadStorage as _; +use radicle::storage::{ReadRepository, ReadStorage as _}; use radicle::{Node, profile}; use crate::commands; @@ -147,11 +147,15 @@ pub fn init(repo: raw::Repository, args: Args, profile: &profile::Profile) -> an &profile.storage, ) { Ok((rid, doc, _)) => { - let proj = doc.project()?; + let proj = doc.project().transpose().ok().flatten(); spinner.message(format!( "Repository {} created.", - term::format::highlight(proj.name()) + term::format::highlight( + proj.as_ref() + .map(|project| project.name().to_string()) + .unwrap_or_else(|| rid.to_string()) + ) )); spinner.finish(); @@ -168,13 +172,13 @@ pub fn init(repo: raw::Repository, args: Args, profile: &profile::Profile) -> an } } - if args.set_upstream || git::branch_remote(&repo, proj.default_branch()).is_err() { + if args.set_upstream || git::branch_remote(&repo, &branch).is_err() { // Setup, e.g. `master` -> `rad/master` radicle::git::set_upstream( &repo, &*radicle::rad::REMOTE_NAME, - proj.default_branch(), - radicle::git::refs::workdir::branch(proj.default_branch()), + &branch, + radicle::git::refs::workdir::branch(&branch), )?; } else { push_cmd = format!("git push {} {branch}", *radicle::rad::REMOTE_NAME); @@ -231,7 +235,6 @@ pub fn init_existing( profile: &profile::Profile, ) -> anyhow::Result<()> { let stored = profile.storage.repository(rid)?; - let project = stored.project()?; let url = radicle::git::Url::from(rid); let interactive = args.interactive(); @@ -244,13 +247,16 @@ pub fn init_existing( )?; if args.set_upstream { - // Setup, e.g. `master` -> `rad/master` - radicle::git::set_upstream( - &working, - &*radicle::rad::REMOTE_NAME, - project.default_branch(), - radicle::git::refs::workdir::branch(project.default_branch()), - )?; + match stored.identity_doc()?.default_branch_name() { + Err(_) => { + term::warning("Failed to set upstream."); + } + Ok(branch) => { + // Setup, e.g. `master` -> `rad/master` + let merge = radicle::git::refs::workdir::branch(&branch); + radicle::git::set_upstream(&working, &*radicle::rad::REMOTE_NAME, branch, merge)?; + } + } } if args.setup_signing { diff --git a/crates/radicle-cli/src/commands/ls.rs b/crates/radicle-cli/src/commands/ls.rs index b4a486676..5d8be68d4 100644 --- a/crates/radicle-cli/src/commands/ls.rs +++ b/crates/radicle-cli/src/commands/ls.rs @@ -2,7 +2,11 @@ mod args; pub use args::Args; -use radicle::storage::{ReadStorage, RepositoryInfo, SignedRefsInfo}; +use radicle::{ + git::Oid, + identity::doc::GetPayload as _, + storage::{ReadStorage, RepositoryInfo, SignedRefsInfo}, +}; use crate::terminal as term; @@ -45,17 +49,15 @@ pub fn run(args: Args, ctx: impl term::Context) -> anyhow::Result<()> { if !seeded && args.seeded { continue; } - let proj = match doc.project() { - Ok(p) => p, - Err(e) => { - log::error!(target: "cli", "Error loading project payload for {rid}: {e}"); - continue; - } - }; - let head = term::format::oid(head).into(); + let proj = doc.project(); + let head = term::format::oid(head.unwrap_or(Oid::ZERO_SHA1)).into(); rows.push([ - term::format::bold(proj.name().to_owned()), + match proj.as_ref() { + Some(Ok(project)) => term::format::bold(project.name().to_string()), + Some(Err(_)) => term::format::negative("Error determining name.".to_string()), + None => term::format::dim("No name provided.".to_string()), + }, term::format::tertiary(rid.urn()), if seeded { term::format::visibility(doc.visibility()).into() @@ -63,7 +65,13 @@ pub fn run(args: Args, ctx: impl term::Context) -> anyhow::Result<()> { term::format::dim("local").into() }, term::format::secondary(head), - term::format::italic(proj.description().to_owned()), + match proj.as_ref() { + Some(Ok(project)) => term::format::italic(project.description().to_string()), + Some(Err(_)) => { + term::format::negative("Error determining description.".to_string()) + } + None => term::format::dim("No description provided.".to_string()), + }, ]); } rows.sort(); diff --git a/crates/radicle-cli/src/commands/remote.rs b/crates/radicle-cli/src/commands/remote.rs index c7ed3fca7..ffe7bd90d 100644 --- a/crates/radicle-cli/src/commands/remote.rs +++ b/crates/radicle-cli/src/commands/remote.rs @@ -6,7 +6,7 @@ pub mod rm; mod args; -use radicle::storage::ReadStorage; +use radicle::storage::{ReadRepository, ReadStorage}; use crate::terminal::Context; use crate::terminal::{self as term, args::rid_or_cwd}; @@ -30,13 +30,18 @@ pub fn run(args: Args, ctx: impl Context) -> anyhow::Result<()> { fetch, sync, } => { - let proj = profile.storage.repository(rid)?.project()?; - let branch = proj.default_branch(); + let branch = profile + .storage + .repository(rid)? + .identity_doc()? + .default_branch_name() + .ok(); + self::add::run( rid, &nid, name, - Some(branch.clone()), + branch, &profile, &working, fetch.should_fetch(), diff --git a/crates/radicle-cli/src/commands/seed.rs b/crates/radicle-cli/src/commands/seed.rs index 2b9e01a2b..3d2574176 100644 --- a/crates/radicle-cli/src/commands/seed.rs +++ b/crates/radicle-cli/src/commands/seed.rs @@ -1,5 +1,6 @@ mod args; +use radicle::identity::doc::GetPayload as _; use radicle::node::Handle; use radicle::node::policy; use radicle::node::policy::{Policy, Scope}; @@ -90,10 +91,18 @@ pub fn seeding(profile: &Profile) -> anyhow::Result<()> { match policy { Ok(policy::SeedPolicy { rid, policy }) => { let id = rid.to_string(); - let name = storage + + let name = match storage .repository(rid) - .and_then(|repo| repo.project().map(|proj| proj.name().to_string())) - .unwrap_or_default(); + .and_then(|repo| repo.identity_doc().map(|identity| identity.project())) + { + Ok(Some(Ok(project))) => project.name().to_string().into(), + Ok(None) => term::format::dim("No name provided.".to_string()), + Err(_) | Ok(Some(Err(_))) => { + term::format::negative("Error determining name.".to_string()) + } + }; + let scope = policy .scope() .map_or(String::new(), |scope| scope.to_string()); @@ -101,7 +110,7 @@ pub fn seeding(profile: &Profile) -> anyhow::Result<()> { t.push([ term::format::tertiary(id), - name.into(), + name, policy, term::format::dim(scope), ]) diff --git a/crates/radicle-node/src/tests/e2e.rs b/crates/radicle-node/src/tests/e2e.rs index 54fc6e447..fb159bf4e 100644 --- a/crates/radicle-node/src/tests/e2e.rs +++ b/crates/radicle-node/src/tests/e2e.rs @@ -5,6 +5,7 @@ use radicle::cob::Title; use radicle::cob::store::access::{ReadOnly, WriteAs}; use radicle::crypto::{Signer as _, SigningKey}; use radicle::git::fmt::Component; +use radicle::identity::doc::GetPayload as _; use test_log::test; use radicle::git::raw::ErrorExt as _; @@ -847,7 +848,7 @@ fn test_large_fetch() { .unwrap(); let doc = bob.storage.repository(rid).unwrap().identity_doc().unwrap(); - let proj = doc.project().unwrap(); + let proj = doc.project().unwrap().unwrap(); assert_eq!(proj.name(), "acme"); } @@ -956,7 +957,7 @@ fn test_concurrent_fetches() { .unwrap() .identity_doc() .unwrap(); - let proj = doc.project().unwrap(); + let proj = doc.project().unwrap().unwrap(); assert!(proj.name().starts_with("bob")); } @@ -967,7 +968,7 @@ fn test_concurrent_fetches() { .unwrap() .identity_doc() .unwrap(); - let proj = doc.project().unwrap(); + let proj = doc.project().unwrap().unwrap(); assert!(proj.name().starts_with("alice")); } @@ -1483,7 +1484,7 @@ fn missing_delegate_default_branch() { // Helper to assert that Bob's default branch is not in storage let assert_bobs_default_is_missing = |repo: &Repository| { let doc = repo.identity_doc().unwrap(); - let project = doc.project().unwrap(); + let project = doc.project().unwrap().unwrap(); let default_branch = repo.reference( &bob_key, &radicle::git::refs::branch(project.default_branch()), @@ -1810,7 +1811,7 @@ fn test_fetch_emits_canonical_ref_update() { let default_branch: git::fmt::Qualified = { let repo = alice.storage.repository(rid).unwrap(); - let proj = repo.project().unwrap(); + let proj = repo.identity_doc().unwrap().project().unwrap().unwrap(); git::fmt::lit::refs_heads(proj.default_branch()).into() }; diff --git a/crates/radicle/src/cob/identity.rs b/crates/radicle/src/cob/identity.rs index eba177224..5656c109e 100644 --- a/crates/radicle/src/cob/identity.rs +++ b/crates/radicle/src/cob/identity.rs @@ -1376,7 +1376,7 @@ mod test { use crate::crypto::{PublicKey, Signer as _, SigningKey}; use crate::identity::Visibility; use crate::identity::did::Did; - use crate::identity::doc::PayloadId; + use crate::identity::doc::{GetPayload as _, PayloadId}; use crate::rad; use crate::storage::ReadStorage as _; use crate::storage::git::Storage; @@ -2590,7 +2590,7 @@ mod test { let repo = storage.repository(id).unwrap(); let mut identity = Identity::load_mut(&repo, &alice).unwrap(); let doc = identity.doc().clone(); - let prj = doc.project().unwrap(); + let prj = doc.project().unwrap().unwrap(); let mut doc = doc.edit(); // Make a change to the description and sign it. @@ -2659,11 +2659,14 @@ mod test { assert_eq!(identity.head(), revision); assert_eq!(identity.doc(), &*doc); assert_eq!( - identity.doc().project().unwrap().description(), + identity.doc().project().unwrap().unwrap().description(), "Acme's repository!?" ); - assert_eq!(doc.project().unwrap().description(), "Acme's repository!?"); + assert_eq!( + doc.project().unwrap().unwrap().description(), + "Acme's repository!?" + ); } #[test] diff --git a/crates/radicle/src/cob/identity/test/property.rs b/crates/radicle/src/cob/identity/test/property.rs index 1d1b4cc31..b7067ff29 100644 --- a/crates/radicle/src/cob/identity/test/property.rs +++ b/crates/radicle/src/cob/identity/test/property.rs @@ -5,7 +5,7 @@ use crate::cob; use crate::cob::identity::{Did, Identity, RedactedBy, RejectedBy, RevisionId, State}; use crate::cob::store::Transaction; use crate::crypto::Signer as _; -use crate::identity::doc::PayloadId; +use crate::identity::doc::{GetPayload as _, PayloadId}; use crate::test::arbitrary::BoundedVec; use crate::test::setup::Network; @@ -431,7 +431,7 @@ impl Harness { } fn update_description(&self, doc: &mut crate::prelude::RawDoc, msg: &str) { - let prj = doc.project().unwrap(); + let prj = doc.project().unwrap().unwrap(); let desc = format!("{} {}", msg, self.revisions.len()); let prj = prj.update(None, desc, None).unwrap(); doc.payload.insert(PayloadId::project(), prj.into()); diff --git a/crates/radicle/src/git.rs b/crates/radicle/src/git.rs index fca283293..45ebcfe4c 100644 --- a/crates/radicle/src/git.rs +++ b/crates/radicle/src/git.rs @@ -296,6 +296,7 @@ pub mod refs { /// /// `refs/namespaces//refs/heads/` /// + #[deprecated(note = "Use `Qualified::with_namespace` instead.")] pub fn branch_of<'a>(remote: &RemoteId, branch: &RefStr) -> Namespaced<'a> { Qualified::from(lit::refs_heads(branch)).with_namespace(remote.into()) } diff --git a/crates/radicle/src/identity/doc.rs b/crates/radicle/src/identity/doc.rs index a6147124b..4d48722b2 100644 --- a/crates/radicle/src/identity/doc.rs +++ b/crates/radicle/src/identity/doc.rs @@ -250,8 +250,6 @@ impl PayloadId { pub enum PayloadError { #[error("json: {0}")] Json(#[from] serde_json::Error), - #[error("payload '{0}' not found in identity document")] - NotFound(PayloadId), } /// A `Payload` is a free-form JSON value that can be associated with an @@ -293,6 +291,26 @@ impl Deref for Payload { /// Trait for all types that may carry payloads. pub trait GetPayload { fn get_payload(&self, id: &PayloadId) -> Option<&Payload>; + + fn load_payload( + &self, + id: &PayloadId, + ) -> Option> { + self.get_payload(id).map(|payload| { + serde_json::from_value(payload.deref().clone()).map_err(PayloadError::Json) + }) + } + + /// Get the [`Project`] by deserializing from the payload. + fn project(&self) -> Option> { + self.load_payload(&PayloadId::project()) + } + + /// Retrieve the [`RawCanonicalRefs`] by deserializing from the payload + /// (if present). + fn raw_canonical_refs(&self) -> Option> { + self.load_payload(&PayloadId::canonical_refs()) + } } impl GetPayload for Doc { @@ -448,17 +466,6 @@ impl RawDoc { &self.version } - /// Get the project payload, if it exists and is valid, out of this document. - pub fn project(&self) -> Result { - let value = self - .payload - .get(&PayloadId::project()) - .ok_or_else(|| PayloadError::NotFound(PayloadId::project()))?; - let proj: Project = serde_json::from_value((**value).clone())?; - - Ok(proj) - } - /// Check if the given `did` is in the set of [`RawDoc::delegates`]. pub fn is_delegate(&self, did: &Did) -> bool { self.delegates.contains(did) @@ -759,17 +766,6 @@ impl Doc { &self.payload } - /// Get the project payload, if it exists and is valid, out of this document. - pub fn project(&self) -> Result { - let value = self - .payload - .get(&PayloadId::project()) - .ok_or_else(|| PayloadError::NotFound(PayloadId::project()))?; - let proj: Project = serde_json::from_value((**value).clone())?; - - Ok(proj) - } - /// Gets the qualified reference name of the default branch, /// according to payloads `xyz.radicle.project` and `xyz.radicle.crefs` /// in this document. @@ -782,6 +778,14 @@ impl Doc { Ok(qualified.to_owned()) } + pub fn default_branch_name(&self) -> Result { + let qualified = self.default_branch()?; + Ok(qualified + .strip_prefix(RefString::try_from("refs/heads").expect("valid refstring")) + .expect("valid branch") + .to_ref_string()) + } + /// Construct the canonical references for this document. /// /// Uses the `xyz.radicle.crefs` payload (if present) and the @@ -805,7 +809,7 @@ impl Doc { /// /// [`RawCanonicalRefs`]: super::crefs::RawCanonicalRefs pub fn canonical_refs(&self) -> Result { - let mut raw_crefs = self.raw_canonical_refs()?.unwrap_or_default(); + let mut raw_crefs = self.raw_canonical_refs().transpose().map_err(CanonicalRefsError::Payload)?.unwrap_or_default(); let resolve = &mut || self.delegates.clone(); // Determine where `HEAD` comes from. The `resolve_head()` result @@ -814,7 +818,7 @@ impl Doc { let head: Option> = raw_crefs.symbolic().resolve_head().cloned(); match (head, self.project()) { - (Some(ref default_branch), Ok(project)) => { + (Some(ref default_branch), Some(Ok(project))) => { let project_branch = project.default_branch_qualified(); if project_branch != *default_branch { return Err(CanonicalRefsError::DefaultBranchRuleError( @@ -826,14 +830,17 @@ impl Doc { } self.validate_head_rule(&raw_crefs, default_branch)?; } - (Some(ref default_branch), Err(_)) => { + (Some(ref default_branch), None) => { self.validate_head_rule(&raw_crefs, default_branch)?; } - (None, Ok(project)) => { + (None, Some(Ok(project))) => { self.synthesize_head(&mut raw_crefs, &project)?; } - (None, Err(err)) => { - return Err(CanonicalRefsError::SynthesisPayloadMissing(err)); + (None, None) => { + return Err(CanonicalRefsError::SynthesisPayloadMissing); + } + (_, Some(Err(err))) => { + return Err(CanonicalRefsError::ProjectPayload(err)); } } @@ -898,6 +905,7 @@ impl Doc { ); } + #[allow(deprecated)] raw_crefs .symbolic_mut() .combine(symbolic::SymbolicRefs::head(project.default_branch())) @@ -1057,22 +1065,19 @@ impl Doc { } } -#[derive(Debug, Error)] -pub enum RawCanonicalRefsError { - #[error(transparent)] - Json(#[from] serde_json::Error), -} - #[derive(Debug, Error)] pub enum CanonicalRefsError { #[error(transparent)] - Raw(#[from] RawCanonicalRefsError), + Payload(PayloadError), #[error(transparent)] CanonicalRefs(#[from] crefs::ValidationError), #[error("could not load `xyz.radicle.project` to get default branch name: {0}")] - SynthesisPayloadMissing(PayloadError), + ProjectPayload(PayloadError), + + #[error("payload `xyz.radicle.project` is missing")] + SynthesisPayloadMissing, #[error(transparent)] DefaultBranchRuleError(#[from] DefaultBranchRuleError), @@ -1103,22 +1108,6 @@ pub enum DefaultBranchRuleError { HeadMismatch { cref: RefString, project: RefString }, } -pub trait GetRawCanonicalRefs: GetPayload { - /// Retrieve the [`RawCanonicalRefs`] by deserializing from the payload - /// (if present). - fn raw_canonical_refs(&self) -> Result, RawCanonicalRefsError> { - let Some(value) = self.get_payload(&PayloadId::canonical_refs()) else { - return Ok(None); - }; - - Ok(Some(serde_json::from_value(value.to_owned().into_inner())?)) - } -} - -impl GetRawCanonicalRefs for Doc {} - -impl GetRawCanonicalRefs for RawDoc {} - #[cfg(test)] #[allow(clippy::unwrap_used)] mod test { diff --git a/crates/radicle/src/identity/doc/update.rs b/crates/radicle/src/identity/doc/update.rs index d04f8b54c..19209860e 100644 --- a/crates/radicle/src/identity/doc/update.rs +++ b/crates/radicle/src/identity/doc/update.rs @@ -5,12 +5,11 @@ use std::{collections::BTreeSet, str::FromStr}; use serde_json as json; use crate::{ - git, prelude::Did, storage::{self, ReadRepository, RepositoryError, refs}, }; -use super::{Doc, PayloadError, PayloadId, RawDoc, Visibility}; +use super::{Doc, GetPayload as _, PayloadError, PayloadId, RawDoc, Visibility}; /// [`EditVisibility`] allows the visibility of a [`RawDoc`] to be edited using /// the [`visibility`] function. @@ -199,9 +198,9 @@ pub fn verify(raw: RawDoc) -> Result { // Verify that the project payload is valid // TODO(finto): perhaps this should be handled by JSON Schemas instead let project = match proposal.project() { - Ok(project) => Some(project), - Err(PayloadError::NotFound(_)) => None, - Err(PayloadError::Json(e)) => { + None => None, + Some(Ok(project)) => Some(project), + Some(Err(PayloadError::Json(e))) => { return Err(error::DocVerification::PayloadError { id: PayloadId::project(), err: e.to_string(), @@ -215,11 +214,9 @@ pub fn verify(raw: RawDoc) -> Result { // (This rule must be synthesized!) // 2. … symbolic reference with the name `HEAD`. // (This reference must be synthesized!) - use super::GetRawCanonicalRefs as _; - match raw.raw_canonical_refs().map(|rcrefs| rcrefs.zip(project)) { + match raw.raw_canonical_refs().transpose().map(|rcrefs| rcrefs.zip(project)) { Ok(Some((crefs, project))) => { - let default = - git::fmt::Qualified::from(git::fmt::lit::refs_heads(project.default_branch())); + let default = project.default_branch_qualified().to_owned(); let matches = crefs .raw_rules() .matches(&default) @@ -284,8 +281,8 @@ fn verify_delegates( mod test { use serde_json::json; + use super::*; use crate::{ - git, identity::doc::{PayloadId, update::error}, prelude::RawDoc, test::arbitrary, @@ -317,9 +314,8 @@ mod test { #[test] fn test_cannot_include_default_branch_rule() { let raw = arbitrary::r#gen::(1); - let branch = git::fmt::Qualified::from(git::fmt::lit::refs_heads( - raw.project().unwrap().default_branch(), - )); + let project = raw.project().unwrap().unwrap(); + let branch = project.default_branch_qualified(); let raw = super::payload( raw, [PayloadUpsert { @@ -350,9 +346,8 @@ mod test { #[test] fn test_default_branch_rule_exists_after_verification() { let raw = arbitrary::r#gen::(1); - let branch = git::fmt::Qualified::from(git::fmt::lit::refs_heads( - raw.project().unwrap().default_branch(), - )); + let project = raw.project().unwrap().unwrap(); + let branch = project.default_branch_qualified(); let raw = super::payload( raw, [PayloadUpsert { diff --git a/crates/radicle/src/identity/project.rs b/crates/radicle/src/identity/project.rs index c530870e0..d652440be 100644 --- a/crates/radicle/src/identity/project.rs +++ b/crates/radicle/src/identity/project.rs @@ -251,6 +251,10 @@ impl Project { &self.description } + /// Return the default branch of the project. + /// + /// To obtain the default branch of the repository, prefer + /// [`super::Doc::default_branch_name`]. #[inline] pub fn default_branch(&self) -> &BranchName { &self.default_branch diff --git a/crates/radicle/src/rad.rs b/crates/radicle/src/rad.rs index 91ca24356..85d7951f5 100644 --- a/crates/radicle/src/rad.rs +++ b/crates/radicle/src/rad.rs @@ -9,7 +9,7 @@ use crate::cob::ObjectId; use crate::git; use crate::git::BranchName; use crate::identity::doc; -use crate::identity::doc::{DocError, RepoId, Visibility}; +use crate::identity::doc::{DocError, GetPayload as _, RepoId, Visibility}; use crate::identity::project::{Project, ProjectName}; use crate::storage::RepositoryError; use crate::storage::git::Repository; @@ -174,16 +174,17 @@ pub fn fork_remote( let me = signer.public_key(); let doc = storage.get(proj)?.ok_or(ForkError::NotFound(proj))?; - let project = doc.project()?; let repository = storage.repository_mut(proj)?; let raw = repository.raw(); - let remote_head = raw.refname_to_id(&git::refs::storage::branch_of( - remote, - project.default_branch(), - ))?; + + #[allow(clippy::unwrap_used)] + let default_branch = doc.default_branch().unwrap(); + + let remote_head = raw.refname_to_id(default_branch.with_namespace(remote.into()).as_str())?; + raw.reference( - &git::refs::storage::branch_of(me, project.default_branch()), + &default_branch.with_namespace(me.into()), remote_head, false, &format!("creating default branch for {me}"), @@ -229,12 +230,12 @@ pub enum CheckoutError { }, #[error("git: {0}")] Git(#[from] git::raw::Error), - #[error("payload: {0}")] - Payload(#[from] doc::PayloadError), #[error("repository `{0}` was not found in storage")] NotFound(RepoId), #[error("repository: {0}")] Repository(#[from] RepositoryError), + #[error(transparent)] + DefaultBranch(#[from] identity::doc::DefaultBranchError), } /// Checkout a project from storage as a working copy. @@ -249,13 +250,13 @@ pub fn checkout, S: storage::ReadStorage>( // TODO: Decide on whether we can use `clone_local` // TODO: Look into sharing object databases. let doc = storage.get(proj)?.ok_or(CheckoutError::NotFound(proj))?; - let project = doc.project()?; let mut opts = git::raw::RepositoryInitOptions::new(); - opts.no_reinit(true) - .external_template(false) - .description(project.description()) - .bare(bare); + opts.no_reinit(true).external_template(false).bare(bare); + + if let Some(Ok(project)) = doc.project() { + opts.description(project.description()); + } let repo = git::raw::Repository::init_opts(path.as_ref(), &opts)?; let url = git::Url::from(proj); @@ -299,26 +300,33 @@ pub fn checkout, S: storage::ReadStorage>( } } - { - // Set up default branch. - let remote_head_ref = - git::refs::workdir::remote_branch(&REMOTE_NAME, project.default_branch()); + match doc.default_branch_name() { + Ok(branch_name) => { + // Set up default branch. + let remote_head_ref = git::refs::workdir::remote_branch(&REMOTE_NAME, &branch_name); - let remote_head_commit = repo.find_reference(&remote_head_ref)?.peel_to_commit()?; - let branch = repo - .branch(project.default_branch(), &remote_head_commit, true)? - .into_reference(); - let branch_ref = branch - .name() - .expect("checkout: default branch name is valid UTF-8"); + let remote_head_commit = repo.find_reference(&remote_head_ref)?.peel_to_commit()?; + let branch = repo + .branch(&branch_name, &remote_head_commit, true)? + .into_reference(); + let branch_ref = branch + .name() + .expect("checkout: default branch name is valid UTF-8"); - repo.set_head(branch_ref)?; - if !bare { - repo.checkout_head(None)?; + repo.set_head(branch_ref)?; + if !bare { + repo.checkout_head(None)?; + } + + // Set up remote tracking for default branch. + git::set_upstream(&repo, &*REMOTE_NAME, &branch_name, branch_ref)?; + } + Err(_) if bare => { + // Ignore. + } + Err(err) => { + return Err(CheckoutError::DefaultBranch(err)); } - - // Set up remote tracking for default branch. - git::set_upstream(&repo, &*REMOTE_NAME, project.default_branch(), branch_ref)?; } Ok(repo) @@ -530,7 +538,7 @@ mod tests { .unwrap(); let doc = storage.get(proj).unwrap().unwrap(); - let project = doc.project().unwrap(); + let project = doc.project().unwrap().unwrap(); let remotes: HashMap<_, _> = storage .repository(proj) .unwrap() diff --git a/crates/radicle/src/storage.rs b/crates/radicle/src/storage.rs index a9620ff81..aee6b110d 100644 --- a/crates/radicle/src/storage.rs +++ b/crates/radicle/src/storage.rs @@ -65,7 +65,7 @@ pub struct RepositoryInfo { /// Repository identifier. pub rid: RepoId, /// Head of default branch. - pub head: Oid, + pub head: Option, /// Identity document. pub doc: Doc, /// Information about local signed references. @@ -521,7 +521,8 @@ pub trait ReadRepository: Sized + ValidateRepository { fn head(&self) -> Result<(Qualified<'_>, Oid), RepositoryError>; /// Gets the qualified reference name of the default branch of self, - /// according to the project payload in the identity document. + /// according to the identity document. + #[deprecated] fn default_branch(&self) -> Result, RepositoryError> { Ok(self.identity_doc()?.default_branch()?.to_owned()) } diff --git a/crates/radicle/src/storage/git.rs b/crates/radicle/src/storage/git.rs index ca6678eed..51503bc8e 100644 --- a/crates/radicle/src/storage/git.rs +++ b/crates/radicle/src/storage/git.rs @@ -13,7 +13,7 @@ use std::{fs, io}; use crate::git::canonical::Quorum; use crate::git::raw::ErrorExt as _; -use crate::identity::doc::DocError; +use crate::identity::doc::{DocError, GetPayload as _}; use crate::identity::{Doc, DocAt, RepoId}; use crate::identity::{Identity, Project}; use crate::storage::refs::{FeatureLevel, Refs, SignedRefs}; @@ -159,10 +159,10 @@ impl ReadStorage for Storage { // For performance reasons, we don't do a full repository check here. let head = match repo.head() { - Ok((_, head)) => head, + Ok((_, head)) => Some(head), Err(e) => { - log::warn!(target: "storage", "Repository {rid} is invalid: looking up head: {e}"); - continue; + log::debug!(target: "storage", "Repository {rid} is invalid: looking up head: {e}"); + None } }; // Nb. This will be `None` if they were not found. @@ -256,7 +256,7 @@ impl Storage { { rids.map(|rid| { let repo = self.repository(*rid)?; - let (_, head) = repo.head()?; + let head = repo.head().ok().map(|(_, head)| head); let refs = SignedRefsInfo::new(refs::SignedRefs::load(self.info.key, &repo)) .map_err(|err| Error::Refs(refs::Error::Read(err)))?; @@ -570,12 +570,14 @@ impl Repository { } /// Get the canonical project information. - pub fn project(&self) -> Result { - let head = self.identity_head()?; - let doc = self.identity_doc_at(head)?; - let proj = doc.project()?; - - Ok(proj) + #[deprecated(note = "Use `Doc::project()` on `Self::identity_doc()`.")] + pub fn project(&self) -> Result, RepositoryError> { + self.identity_doc().and_then(|identity| { + identity + .project() + .transpose() + .map_err(RepositoryError::Payload) + }) } pub fn identity_doc_of(&self, remote: &RemoteId) -> Result { diff --git a/crates/radicle/src/storage/refs.rs b/crates/radicle/src/storage/refs.rs index 1f4b0a156..d9c25895a 100644 --- a/crates/radicle/src/storage/refs.rs +++ b/crates/radicle/src/storage/refs.rs @@ -675,7 +675,8 @@ mod tests { london .raw() .reference( - git::refs::storage::branch_of(bob.public_key(), &git::fmt::refname!("master")) + git::fmt::Qualified::from(git::fmt::lit::refs_heads(&git::fmt::refname!("master"))) + .with_namespace(bob.public_key().into()) .as_str(), bob_head, false, diff --git a/crates/radicle/src/test/storage.rs b/crates/radicle/src/test/storage.rs index b3d5778e5..b4d5fb4cc 100644 --- a/crates/radicle/src/test/storage.rs +++ b/crates/radicle/src/test/storage.rs @@ -100,7 +100,7 @@ impl ReadStorage for MockStorage { .iter() .map(|(rid, r)| RepositoryInfo { rid: *rid, - head: r.head().unwrap().1, + head: Some(r.head().unwrap().1), doc: r.doc.clone().into(), refs: SignedRefsInfo::None, synced_at: None,