From 6d3c9218d2d3320f5d7fb9b9ede8750e947b70e8 Mon Sep 17 00:00:00 2001 From: DanConwayDev Date: Fri, 8 Dec 2023 20:15:43 +0000 Subject: feat(push) push commits to existing pr - find pr with a branch-name that matches checked out branch - check branch isnt behind latest patch on pr - push new commits a patches associated with pr --- src/git.rs | 6 + src/main.rs | 3 + src/sub_commands/mod.rs | 1 + src/sub_commands/push.rs | 182 ++++++++++++++++++ tests/push.rs | 477 +++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 669 insertions(+) create mode 100644 src/sub_commands/push.rs create mode 100644 tests/push.rs diff --git a/src/git.rs b/src/git.rs index f4f73a5..e2d8196 100644 --- a/src/git.rs +++ b/src/git.rs @@ -384,6 +384,12 @@ fn sha1_to_oid(hash: &Sha1Hash) -> Result { Oid::from_bytes(hash.as_byte_array()).context("Sha1Hash bytes failed to produce a valid Oid") } +pub fn str_to_sha1(s: &str) -> Result { + Ok(oid_to_sha1( + &Oid::from_str(s).context("string is not a sha1 hash")?, + )) +} + fn git_sig_to_tag_vec(sig: &git2::Signature) -> Vec { vec![ sig.name().unwrap_or("").to_string(), diff --git a/src/main.rs b/src/main.rs index 8c6f0d0..996b697 100644 --- a/src/main.rs +++ b/src/main.rs @@ -40,6 +40,8 @@ enum Commands { Prs(sub_commands::prs::SubCommandArgs), /// pull latest commits in pr linked to checked out branch Pull, + /// push commits to current checked out pr branch + Push, } #[tokio::main] @@ -54,5 +56,6 @@ async fn main() -> Result<()> { } Commands::Prs(args) => futures::executor::block_on(sub_commands::prs::launch(&cli, args)), Commands::Pull => futures::executor::block_on(sub_commands::pull::launch()), + Commands::Push => futures::executor::block_on(sub_commands::push::launch(&cli)), } } diff --git a/src/sub_commands/mod.rs b/src/sub_commands/mod.rs index 12a7f0f..8be9004 100644 --- a/src/sub_commands/mod.rs +++ b/src/sub_commands/mod.rs @@ -2,3 +2,4 @@ pub mod claim; pub mod login; pub mod prs; pub mod pull; +pub mod push; diff --git a/src/sub_commands/push.rs b/src/sub_commands/push.rs new file mode 100644 index 0000000..968aa0a --- /dev/null +++ b/src/sub_commands/push.rs @@ -0,0 +1,182 @@ +use anyhow::{bail, Context, Result}; +use nostr::prelude::sha1::Hash as Sha1Hash; + +#[cfg(not(test))] +use crate::client::Client; +#[cfg(test)] +use crate::client::MockConnect; +use crate::{ + client::Connect, + git::{str_to_sha1, Repo, RepoActions}, + login, + repo_ref::{self, RepoRef}, + sub_commands::prs::{ + create::{generate_patch_event, send_events, PATCH_KIND, PR_KIND}, + list::{get_most_recent_patch_with_ancestors, tag_value}, + }, + Cli, +}; + +pub async fn launch(cli_args: &Cli) -> 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")?; + + let branch_name = git_repo + .get_checked_out_branch_name() + .context("cannot get checked out branch name")?; + + if branch_name == main_or_master_branch_name { + bail!("checkout a branch associated with a PR first") + } + #[cfg(not(test))] + let mut client = Client::default(); + #[cfg(test)] + let mut client = ::default(); + + let repo_ref = repo_ref::fetch( + root_commit.to_string(), + &client, + client.get_more_fallback_relays().clone(), + ) + .await?; + + let (pr_event, commit_events) = + fetch_pr_and_most_recent_patch_chain(&client, &repo_ref, &root_commit, &branch_name) + .await?; + + // TODO: fix these scenarios: + // - local PR branch is 2 behind and 1 ahead. intructions: ... + // - PR has been rebased. (against commit in main) instructions: ... + // - PR has been rebased. (against commit not in repo) instructions: .. + + let most_recent_pr_patch_chain = get_most_recent_patch_with_ancestors(commit_events) + .context("cannot get most recent patch for PR")?; + + let branch_tip = git_repo.get_tip_of_local_branch(&branch_name)?; + + let most_recent_patch_commit_id = str_to_sha1( + &tag_value(&most_recent_pr_patch_chain[0], "commit") + .context("latest patch event doesnt have a commit tag")?, + ) + .context("latest patch event commit tag isn't a valid SHA1 hash")?; + + if most_recent_patch_commit_id.eq(&branch_tip) { + bail!("nostr pr already up-to-date with local branch"); + } + + if most_recent_pr_patch_chain.iter().any(|e| { + let c = tag_value(e, "parent-commit").unwrap_or_default(); + c.eq(&branch_tip.to_string()) + }) { + bail!("nostr pr is ahead of local branch"); + } + + let (ahead, behind) = git_repo + .get_commits_ahead_behind(&most_recent_patch_commit_id, &branch_tip) + .context("the latest patch in pr doesnt share an ancestor with your branch.")?; + + if !behind.is_empty() { + bail!( + "your local pr branch is {} behind patches on nostr. consider rebasing or force pushing", + behind.len() + ) + } + + println!( + "{} commits ahead. preparing to create creating patch events.", + ahead.len() + ); + + let (keys, user_ref) = login::launch(&cli_args.nsec, &cli_args.password, Some(&client)).await?; + + client.set_keys(&keys).await; + + let mut patch_events: Vec = vec![]; + for commit in &ahead { + patch_events.push( + generate_patch_event(&git_repo, &root_commit, commit, pr_event.id, &keys) + .context("cannot make patch event from commit")?, + ); + } + println!("pushing {} commits", ahead.len()); + + send_events( + &client, + patch_events, + user_ref.relays.write(), + repo_ref.relays.clone(), + !cli_args.disable_cli_spinners, + ) + .await?; + + println!("pushed {} commits", ahead.len()); + + Ok(()) +} + +async fn fetch_pr_and_most_recent_patch_chain( + #[cfg(test)] client: &crate::client::MockConnect, + #[cfg(not(test))] client: &Client, + repo_ref: &RepoRef, + root_commit: &Sha1Hash, + branch_name: &String, +) -> Result<(nostr::Event, Vec)> { + println!("finding PR event..."); + + let pr_event: nostr::Event = client + .get_events( + repo_ref.relays.clone(), + vec![ + nostr::Filter::default() + .kind(nostr::Kind::Custom(PR_KIND)) + .reference(format!("r-{root_commit}")), + ], + ) + .await? + .iter() + .find(|e| { + e.kind.as_u64() == PR_KIND + && e.tags + .iter() + .any(|t| t.as_vec().len() > 1 && t.as_vec()[1].eq(&format!("r-{root_commit}"))) + && tag_value(e, "branch-name") + .unwrap_or_default() + .eq(branch_name) + }) + .context("cannot find a PR event associated with the checked out branch name")? + .to_owned(); + + println!("found PR event. finding commits..."); + + let commits_events: Vec = client + .get_events( + repo_ref.relays.clone(), + vec![ + nostr::Filter::default() + .kind(nostr::Kind::Custom(PATCH_KIND)) + .event(pr_event.id) + .reference(format!("r-{root_commit}")), + ], + ) + .await? + .iter() + .filter(|e| { + e.kind.as_u64() == PATCH_KIND + && e.tags + .iter() + .any(|t| t.as_vec().len() > 2 && t.as_vec()[1].eq(&pr_event.id.to_string())) + && e.tags + .iter() + .any(|t| t.as_vec().len() > 1 && t.as_vec()[1].eq(&format!("r-{root_commit}"))) + }) + .map(std::borrow::ToOwned::to_owned) + .collect(); + Ok((pr_event, commits_events)) +} diff --git a/tests/push.rs b/tests/push.rs new file mode 100644 index 0000000..4fdb6eb --- /dev/null +++ b/tests/push.rs @@ -0,0 +1,477 @@ +use anyhow::Result; +use futures::join; +use serial_test::serial; +use test_utils::{git::GitTestRepo, relay::Relay, *}; + +static FEATURE_BRANCH_NAME_1: &str = "feature-example-t"; +static FEATURE_BRANCH_NAME_2: &str = "feature-example-f"; +static FEATURE_BRANCH_NAME_3: &str = "feature-example-c"; + +static PR_TITLE_1: &str = "pr a"; +static PR_TITLE_2: &str = "pr b"; +static PR_TITLE_3: &str = "pr c"; + +fn cli_tester_create_prs() -> Result { + let git_repo = GitTestRepo::default(); + git_repo.populate()?; + cli_tester_create_pr( + &git_repo, + FEATURE_BRANCH_NAME_1, + "a", + PR_TITLE_1, + "pr a description", + )?; + cli_tester_create_pr( + &git_repo, + FEATURE_BRANCH_NAME_2, + "b", + PR_TITLE_2, + "pr b description", + )?; + cli_tester_create_pr( + &git_repo, + FEATURE_BRANCH_NAME_3, + "c", + PR_TITLE_3, + "pr c description", + )?; + Ok(git_repo) +} + +fn create_and_populate_branch( + test_repo: &GitTestRepo, + branch_name: &str, + prefix: &str, + only_one_commit: bool, +) -> Result<()> { + test_repo.checkout("main")?; + test_repo.create_branch(branch_name)?; + test_repo.checkout(branch_name)?; + std::fs::write( + test_repo.dir.join(format!("{}3.md", prefix)), + "some content", + )?; + test_repo.stage_and_commit(format!("add {}3.md", prefix).as_str())?; + if !only_one_commit { + std::fs::write( + test_repo.dir.join(format!("{}4.md", prefix)), + "some content", + )?; + test_repo.stage_and_commit(format!("add {}4.md", prefix).as_str())?; + } + Ok(()) +} + +fn cli_tester_create_pr( + test_repo: &GitTestRepo, + branch_name: &str, + prefix: &str, + title: &str, + description: &str, +) -> Result<()> { + create_and_populate_branch(test_repo, branch_name, prefix, false)?; + + let mut p = CliTester::new_from_dir( + &test_repo.dir, + [ + "--nsec", + TEST_KEY_1_NSEC, + "--password", + TEST_PASSWORD, + "--disable-cli-spinners", + "prs", + "create", + "--title", + format!("\"{title}\"").as_str(), + "--description", + format!("\"{description}\"").as_str(), + ], + ); + p.expect_end_eventually()?; + Ok(()) +} + +mod when_main_is_checked_out { + use super::*; + + #[test] + fn cli_returns_error() -> Result<()> { + let test_repo = GitTestRepo::default(); + test_repo.populate()?; + create_and_populate_branch(&test_repo, FEATURE_BRANCH_NAME_1, "a", false)?; + test_repo.checkout("main")?; + let mut p = CliTester::new_from_dir(&test_repo.dir, ["push"]); + p.expect("Error: checkout a branch associated with a PR first\r\n")?; + p.expect_end()?; + Ok(()) + } +} + +mod when_pr_isnt_associated_with_branch_name { + use super::*; + + mod cli_prompts { + use super::*; + async fn run_async_cli_show_error() -> Result<()> { + let (mut r51, mut r52, mut r53, mut r55, mut r56) = ( + Relay::new(8051, None, None), + Relay::new(8052, None, None), + Relay::new(8053, None, None), + Relay::new(8055, None, None), + Relay::new(8056, None, None), + ); + + r51.events.push(generate_test_key_1_relay_list_event()); + r51.events.push(generate_test_key_1_metadata_event("fred")); + r51.events.push(generate_repo_ref_event()); + + r55.events.push(generate_repo_ref_event()); + r55.events.push(generate_test_key_1_metadata_event("fred")); + r55.events.push(generate_test_key_1_relay_list_event()); + + let cli_tester_handle = std::thread::spawn(move || -> Result<()> { + cli_tester_create_prs()?; + + let test_repo = GitTestRepo::default(); + test_repo.populate()?; + + test_repo.create_branch("random-name")?; + test_repo.checkout("random-name")?; + + let mut p = CliTester::new_from_dir(&test_repo.dir, ["push"]); + p.expect("finding PR event...\r\n")?; + p.expect( + "Error: cannot find a PR event associated with the checked out branch name\r\n", + )?; + + p.expect_end()?; + + 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 cli_show_error() -> Result<()> { + futures::executor::block_on(run_async_cli_show_error()) + } + } +} + +mod when_branch_is_checked_out { + use super::*; + + mod when_branch_is_up_to_date { + use super::*; + + mod cli_prompts { + use super::*; + async fn run_async_cli_show_up_to_date() -> Result<()> { + let (mut r51, mut r52, mut r53, mut r55, mut r56) = ( + Relay::new(8051, None, None), + Relay::new(8052, None, None), + Relay::new(8053, None, None), + Relay::new(8055, None, None), + Relay::new(8056, None, None), + ); + + r51.events.push(generate_test_key_1_relay_list_event()); + r51.events.push(generate_test_key_1_metadata_event("fred")); + r51.events.push(generate_repo_ref_event()); + + r55.events.push(generate_repo_ref_event()); + r55.events.push(generate_test_key_1_metadata_event("fred")); + r55.events.push(generate_test_key_1_relay_list_event()); + + let cli_tester_handle = std::thread::spawn(move || -> Result<()> { + cli_tester_create_prs()?; + + let test_repo = GitTestRepo::default(); + test_repo.populate()?; + + create_and_populate_branch(&test_repo, FEATURE_BRANCH_NAME_1, "a", false)?; + + let mut p = CliTester::new_from_dir(&test_repo.dir, ["push"]); + p.expect("finding PR event...\r\n")?; + p.expect("found PR event. finding commits...\r\n")?; + p.expect("Error: nostr pr already up-to-date with local branch\r\n")?; + p.expect_end()?; + + 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 cli_show_up_to_date() -> Result<()> { + futures::executor::block_on(run_async_cli_show_up_to_date()) + } + } + } + + mod when_branch_is_behind { + use super::*; + + mod cli_prompts { + use super::*; + async fn run_async_cli_show_up_to_date() -> Result<()> { + let (mut r51, mut r52, mut r53, mut r55, mut r56) = ( + Relay::new(8051, None, None), + Relay::new(8052, None, None), + Relay::new(8053, None, None), + Relay::new(8055, None, None), + Relay::new(8056, None, None), + ); + + r51.events.push(generate_test_key_1_relay_list_event()); + r51.events.push(generate_test_key_1_metadata_event("fred")); + r51.events.push(generate_repo_ref_event()); + + r55.events.push(generate_repo_ref_event()); + r55.events.push(generate_test_key_1_metadata_event("fred")); + r55.events.push(generate_test_key_1_relay_list_event()); + + let cli_tester_handle = std::thread::spawn(move || -> Result<()> { + cli_tester_create_prs()?; + + let test_repo = GitTestRepo::default(); + test_repo.populate()?; + + create_and_populate_branch(&test_repo, FEATURE_BRANCH_NAME_1, "a", true)?; + + let mut p = CliTester::new_from_dir(&test_repo.dir, ["push"]); + p.expect("finding PR event...\r\n")?; + p.expect("found PR event. finding commits...\r\n")?; + p.expect("Error: nostr pr is ahead of local branch\r\n")?; + p.expect_end()?; + + 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 cli_show_up_to_date() -> Result<()> { + futures::executor::block_on(run_async_cli_show_up_to_date()) + } + } + } + + mod when_branch_is_ahead { + use super::*; + + mod cli_prompts { + use test_utils::relay::expect_send_with_progress; + + use super::*; + + async fn run_async_cli_applied_1_commit() -> Result<()> { + // 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, None), + Relay::new(8052, None, None), + Relay::new(8053, None, None), + Relay::new(8055, None, None), + Relay::new(8056, None, None), + ); + + r51.events.push(generate_test_key_1_relay_list_event()); + r51.events.push(generate_test_key_1_metadata_event("fred")); + r51.events.push(generate_repo_ref_event()); + + r55.events.push(generate_repo_ref_event()); + r55.events.push(generate_test_key_1_metadata_event("fred")); + r55.events.push(generate_test_key_1_relay_list_event()); + + let cli_tester_handle = + std::thread::spawn(move || -> Result<(GitTestRepo, GitTestRepo)> { + let originating_repo = cli_tester_create_prs()?; + + let test_repo = GitTestRepo::default(); + test_repo.populate()?; + + create_and_populate_branch(&test_repo, FEATURE_BRANCH_NAME_1, "a", false)?; + + std::fs::write(test_repo.dir.join("a5.md"), "some content")?; + test_repo.stage_and_commit("add a5.md".to_string().as_str())?; + + let mut p = CliTester::new_from_dir( + &test_repo.dir, + [ + "--nsec", + TEST_KEY_1_NSEC, + "--password", + TEST_PASSWORD, + "--disable-cli-spinners", + "push", + ], + ); + p.expect("finding PR event...\r\n")?; + p.expect("found PR event. finding commits...\r\n")?; + p.expect( + "1 commits ahead. preparing to create creating patch events.\r\n", + )?; + p.expect("searching for your details...\r\n")?; + p.expect("\r")?; + p.expect("logged in as fred\r\n")?; + p.expect("pushing 1 commits\r\n")?; + + 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_eventually("pushed 1 commits\r\n")?; + p.expect_end()?; + + for p in [51, 52, 53, 55, 56] { + relay::shutdown_relay(8000 + p)?; + } + Ok((originating_repo, test_repo)) + }); + + // 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 cli_applied_1_commit() -> Result<()> { + futures::executor::block_on(run_async_cli_applied_1_commit()) + } + } + + async fn prep_and_run() -> Result<(GitTestRepo, Vec)> { + // 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, None), + Relay::new(8052, None, None), + Relay::new(8053, None, None), + Relay::new(8055, None, None), + Relay::new(8056, None, None), + ); + + r51.events.push(generate_test_key_1_relay_list_event()); + r51.events.push(generate_test_key_1_metadata_event("fred")); + r51.events.push(generate_repo_ref_event()); + + r55.events.push(generate_repo_ref_event()); + r55.events.push(generate_test_key_1_metadata_event("fred")); + r55.events.push(generate_test_key_1_relay_list_event()); + + let cli_tester_handle = std::thread::spawn(move || -> Result { + cli_tester_create_prs()?; + + let test_repo = GitTestRepo::default(); + test_repo.populate()?; + + create_and_populate_branch(&test_repo, FEATURE_BRANCH_NAME_1, "a", false)?; + + let mut p = CliTester::new_from_dir( + &test_repo.dir, + [ + "--nsec", + TEST_KEY_1_NSEC, + "--password", + TEST_PASSWORD, + "--disable-cli-spinners", + "push", + ], + ); + p.expect_end_eventually()?; + + for p in [51, 52, 53, 55, 56] { + relay::shutdown_relay(8000 + p)?; + } + Ok(test_repo) + }); + + // launch relay + let _ = join!( + r51.listen_until_close(), + r52.listen_until_close(), + r53.listen_until_close(), + r55.listen_until_close(), + r56.listen_until_close(), + ); + let res = cli_tester_handle.join().unwrap()?; + + Ok((res, r55.events.clone())) + } + #[test] + #[serial] + fn commits_issued_as_patch_event() -> Result<()> { + let (test_repo, r55_events) = futures::executor::block_on(prep_and_run())?; + + let commit_id = test_repo + .get_tip_of_local_branch(FEATURE_BRANCH_NAME_1)? + .to_string(); + assert!(r55_events.iter().any(|e| { + e.tags + .iter() + .any(|t| t.as_vec()[0].eq("commit") && t.as_vec()[1].eq(&commit_id)) + })); + Ok(()) + } + } + + mod when_branch_has_been_rebased { + // use super::*; + // TODO + } +} -- cgit v1.2.3