From 312786fbdacd61fc9f3ed59612d9a6add9112b7f Mon Sep 17 00:00:00 2001 From: DanConwayDev Date: Thu, 22 Feb 2024 12:18:01 +0000 Subject: feat(pull): support `--in-reply-to` revisions added tests to cover one of these rebase scenarios --- src/git.rs | 34 ++++++ src/sub_commands/pull.rs | 141 ++++++++++++++++++++-- tests/pull.rs | 296 ++++++++++++++++++++++++++++++++++++++++++----- 3 files changed, 434 insertions(+), 37 deletions(-) diff --git a/src/git.rs b/src/git.rs index 0a06ab5..6edca0f 100644 --- a/src/git.rs +++ b/src/git.rs @@ -344,6 +344,12 @@ impl RepoActions for Repo { } fn create_branch_at_commit(&self, branch_name: &str, commit: &str) -> Result<()> { + let branch_checkedout = self.get_checked_out_branch_name()?.eq(branch_name); + if branch_checkedout { + let (name, _) = self.get_main_or_master_branch()?; + self.checkout(name)?; + } + self.git_repo .branch( branch_name, @@ -351,6 +357,10 @@ impl RepoActions for Repo { true, ) .context("branch could not be created")?; + + if branch_checkedout { + self.checkout(branch_name)?; + } Ok(()) } /* returns patches applied */ @@ -1292,6 +1302,30 @@ mod tests { assert_eq!(test_repo.checkout(branch_name)?, ahead_1_oid); Ok(()) } + + #[test] + fn when_branch_is_checkedout_new_tip_specified_it_is_updated() -> Result<()> { + let test_repo = GitTestRepo::default(); + test_repo.populate()?; + // create feature branch and add 2 commits + test_repo.create_branch("feature")?; + test_repo.checkout("feature")?; + std::fs::write(test_repo.dir.join("t3.md"), "some content")?; + let ahead_1_oid = test_repo.stage_and_commit("add t3.md")?; + std::fs::write(test_repo.dir.join("t4.md"), "some content")?; + let ahead_2_oid = test_repo.stage_and_commit("add t4.md")?; + + let git_repo = Repo::from_path(&test_repo.dir)?; + + let branch_name = "test-name-1"; + git_repo.create_branch_at_commit(branch_name, &ahead_1_oid.to_string())?; + test_repo.checkout(branch_name)?; + git_repo.create_branch_at_commit(branch_name, &ahead_2_oid.to_string())?; + test_repo.checkout("main")?; + + assert_eq!(test_repo.checkout(branch_name)?, ahead_2_oid); + Ok(()) + } } } diff --git a/src/sub_commands/pull.rs b/src/sub_commands/pull.rs index de078e3..d832f6e 100644 --- a/src/sub_commands/pull.rs +++ b/src/sub_commands/pull.rs @@ -1,12 +1,13 @@ use anyhow::{bail, Context, Result}; +use super::list::{get_commit_id_from_patch, tag_value}; #[cfg(not(test))] use crate::client::Client; #[cfg(test)] use crate::client::MockConnect; use crate::{ client::Connect, - git::{Repo, RepoActions}, + git::{str_to_sha1, Repo, RepoActions}, repo_ref, sub_commands::{ list::get_most_recent_patch_with_ancestors, @@ -14,6 +15,7 @@ use crate::{ }, }; +#[allow(clippy::too_many_lines)] pub async fn launch() -> Result<()> { let git_repo = Repo::discover().context("cannot find a git repository")?; @@ -53,22 +55,139 @@ pub async fn launch() -> Result<()> { ) .await?; - if git_repo.has_outstanding_changes()? { - bail!("cannot pull changes when repository is not clean. discard changes and try again."); - } + let most_recent_proposal_patch_chain = + get_most_recent_patch_with_ancestors(commit_events.clone()) + .context("cannot get most recent patch for proposal")?; + + let local_branch_tip = git_repo.get_tip_of_local_branch(&branch_name)?; + + let (main_branch_name, master_tip) = git_repo.get_main_or_master_branch()?; + + let (local_ahead_of_main, local_beind_main) = + git_repo.get_commits_ahead_behind(&master_tip, &local_branch_tip)?; - let most_recent_proposal_patch_chain = get_most_recent_patch_with_ancestors(commit_events) - .context("cannot get most recent patch for proposal")?; + let proposal_base_commit = str_to_sha1(&tag_value( + most_recent_proposal_patch_chain + .last() + .context("there should be at least one patch as we have already checked for this")?, + "parent-commit", + )?) + .context("cannot get valid parent commit id from patch")?; - let applied = git_repo - .apply_patch_chain(&branch_name, most_recent_proposal_patch_chain) - .context("cannot apply patch chain")?; + let (_, proposal_behind_main) = + git_repo.get_commits_ahead_behind(&master_tip, &proposal_base_commit)?; - if applied.is_empty() { + let proposal_tip = + str_to_sha1( + &get_commit_id_from_patch(most_recent_proposal_patch_chain.first().context( + "there should be at least one patch as we have already checked for this", + )?) + .context("cannot get valid commit_id from patch")?, + ) + .context("cannot get valid commit_id from patch")?; + + // if uptodate + if proposal_tip.eq(&local_branch_tip) { println!("branch already up-to-date"); - } else { + } + // if new appendments + else if most_recent_proposal_patch_chain.iter().any(|patch| { + get_commit_id_from_patch(patch) + .unwrap_or_default() + .eq(&local_branch_tip.to_string()) + }) { + check_clean(&git_repo)?; + let applied = git_repo + .apply_patch_chain(&branch_name, most_recent_proposal_patch_chain) + .context("cannot apply patch chain")?; println!("applied {} new commits", applied.len(),); } + // if parent commit doesnt exist + else if !git_repo.does_commit_exist(&proposal_base_commit.to_string())? { + println!( + "a new version of the proposal has a prant commit that doesnt exist in your local repository." + ); + println!("your '{main_branch_name}' branch may not be up-to-date."); + println!("manually run `git pull` on '{main_branch_name}' and try again"); + } + // if tip of local in proposal history (new, ammended or rebased version but no + // local changes) + else if commit_events.iter().any(|patch| { + get_commit_id_from_patch(patch) + .unwrap_or_default() + .eq(&local_branch_tip.to_string()) + }) { + check_clean(&git_repo)?; + + git_repo.create_branch_at_commit(&branch_name, &proposal_base_commit.to_string())?; + let applied = git_repo + .apply_patch_chain(&branch_name, most_recent_proposal_patch_chain) + .context("cannot apply patch chain")?; + + println!( + "pulled new version of proposal ({} ahead {} behind '{main_branch_name}'), replacing old version ({} ahead {} behind '{main_branch_name}')", + applied.len(), + proposal_behind_main.len(), + local_ahead_of_main.len(), + local_beind_main.len(), + ); + } + // if tip of proposal in branch in history (local appendments made to up-to-date + // proposal) + else if let Ok((local_ahead_of_proposal, _)) = + git_repo.get_commits_ahead_behind(&proposal_tip, &local_branch_tip) + { + println!( + "local proposal branch exists with {} unpublished commits on top of the most up-to-date version of the proposal", + local_ahead_of_proposal.len() + ); + } + // user has probably has an unpublished rebase of the latest proposal version + // if tip of proposal commits exist (were once part of branch but have been + // ammended and git clean up job hasn't removed them) + else if git_repo.does_commit_exist(&proposal_tip.to_string())? { + println!( + "you have previously applied the latest version of the proposal ({} ahead {} behind '{main_branch_name}') but your local proposal branch has other unpublished changes ({} ahead {} behind '{main_branch_name}')", + most_recent_proposal_patch_chain.len(), + proposal_behind_main.len(), + local_ahead_of_main.len(), + local_beind_main.len(), + ); + println!( + "if this sounds right then consider publishing your rebase `ngit push --force` or discarding your local branch" + ); + } + // user has probaly has an unpublished rebase of an older version of the + // proposal + else { + println!( + "your local proposal branch ({} ahead {} behind '{main_branch_name}') has conflicting changes with the latest published proposal ({} ahead {} behind '{main_branch_name}')", + local_ahead_of_main.len(), + local_beind_main.len(), + most_recent_proposal_patch_chain.len(), + proposal_behind_main.len(), + ); + println!( + "its likely that you are working off an old proposal version because git has no record of the latest proposal commit." + ); + println!( + "it is possible that you have ammended the latest version and git has delete this commit as part of a clean up" + ); + + println!("to view the latest proposal but retain your changes:"); + println!(" 1) create a new branch off the tip commit of this one to store your changes"); + println!(" 2) run `ngit list` and checkout the latest published version of this proposal"); + + println!("if you are confident in your changes consider running `ngit push --force`"); + } + Ok(()) +} +fn check_clean(git_repo: &Repo) -> Result<()> { + if git_repo.has_outstanding_changes()? { + bail!( + "cannot pull proposal branch when repository is not clean. discard or stash (un)staged changes and try again." + ); + } Ok(()) } diff --git a/tests/pull.rs b/tests/pull.rs index c4bc169..39f3ef4 100644 --- a/tests/pull.rs +++ b/tests/pull.rs @@ -18,22 +18,22 @@ fn cli_tester_create_proposals() -> Result { &git_repo, FEATURE_BRANCH_NAME_1, "a", - PROPOSAL_TITLE_1, - "proposal a description", + Some((PROPOSAL_TITLE_1, "proposal a description")), + None, )?; cli_tester_create_proposal( &git_repo, FEATURE_BRANCH_NAME_2, "b", - PROPOSAL_TITLE_2, - "proposal b description", + Some((PROPOSAL_TITLE_2, "proposal b description")), + None, )?; cli_tester_create_proposal( &git_repo, FEATURE_BRANCH_NAME_3, "c", - PROPOSAL_TITLE_3, - "proposal c description", + Some((PROPOSAL_TITLE_3, "proposal c description")), + None, )?; Ok(git_repo) } @@ -66,27 +66,59 @@ fn cli_tester_create_proposal( test_repo: &GitTestRepo, branch_name: &str, prefix: &str, - title: &str, - description: &str, + cover_letter_title_and_description: Option<(&str, &str)>, + in_reply_to: Option, ) -> 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", - "send", - "--title", - format!("\"{title}\"").as_str(), - "--description", - format!("\"{description}\"").as_str(), - ], - ); - p.expect_end_eventually()?; + if let Some(in_reply_to) = in_reply_to { + let mut p = CliTester::new_from_dir( + &test_repo.dir, + [ + "--nsec", + TEST_KEY_1_NSEC, + "--password", + TEST_PASSWORD, + "--disable-cli-spinners", + "send", + "--no-cover-letter", + "--in-reply-to", + in_reply_to.as_str(), + ], + ); + p.expect_end_eventually()?; + } else if let Some((title, description)) = cover_letter_title_and_description { + let mut p = CliTester::new_from_dir( + &test_repo.dir, + [ + "--nsec", + TEST_KEY_1_NSEC, + "--password", + TEST_PASSWORD, + "--disable-cli-spinners", + "send", + "--title", + format!("\"{title}\"").as_str(), + "--description", + format!("\"{description}\"").as_str(), + ], + ); + p.expect_end_eventually()?; + } else { + let mut p = CliTester::new_from_dir( + &test_repo.dir, + [ + "--nsec", + TEST_KEY_1_NSEC, + "--password", + TEST_PASSWORD, + "--disable-cli-spinners", + "send", + "--no-cover-letter", + ], + ); + p.expect_end_eventually()?; + } Ok(()) } @@ -415,7 +447,219 @@ mod when_branch_is_checked_out { } mod when_latest_event_rebases_branch { - // use super::*; - // TODO + use std::time::Duration; + + use nostr_sdk::blocking::Client; + + use super::*; + + async fn prep_and_run() -> Result<(GitTestRepo, GitTestRepo)> { + // 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)> { + // create 3 proposals + let _ = cli_tester_create_proposals()?; + // get proposal id of first + let client = Client::new(&nostr::Keys::generate()); + client.add_relay("ws://localhost:8055")?; + client.connect_relay("ws://localhost:8055")?; + let proposals = client.get_events_of( + vec![ + nostr::Filter::default() + .kind(nostr::Kind::Custom(PATCH_KIND)) + .custom_tag(nostr::Alphabet::T, vec!["root"]), + ], + Some(Duration::from_millis(500)), + )?; + client.disconnect()?; + + let proposal_1_id = proposals + .iter() + .find(|e| { + e.tags + .iter() + .any(|t| t.as_vec()[1].eq(&FEATURE_BRANCH_NAME_1)) + }) + .unwrap() + .id; + // recreate proposal 1 on top of a another commit (like a rebase on top + // of one extra commit) + let second_originating_repo = GitTestRepo::default(); + second_originating_repo.populate()?; + std::fs::write( + second_originating_repo.dir.join("amazing.md"), + "some content", + )?; + second_originating_repo.stage_and_commit("commit for rebasing on top of")?; + cli_tester_create_proposal( + &second_originating_repo, + FEATURE_BRANCH_NAME_1, + "a", + Some((PROPOSAL_TITLE_1, "proposal a description")), + Some(proposal_1_id.to_string()), + )?; + + // pretend we have downloaded the origianl version of the first proposal + let test_repo = GitTestRepo::default(); + test_repo.populate()?; + create_and_populate_branch(&test_repo, FEATURE_BRANCH_NAME_1, "a", false)?; + // pretend we have pulled the updated main branch + test_repo.checkout("main")?; + std::fs::write(test_repo.dir.join("amazing.md"), "some content")?; + test_repo.stage_and_commit("commit for rebasing on top of")?; + test_repo.checkout(FEATURE_BRANCH_NAME_1)?; + + let mut p = CliTester::new_from_dir(&test_repo.dir, ["pull"]); + p.expect_end_eventually_and_print()?; + + for p in [51, 52, 53, 55, 56] { + relay::shutdown_relay(8000 + p)?; + } + Ok((second_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(), + ); + let res = cli_tester_handle.join().unwrap()?; + + Ok(res) + } + + mod cli_prompts { + use super::*; + async fn run_async_prompts_to_choose_from_proposal_titles() -> 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<()> { + // create 3 proposals + let _ = cli_tester_create_proposals()?; + // get proposal id of first + let client = Client::new(&nostr::Keys::generate()); + client.add_relay("ws://localhost:8055")?; + client.connect_relay("ws://localhost:8055")?; + let proposals = client.get_events_of( + vec![ + nostr::Filter::default() + .kind(nostr::Kind::Custom(PATCH_KIND)) + .custom_tag(nostr::Alphabet::T, vec!["root"]), + ], + Some(Duration::from_millis(500)), + )?; + client.disconnect()?; + + let proposal_1_id = proposals + .iter() + .find(|e| { + e.tags + .iter() + .any(|t| t.as_vec()[1].eq(&FEATURE_BRANCH_NAME_1)) + }) + .unwrap() + .id; + // recreate proposal 1 on top of a another commit (like a rebase on top + // of one extra commit) + let second_originating_repo = GitTestRepo::default(); + second_originating_repo.populate()?; + std::fs::write( + second_originating_repo.dir.join("amazing.md"), + "some content", + )?; + second_originating_repo.stage_and_commit("commit for rebasing on top of")?; + cli_tester_create_proposal( + &second_originating_repo, + FEATURE_BRANCH_NAME_1, + "a", + Some((PROPOSAL_TITLE_1, "proposal a description")), + Some(proposal_1_id.to_string()), + )?; + + // pretend we have downloaded the origianl version of the first proposal + let test_repo = GitTestRepo::default(); + test_repo.populate()?; + create_and_populate_branch(&test_repo, FEATURE_BRANCH_NAME_1, "a", false)?; + // pretend we have pulled the updated main branch + test_repo.checkout("main")?; + std::fs::write(test_repo.dir.join("amazing.md"), "some content")?; + test_repo.stage_and_commit("commit for rebasing on top of")?; + test_repo.checkout(FEATURE_BRANCH_NAME_1)?; + + let mut p = CliTester::new_from_dir(&test_repo.dir, ["pull"]); + p.expect("finding proposal root event...\r\n")?; + p.expect("found proposal root event. finding commits...\r\n")?; + p.expect_end_with("pulled new version of proposal (2 ahead 0 behind 'main'), replacing old version (2 ahead 1 behind 'main')\r\n")?; + + 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()?; + println!("{:?}", r55.events); + Ok(()) + } + + #[tokio::test] + #[serial] + async fn prompts_to_choose_from_proposal_titles() -> Result<()> { + let _ = run_async_prompts_to_choose_from_proposal_titles().await; + Ok(()) + } + } + + #[tokio::test] + #[serial] + async fn proposal_branch_tip_is_most_recent_proposal_revision_tip() -> Result<()> { + let (originating_repo, test_repo) = prep_and_run().await?; + assert_eq!( + originating_repo.get_tip_of_local_branch(FEATURE_BRANCH_NAME_1)?, + test_repo.get_tip_of_local_branch(FEATURE_BRANCH_NAME_1)?, + ); + Ok(()) + } } } -- cgit v1.2.3