From 3e52ecb609f8424cffb2e6398c599aa78224825a Mon Sep 17 00:00:00 2001 From: DanConwayDev Date: Tue, 12 Dec 2023 00:00:00 +0000 Subject: feat(claim) create yaml add maintainers and relays - create yaml file with maintainers and relays - add maintainers to repo event - add current user as maintainer - custom repo relays from cli argument - save git-server in repo event --- src/git.rs | 33 +++++++- src/repo_ref.rs | 184 ++++++++++++++++++++++++++++++++++++----- src/sub_commands/claim.rs | 52 ++++++++++-- src/sub_commands/prs/create.rs | 2 +- src/sub_commands/prs/list.rs | 1 + src/sub_commands/pull.rs | 1 + src/sub_commands/push.rs | 1 + 7 files changed, 247 insertions(+), 27 deletions(-) (limited to 'src') diff --git a/src/git.rs b/src/git.rs index e2d8196..29670eb 100644 --- a/src/git.rs +++ b/src/git.rs @@ -1,6 +1,6 @@ -use std::env::current_dir; #[cfg(test)] use std::path::PathBuf; +use std::{env::current_dir, path::Path}; use anyhow::{bail, Context, Result}; use git2::{Oid, Revwalk}; @@ -30,6 +30,8 @@ impl Repo { // pub type Sha1 = [u8; 20]; pub trait RepoActions { + fn get_path(&self) -> Result<&Path>; + fn get_origin_url(&self) -> Result; fn get_local_branch_names(&self) -> Result>; fn get_main_or_master_branch(&self) -> Result<(&str, Sha1Hash)>; fn get_checked_out_branch_name(&self) -> Result; @@ -61,6 +63,23 @@ pub trait RepoActions { } impl RepoActions for Repo { + fn get_path(&self) -> Result<&Path> { + self.git_repo + .path() + .parent() + .context("cannot find repositiory path as .git has no parent") + } + + fn get_origin_url(&self) -> Result { + Ok(self + .git_repo + .find_remote("origin") + .context("cannot find origin")? + .url() + .context("cannot find origin url")? + .to_string()) + } + fn get_main_or_master_branch(&self) -> Result<(&str, Sha1Hash)> { let main_branch_name = { let local_branches = self @@ -860,6 +879,18 @@ mod tests { } } + mod get_origin_url { + use super::*; + + #[test] + fn returns_origin_url() -> Result<()> { + let test_repo = GitTestRepo::default(); + test_repo.add_remote("origin", "https://localhost:1000")?; + let git_repo = Repo::from_path(&test_repo.dir)?; + assert_eq!(git_repo.get_origin_url()?, "https://localhost:1000"); + Ok(()) + } + } mod get_checked_out_branch_name { use super::*; diff --git a/src/repo_ref.rs b/src/repo_ref.rs index a92b5b3..a5b35c9 100644 --- a/src/repo_ref.rs +++ b/src/repo_ref.rs @@ -1,20 +1,26 @@ +use std::{fs::File, io::BufReader, str::FromStr}; + use anyhow::{bail, Context, Result}; -use nostr::Tag; +use nostr::{secp256k1::XOnlyPublicKey, FromBech32, Tag, ToBech32}; +use serde::{Deserialize, Serialize}; #[cfg(not(test))] use crate::client::Client; -use crate::client::Connect; #[cfg(test)] use crate::client::MockConnect; +use crate::{ + client::Connect, + git::{Repo, RepoActions}, +}; #[derive(Default)] pub struct RepoRef { pub name: String, pub description: String, pub root_commit: String, + pub git_server: String, pub relays: Vec, - // git_server: String, - // other maintainers + pub maintainers: Vec, // code languages and hashtags } @@ -35,6 +41,10 @@ impl TryFrom for RepoRef { r.description = t.as_vec()[1].clone(); } + if let Some(t) = event.tags.iter().find(|t| t.as_vec()[0].eq("git-server")) { + r.git_server = t.as_vec()[1].clone(); + } + if let Some(t) = event.tags.iter().find(|t| t.as_vec()[0].eq("d")) { r.root_commit = t.as_vec()[1].clone(); } @@ -46,6 +56,15 @@ impl TryFrom for RepoRef { .map(|t| t.as_vec()[1].clone()) .collect(); + for tag in event.tags.iter().filter(|t| t.as_vec()[0].eq("p")) { + let pk = tag.as_vec()[1].clone(); + r.maintainers.push( + nostr_sdk::prelude::XOnlyPublicKey::from_str(&pk) + .context(format!("cannot convert {pk} into a valid nostr public key")) + .context("invalid repository event")?, + ); + } + Ok(r) } } @@ -62,10 +81,17 @@ impl RepoRef { Tag::Reference(format!("r-{}", self.root_commit)), Tag::Name(self.name.clone()), Tag::Description(self.description.clone()), + Tag::Generic( + nostr::TagKind::Custom("git-server".to_string()), + vec![self.git_server.clone()], + ), + Tag::Reference(self.git_server.clone()), ], self.relays.iter().map(|r| Tag::Relay(r.into())).collect(), - // git_servers - // other maintainers + self.maintainers + .iter() + .map(|pk| Tag::PubKey(*pk, None)) + .collect(), // code languages and hashtags ] .concat(), @@ -76,24 +102,30 @@ impl RepoRef { } pub async fn fetch( + git_repo: &Repo, root_commit: String, #[cfg(test)] client: &MockConnect, #[cfg(not(test))] client: &Client, // TODO: more rubust way of finding repo events - relays: Vec, + fallback_relays: Vec, ) -> Result { - // TODO: fetch relay information from file + let repo_config = get_repo_config_from_yaml(git_repo); - let events: Vec = client - .get_events( - relays, - vec![ - nostr::Filter::default() - .kind(nostr::Kind::Custom(REPO_REF_KIND)) - .identifier(root_commit), - ], - ) - .await?; + // TODO: check events only from maintainers. get relay list of maintainters. + // check those relays. + + let mut repo_event_filter = nostr::Filter::default() + .kind(nostr::Kind::Custom(REPO_REF_KIND)) + .identifier(root_commit); + + let mut relays = fallback_relays; + if let Ok(repo_config) = repo_config { + repo_event_filter = + repo_event_filter.pubkeys(extract_pks(repo_config.maintainers.clone())?); + relays = repo_config.relays.clone(); + } + + let events: Vec = client.get_events(relays, vec![repo_event_filter]).await?; RepoRef::try_from( events @@ -105,6 +137,68 @@ pub async fn fetch( ) } +#[derive(Serialize, Deserialize, Default, Clone, Debug, PartialEq, Eq)] +pub struct RepoConfigYaml { + pub maintainers: Vec, + pub relays: Vec, +} + +pub fn get_repo_config_from_yaml(git_repo: &Repo) -> Result { + let path = git_repo.get_path()?.join("maintainers.yaml"); + let file = File::open(path) + .context("should open maintainers.yaml if it exists") + .context("maintainers.yaml doesnt exist")?; + let reader = BufReader::new(file); + let repo_config_yaml: RepoConfigYaml = serde_yaml::from_reader(reader) + .context("should read maintainers.yaml with serde_yaml") + .context("maintainers.yaml incorrectly formatted")?; + Ok(repo_config_yaml) +} + +pub fn extract_pks(pk_strings: Vec) -> Result> { + let mut pks: Vec = vec![]; + for s in pk_strings { + pks.push( + nostr_sdk::prelude::XOnlyPublicKey::from_bech32(s.clone()) + .context(format!("cannot convert {s} into a valid nostr public key"))?, + ); + } + Ok(pks) +} + +pub fn save_repo_config_to_yaml( + git_repo: &Repo, + maintainers: Vec, + relays: Vec, +) -> Result<()> { + let path = git_repo.get_path()?.join("maintainers.yaml"); + let file = if path.exists() { + std::fs::OpenOptions::new() + .create(true) + .write(true) + .truncate(true) + .open(path) + .context("cannot open maintainers.yaml file with write and truncate options")? + } else { + std::fs::File::create(path).context("cannot create maintainers.yaml file")? + }; + let mut maintainers_npubs = vec![]; + for m in maintainers { + maintainers_npubs.push( + m.to_bech32() + .context("cannot convert public key into npub")?, + ); + } + serde_yaml::to_writer( + file, + &RepoConfigYaml { + maintainers: maintainers_npubs, + relays, + }, + ) + .context("cannot write maintainers to maintainers.yaml file serde_yaml") +} + #[cfg(test)] mod tests { use test_utils::*; @@ -116,7 +210,9 @@ mod tests { name: "test name".to_string(), description: "test description".to_string(), root_commit: "23471389461".to_string(), + git_server: "https://localhost:1000".to_string(), relays: vec!["ws://relay1.io".to_string(), "ws://relay2.io".to_string()], + maintainers: vec![TEST_KEY_1_KEYS.public_key(), TEST_KEY_2_KEYS.public_key()], } .to_event(&TEST_KEY_1_KEYS) .unwrap() @@ -145,6 +241,14 @@ mod tests { ) } + #[test] + fn git_server() { + assert_eq!( + RepoRef::try_from(create()).unwrap().git_server, + "https://localhost:1000", + ) + } + #[test] fn relays() { assert_eq!( @@ -152,6 +256,14 @@ mod tests { vec!["ws://relay1.io".to_string(), "ws://relay2.io".to_string()], ) } + + #[test] + fn maintainers() { + assert_eq!( + RepoRef::try_from(create()).unwrap().maintainers, + vec![TEST_KEY_1_KEYS.public_key(), TEST_KEY_2_KEYS.public_key()], + ) + } } mod to_event { @@ -185,6 +297,21 @@ mod tests { ) } + #[test] + fn git_server() { + assert!(create().tags.iter().any(|t| t.as_vec()[0].eq("git-server") + && t.as_vec()[1].eq("https://localhost:1000"))) + } + + #[test] + fn git_server_as_reference() { + assert!( + create().tags.iter().any( + |t| t.as_vec()[0].eq("r") && t.as_vec()[1].eq("https://localhost:1000") + ) + ) + } + #[test] fn root_commit_as_reference() { assert!( @@ -208,9 +335,28 @@ mod tests { assert_eq!(relay_tags[1].as_vec()[1], "ws://relay2.io"); } + #[test] + fn maintainers() { + let event = create(); + let p_tags = event + .tags + .iter() + .filter(|t| t.as_vec()[0].eq("p")) + .collect::>(); + assert_eq!(p_tags[0].as_vec().len(), 2); + assert_eq!( + p_tags[0].as_vec()[1], + TEST_KEY_1_KEYS.public_key().to_string() + ); + assert_eq!( + p_tags[1].as_vec()[1], + TEST_KEY_2_KEYS.public_key().to_string() + ); + } + #[test] fn no_other_tags() { - assert_eq!(create().tags.len(), 6) + assert_eq!(create().tags.len(), 10) } } } diff --git a/src/sub_commands/claim.rs b/src/sub_commands/claim.rs index c0d26dd..2573267 100644 --- a/src/sub_commands/claim.rs +++ b/src/sub_commands/claim.rs @@ -10,7 +10,7 @@ use crate::{ client::Connect, git::{Repo, RepoActions}, login, - repo_ref::RepoRef, + repo_ref::{extract_pks, get_repo_config_from_yaml, save_repo_config_to_yaml, RepoRef}, Cli, }; @@ -22,6 +22,9 @@ pub struct SubCommandArgs { #[clap(short, long)] /// optional description description: Option, + #[clap(short, long, value_parser, num_args = 1..)] + /// relays contributors push patches and comments to + relays: Vec, } pub async fn launch(cli_args: &Cli, args: &SubCommandArgs) -> Result<()> { @@ -37,6 +40,8 @@ pub async fn launch(cli_args: &Cli, args: &SubCommandArgs) -> Result<()> { // TODO: check for empty repo // TODO: check for existing maintaiers file + + let repo_config_result = get_repo_config_from_yaml(&git_repo); // TODO: check for other claims let name = match &args.title { @@ -50,6 +55,8 @@ pub async fn launch(cli_args: &Cli, args: &SubCommandArgs) -> Result<()> { .input(PromptInputParms::default().with_prompt("description (Optional)"))?, }; + let git_server = git_repo.get_origin_url()?; + #[cfg(not(test))] let mut client = Client::default(); #[cfg(test)] @@ -59,11 +66,41 @@ pub async fn launch(cli_args: &Cli, args: &SubCommandArgs) -> Result<()> { client.set_keys(&keys).await; - // TODO: choice input defaulting to user relay list filtered by non paid relays - let repo_relays: Vec = vec![ - "ws://localhost:8055".to_string(), - "ws://localhost:8056".to_string(), - ]; + let mut maintainers = vec![keys.public_key()]; + + let repo_relays: Vec = if !args.relays.is_empty() { + args.relays.clone() + } else if let Ok(config) = &repo_config_result { + config.relays.clone() + } else { + // TODO: choice input defaulting to user relay list filtered by non paid relays + // TODO: allow manual input for more relays + // TODO: reccommend some free relays + user_ref.relays.write() + }; + + if let Ok(config) = &repo_config_result { + maintainers = extract_pks(config.maintainers.clone())?; + } + + // if yaml file doesnt exist or needs updating + if match &repo_config_result { + Ok(config) => { + !(extract_pks(config.maintainers.clone())?.eq(&maintainers) + && config.relays.eq(&repo_relays)) + } + Err(_) => true, + } { + save_repo_config_to_yaml(&git_repo, maintainers.clone(), repo_relays.clone())?; + println!( + "maintainers.yaml {}. commit and push.", + if repo_config_result.is_err() { + "created" + } else { + "updated" + } + ); + } println!("publishing repostory reference..."); @@ -71,10 +108,13 @@ pub async fn launch(cli_args: &Cli, args: &SubCommandArgs) -> Result<()> { name, description, root_commit: root_commit.to_string(), + git_server, relays: repo_relays.clone(), + maintainers, } .to_event(&keys)?; + // TODO: send repo event to blaster send_events( &client, vec![repo_event], diff --git a/src/sub_commands/prs/create.rs b/src/sub_commands/prs/create.rs index 5c4e578..5e41a56 100644 --- a/src/sub_commands/prs/create.rs +++ b/src/sub_commands/prs/create.rs @@ -100,12 +100,12 @@ pub async fn launch( generate_pr_and_patch_events(&title, &description, &to_branch, &git_repo, &ahead, &keys)?; let repo_ref = repo_ref::fetch( + &git_repo, git_repo .get_root_commit(&to_branch) .context("failed to get root commit of the repository")? .to_string(), &client, - // TODO: get relay list from local yaml file user_ref.relays.write(), ) .await?; diff --git a/src/sub_commands/prs/list.rs b/src/sub_commands/prs/list.rs index 13f29fd..a6aa8b7 100644 --- a/src/sub_commands/prs/list.rs +++ b/src/sub_commands/prs/list.rs @@ -45,6 +45,7 @@ pub async fn launch( let client = ::default(); let repo_ref = repo_ref::fetch( + &git_repo, root_commit.to_string(), &client, client.get_more_fallback_relays().clone(), diff --git a/src/sub_commands/pull.rs b/src/sub_commands/pull.rs index a6513e8..a656e09 100644 --- a/src/sub_commands/pull.rs +++ b/src/sub_commands/pull.rs @@ -38,6 +38,7 @@ pub async fn launch() -> Result<()> { let client = ::default(); let repo_ref = repo_ref::fetch( + &git_repo, root_commit.to_string(), &client, client.get_more_fallback_relays().clone(), diff --git a/src/sub_commands/push.rs b/src/sub_commands/push.rs index 968aa0a..7c64bb2 100644 --- a/src/sub_commands/push.rs +++ b/src/sub_commands/push.rs @@ -41,6 +41,7 @@ pub async fn launch(cli_args: &Cli) -> Result<()> { let mut client = ::default(); let repo_ref = repo_ref::fetch( + &git_repo, root_commit.to_string(), &client, client.get_more_fallback_relays().clone(), -- cgit v1.2.3