From 0753e0bcdd3d606f8f0226a3980bcd817117abaa Mon Sep 17 00:00:00 2001 From: DanConwayDev Date: Wed, 1 Nov 2023 00:00:00 +0000 Subject: feat(claim) create basic event replacable event with root-commit, name, description and relay tags --- src/main.rs | 7 +- src/sub_commands/claim.rs | 114 ++++++++++++++ src/sub_commands/mod.rs | 1 + src/sub_commands/prs/create.rs | 12 +- tests/claim.rs | 331 +++++++++++++++++++++++++++++++++++++++++ 5 files changed, 458 insertions(+), 7 deletions(-) create mode 100644 src/sub_commands/claim.rs create mode 100644 tests/claim.rs diff --git a/src/main.rs b/src/main.rs index 68b0ed6..54ad748 100644 --- a/src/main.rs +++ b/src/main.rs @@ -33,7 +33,9 @@ pub struct Cli { enum Commands { /// save encrypted nsec for future use Login(sub_commands::login::SubCommandArgs), - /// create and issue Prs + /// issue repository reference event as a maintainers + Claim(sub_commands::claim::SubCommandArgs), + /// create and issue prs Prs(sub_commands::prs::SubCommandArgs), } @@ -44,6 +46,9 @@ async fn main() -> Result<()> { Commands::Login(args) => { futures::executor::block_on(sub_commands::login::launch(&cli, args)) } + Commands::Claim(args) => { + futures::executor::block_on(sub_commands::claim::launch(&cli, args)) + } Commands::Prs(args) => futures::executor::block_on(sub_commands::prs::launch(&cli, args)), } } diff --git a/src/sub_commands/claim.rs b/src/sub_commands/claim.rs new file mode 100644 index 0000000..5eb66bb --- /dev/null +++ b/src/sub_commands/claim.rs @@ -0,0 +1,114 @@ +use anyhow::{Context, Result}; +use nostr::{EventBuilder, Tag}; + +use super::prs::create::send_events; +#[cfg(not(test))] +use crate::client::Client; +#[cfg(test)] +use crate::client::MockConnect; +use crate::{ + cli_interactor::{Interactor, InteractorPrompt, PromptInputParms}, + client::Connect, + git::{Repo, RepoActions}, + login, Cli, +}; + +#[derive(Debug, clap::Args)] +pub struct SubCommandArgs { + #[clap(short, long)] + /// name of repository + title: Option, + #[clap(short, long)] + /// optional description + description: Option, +} + +pub async fn launch(cli_args: &Cli, args: &SubCommandArgs) -> Result<()> { + let git_repo = Repo::discover().context("cannot find a git repository")?; + + let (main_or_master_branch_name, _) = git_repo + .get_main_or_master_branch() + .context("no main or master branch")?; + + let root_commit = git_repo + .get_root_commit(main_or_master_branch_name) + .context("failed to get root commit of the repository")?; + + // TODO: check for empty repo + // TODO: check for existing maintaiers file + // TODO: check for other claims + + let name = match &args.title { + Some(t) => t.clone(), + None => Interactor::default().input(PromptInputParms::default().with_prompt("name"))?, + }; + + let description = match &args.description { + Some(t) => t.clone(), + None => Interactor::default() + .input(PromptInputParms::default().with_prompt("description (Optional)"))?, + }; + + #[cfg(not(test))] + let mut client = Client::default(); + #[cfg(test)] + let mut client = ::default(); + + let (keys, user_ref) = login::launch(&cli_args.nsec, &cli_args.password, Some(&client)).await?; + + 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(), + ]; + + println!("publishing repostory reference..."); + + send_events( + &client, + vec![generate_repo_event( + &name, + &description, + &repo_relays, + &root_commit.to_string(), + &keys, + )?], + user_ref.relays.write(), + repo_relays, + !cli_args.disable_cli_spinners, + ) + .await?; + + Ok(()) +} + +fn generate_repo_event( + name: &str, + description: &str, + relays: &[String], + // git_server: String, + root_commit: &String, + keys: &nostr::Keys, +) -> Result { + EventBuilder::new( + nostr::event::Kind::Custom(30017), + "", + &[ + vec![ + Tag::Identifier(root_commit.to_string()), + Tag::Reference(format!("r-{root_commit}")), + Tag::Name(name.to_owned()), + Tag::Description(description.to_owned()), + ], + relays.iter().map(|r| Tag::Relay(r.into())).collect(), + // git_servers + // other maintainers + // code languages and hashtags + ] + .concat(), + ) + .to_event(keys) + .context("failed to create pr event") +} diff --git a/src/sub_commands/mod.rs b/src/sub_commands/mod.rs index 3c3da1d..6e99ca5 100644 --- a/src/sub_commands/mod.rs +++ b/src/sub_commands/mod.rs @@ -1,2 +1,3 @@ +pub mod claim; pub mod login; pub mod prs; diff --git a/src/sub_commands/prs/create.rs b/src/sub_commands/prs/create.rs index aad80f4..d82f53e 100644 --- a/src/sub_commands/prs/create.rs +++ b/src/sub_commands/prs/create.rs @@ -105,6 +105,11 @@ pub async fn launch( "ws://localhost:8056".to_string(), ]; + println!( + "posting 1 pull request with {} commits...", + events.len() - 1 + ); + send_events( &client, events, @@ -118,7 +123,7 @@ pub async fn launch( Ok(()) } -async fn send_events( +pub async fn send_events( #[cfg(test)] client: &crate::client::MockConnect, #[cfg(not(test))] client: &Client, events: Vec, @@ -128,11 +133,6 @@ async fn send_events( ) -> Result<()> { let (_, _, _, all) = unique_and_duplicate_all(&my_write_relays, &repo_read_relays); - println!( - "posting 1 pull request with {} commits...", - events.len() - 1 - ); - let m = MultiProgress::new(); let pb_style = ProgressStyle::with_template(if animate { " {spinner} {prefix} {bar} {pos}/{len} {msg}" diff --git a/tests/claim.rs b/tests/claim.rs new file mode 100644 index 0000000..ec62c0b --- /dev/null +++ b/tests/claim.rs @@ -0,0 +1,331 @@ +use anyhow::Result; +use serial_test::serial; +use test_utils::{git::GitTestRepo, *}; + +#[test] +fn when_no_main_or_master_branch_return_error() -> Result<()> { + let test_repo = GitTestRepo::new("notmain")?; + test_repo.populate()?; + let mut p = CliTester::new_from_dir(&test_repo.dir, ["claim"]); + p.expect("Error: no main or master branch")?; + Ok(()) +} + +mod sends_repoistory_to_relays { + use futures::join; + use test_utils::relay::Relay; + + use super::*; + + static REPOSITORY_KIND: u64 = 30017; + + fn prep_git_repo() -> Result { + let test_repo = GitTestRepo::default(); + test_repo.populate()?; + Ok(test_repo) + } + + fn cli_tester_claim(git_repo: &GitTestRepo) -> CliTester { + CliTester::new_from_dir( + &git_repo.dir, + [ + "--nsec", + TEST_KEY_1_NSEC, + "--password", + TEST_PASSWORD, + "--disable-cli-spinners", + "claim", + "--title", + "example-name", + "--description", + "example-description", + ], + ) + } + + fn expect_msgs_first(p: &mut CliTester) -> Result<()> { + p.expect("searching for your details...\r\n")?; + p.expect("\r")?; + p.expect("logged in as fred\r\n")?; + // // p.expect("searching for existing claims on repository...\r\n")?; + p.expect("publishing repostory reference...\r\n")?; + Ok(()) + } + + async fn prep_run_claim() -> Result<( + Relay<'static>, + Relay<'static>, + Relay<'static>, + Relay<'static>, + Relay<'static>, + )> { + let git_repo = prep_git_repo()?; + // fallback (51,52) user write (53, 55) repo (55, 56) + let (mut r51, mut r52, mut r53, mut r55, mut r56) = ( + Relay::new( + 8051, + None, + Some(&|relay, client_id, subscription_id, _| -> Result<()> { + relay.respond_events( + client_id, + &subscription_id, + &vec![ + generate_test_key_1_metadata_event("fred"), + generate_test_key_1_relay_list_event(), + ], + )?; + Ok(()) + }), + ), + Relay::new(8052, None, None), + Relay::new(8053, None, None), + Relay::new(8055, None, None), + Relay::new(8056, None, None), + ); + + // // check relay had the right number of events + let cli_tester_handle = std::thread::spawn(move || -> Result<()> { + let mut p = cli_tester_claim(&git_repo); + p.expect_end_eventually()?; + for p in [51, 52, 53, 55, 56] { + relay::shutdown_relay(8000 + p)?; + } + Ok(()) + }); + + // launch relay + let _ = join!( + r51.listen_until_close(), + r52.listen_until_close(), + r53.listen_until_close(), + r55.listen_until_close(), + r56.listen_until_close(), + ); + cli_tester_handle.join().unwrap()?; + Ok((r51, r52, r53, r55, r56)) + } + + mod sent_to_correct_relays { + use super::*; + + #[test] + #[serial] + fn only_1_repository_kind_event_sent_to_user_relays() -> Result<()> { + let (_, _, r53, r55, _) = futures::executor::block_on(prep_run_claim())?; + for relay in [&r53, &r55] { + assert_eq!( + relay + .events + .iter() + .filter(|e| e.kind.as_u64().eq(&REPOSITORY_KIND)) + .count(), + 1, + ); + } + Ok(()) + } + + #[test] + #[serial] + fn only_1_repository_kind_event_sent_to_repo_relays() -> Result<()> { + let (_, _, _, r55, r56) = futures::executor::block_on(prep_run_claim())?; + for relay in [&r55, &r56] { + assert_eq!( + relay + .events + .iter() + .filter(|e| e.kind.as_u64().eq(&REPOSITORY_KIND)) + .count(), + 1, + ); + } + Ok(()) + } + + #[test] + #[serial] + fn event_not_sent_to_fallback_relay() -> Result<()> { + let (r51, r52, _, _, _) = futures::executor::block_on(prep_run_claim())?; + for relay in [&r51, &r52] { + assert_eq!( + relay + .events + .iter() + .filter(|e| e.kind.as_u64().eq(&REPOSITORY_KIND)) + .count(), + 0, + ); + } + Ok(()) + } + } + + mod tags { + use super::*; + + #[test] + #[serial] + fn d_replaceable_event_identifier() -> Result<()> { + let (_, _, r53, r55, r56) = futures::executor::block_on(prep_run_claim())?; + for relay in [&r53, &r55, &r56] { + let event: &nostr::Event = relay + .events + .iter() + .find(|e| e.kind.as_u64().eq(&REPOSITORY_KIND)) + .unwrap(); + + assert!(event.tags.iter().any(|t| t.as_vec()[0].eq("d") + && t.as_vec()[1].eq("9ee507fc4357d7ee16a5d8901bedcd103f23c17d"))); + } + Ok(()) + } + + #[test] + #[serial] + fn root_commit() -> Result<()> { + let (_, _, r53, r55, r56) = futures::executor::block_on(prep_run_claim())?; + for relay in [&r53, &r55, &r56] { + let event: &nostr::Event = relay + .events + .iter() + .find(|e| e.kind.as_u64().eq(&REPOSITORY_KIND)) + .unwrap(); + + // root commit 'r' tag with 'r-' prefix + assert!(event.tags.iter().any(|t| t.as_vec()[0].eq("r") + && t.as_vec()[1].eq("r-9ee507fc4357d7ee16a5d8901bedcd103f23c17d"))); + } + Ok(()) + } + + #[test] + #[serial] + fn name() -> Result<()> { + let (_, _, r53, r55, r56) = futures::executor::block_on(prep_run_claim())?; + for relay in [&r53, &r55, &r56] { + let event: &nostr::Event = relay + .events + .iter() + .find(|e| e.kind.as_u64().eq(&REPOSITORY_KIND)) + .unwrap(); + + assert!( + event + .tags + .iter() + .any(|t| t.as_vec()[0].eq("name") && t.as_vec()[1].eq("example-name")) + ); + } + Ok(()) + } + + #[test] + #[serial] + fn description() -> Result<()> { + let (_, _, r53, r55, r56) = futures::executor::block_on(prep_run_claim())?; + for relay in [&r53, &r55, &r56] { + let event: &nostr::Event = relay + .events + .iter() + .find(|e| e.kind.as_u64().eq(&REPOSITORY_KIND)) + .unwrap(); + + assert!( + event.tags.iter().any(|t| t.as_vec()[0].eq("description") + && t.as_vec()[1].eq("example-description")) + ); + } + Ok(()) + } + + #[test] + #[serial] + fn relays() -> Result<()> { + let (_, _, r53, r55, r56) = futures::executor::block_on(prep_run_claim())?; + for relay in [&r53, &r55, &r56] { + let event: &nostr::Event = relay + .events + .iter() + .find(|e| e.kind.as_u64().eq(&REPOSITORY_KIND)) + .unwrap(); + + let relay_tags = event + .tags + .iter() + .filter(|t| t.as_vec()[0].eq("relay")) + .collect::>(); + assert_eq!(relay_tags[0].as_vec()[1], "ws://localhost:8055"); + assert_eq!(relay_tags[1].as_vec()[1], "ws://localhost:8056"); + } + Ok(()) + } + } + + mod cli_ouput { + use super::*; + + async fn run_test_async() -> Result<()> { + let git_repo = prep_git_repo()?; + + let (mut r51, mut r52, mut r53, mut r55, mut r56) = ( + Relay::new( + 8051, + None, + Some(&|relay, client_id, subscription_id, _| -> Result<()> { + relay.respond_events( + client_id, + &subscription_id, + &vec![ + generate_test_key_1_metadata_event("fred"), + generate_test_key_1_relay_list_event(), + ], + )?; + Ok(()) + }), + ), + Relay::new(8052, None, None), + Relay::new(8053, None, None), + Relay::new(8055, None, None), + Relay::new(8056, None, None), + ); + + // // check relay had the right number of events + let cli_tester_handle = std::thread::spawn(move || -> Result<()> { + let mut p = cli_tester_claim(&git_repo); + expect_msgs_first(&mut p)?; + relay::expect_send_with_progress( + &mut p, + vec![ + (" [my-relay] [repo-relay] ws://localhost:8055", true, ""), + (" [my-relay] ws://localhost:8053", true, ""), + (" [repo-relay] ws://localhost:8056", true, ""), + ], + 1, + )?; + p.expect_end_with_whitespace()?; + for p in [51, 52, 53, 55, 56] { + relay::shutdown_relay(8000 + p)?; + } + Ok(()) + }); + + // launch relay + let _ = join!( + r51.listen_until_close(), + r52.listen_until_close(), + r53.listen_until_close(), + r55.listen_until_close(), + r56.listen_until_close(), + ); + cli_tester_handle.join().unwrap()?; + Ok(()) + } + + #[test] + #[serial] + fn check_cli_output() -> Result<()> { + futures::executor::block_on(run_test_async())?; + Ok(()) + } + } +} -- cgit v1.2.3