diff options
| author | DanConwayDev <DanConwayDev@protonmail.com> | 2025-07-25 21:02:26 +0100 |
|---|---|---|
| committer | DanConwayDev <DanConwayDev@protonmail.com> | 2025-07-25 22:17:23 +0100 |
| commit | 513fce723c7e37aa353844303f36022517f2db43 (patch) | |
| tree | 05e16bdd4789036af04b6c046823396f9f0faf22 /src/bin/git_remote_nostr | |
| parent | e89dbc142f5a0a517f197562f5f228681d9aed47 (diff) | |
refactor: move `utils` and `list` helpers to lib
to enable forthcoming `ngit sync` cmd
Diffstat (limited to 'src/bin/git_remote_nostr')
| -rw-r--r-- | src/bin/git_remote_nostr/fetch.rs | 10 | ||||
| -rw-r--r-- | src/bin/git_remote_nostr/list.rs | 163 | ||||
| -rw-r--r-- | src/bin/git_remote_nostr/main.rs | 3 | ||||
| -rw-r--r-- | src/bin/git_remote_nostr/push.rs | 17 | ||||
| -rw-r--r-- | src/bin/git_remote_nostr/utils.rs | 448 |
5 files changed, 18 insertions, 623 deletions
diff --git a/src/bin/git_remote_nostr/fetch.rs b/src/bin/git_remote_nostr/fetch.rs index f3d4362..221d964 100644 --- a/src/bin/git_remote_nostr/fetch.rs +++ b/src/bin/git_remote_nostr/fetch.rs | |||
| @@ -19,15 +19,15 @@ use ngit::{ | |||
| 19 | git_events::{KIND_PULL_REQUEST, KIND_PULL_REQUEST_UPDATE, tag_value}, | 19 | git_events::{KIND_PULL_REQUEST, KIND_PULL_REQUEST_UPDATE, tag_value}, |
| 20 | login::get_curent_user, | 20 | login::get_curent_user, |
| 21 | repo_ref::{RepoRef, is_grasp_server}, | 21 | repo_ref::{RepoRef, is_grasp_server}, |
| 22 | utils::{ | ||
| 23 | Direction, find_proposal_and_patches_by_branch_name, get_oids_from_fetch_batch, | ||
| 24 | get_open_or_draft_proposals, get_read_protocols_to_try, join_with_and, | ||
| 25 | set_protocol_preference, | ||
| 26 | }, | ||
| 22 | }; | 27 | }; |
| 23 | use nostr::nips::nip19; | 28 | use nostr::nips::nip19; |
| 24 | use nostr_sdk::{Event, ToBech32}; | 29 | use nostr_sdk::{Event, ToBech32}; |
| 25 | 30 | ||
| 26 | use crate::utils::{ | ||
| 27 | Direction, find_proposal_and_patches_by_branch_name, get_oids_from_fetch_batch, | ||
| 28 | get_open_or_draft_proposals, get_read_protocols_to_try, join_with_and, set_protocol_preference, | ||
| 29 | }; | ||
| 30 | |||
| 31 | pub async fn run_fetch( | 31 | pub async fn run_fetch( |
| 32 | git_repo: &Repo, | 32 | git_repo: &Repo, |
| 33 | repo_ref: &RepoRef, | 33 | repo_ref: &RepoRef, |
diff --git a/src/bin/git_remote_nostr/list.rs b/src/bin/git_remote_nostr/list.rs index 7bdf170..df98c12 100644 --- a/src/bin/git_remote_nostr/list.rs +++ b/src/bin/git_remote_nostr/list.rs | |||
| @@ -1,30 +1,22 @@ | |||
| 1 | use core::str; | ||
| 2 | use std::collections::HashMap; | 1 | use std::collections::HashMap; |
| 3 | 2 | ||
| 4 | use anyhow::{Context, Result, anyhow}; | 3 | use anyhow::{Context, Result}; |
| 5 | use auth_git2::GitAuthenticator; | ||
| 6 | use client::get_state_from_cache; | 4 | use client::get_state_from_cache; |
| 7 | use git::RepoActions; | 5 | use git::RepoActions; |
| 8 | use ngit::{ | 6 | use ngit::{ |
| 9 | client, | 7 | client, |
| 10 | git::{ | 8 | git::{self}, |
| 11 | self, | ||
| 12 | nostr_url::{CloneUrl, NostrUrlDecoded, ServerProtocol}, | ||
| 13 | }, | ||
| 14 | git_events::{KIND_PULL_REQUEST, KIND_PULL_REQUEST_UPDATE, event_to_cover_letter, tag_value}, | 9 | git_events::{KIND_PULL_REQUEST, KIND_PULL_REQUEST_UPDATE, event_to_cover_letter, tag_value}, |
| 10 | list::{get_ahead_behind, list_from_remotes}, | ||
| 15 | login::get_curent_user, | 11 | login::get_curent_user, |
| 16 | repo_ref::{self, is_grasp_server}, | 12 | repo_ref::{self}, |
| 13 | utils::{get_open_or_draft_proposals, get_short_git_server_name}, | ||
| 17 | }; | 14 | }; |
| 18 | use nostr_sdk::hashes::sha1::Hash as Sha1Hash; | ||
| 19 | use repo_ref::RepoRef; | 15 | use repo_ref::RepoRef; |
| 20 | 16 | ||
| 21 | use crate::{ | 17 | use crate::{ |
| 22 | fetch::{fetch_from_git_server, make_commits_for_proposal}, | 18 | fetch::{fetch_from_git_server, make_commits_for_proposal}, |
| 23 | git::Repo, | 19 | git::Repo, |
| 24 | utils::{ | ||
| 25 | Direction, get_open_or_draft_proposals, get_read_protocols_to_try, | ||
| 26 | get_short_git_server_name, join_with_and, set_protocol_preference, | ||
| 27 | }, | ||
| 28 | }; | 20 | }; |
| 29 | 21 | ||
| 30 | pub async fn run_list( | 22 | pub async fn run_list( |
| @@ -210,148 +202,3 @@ async fn get_open_and_draft_proposals_state( | |||
| 210 | } | 202 | } |
| 211 | Ok(state) | 203 | Ok(state) |
| 212 | } | 204 | } |
| 213 | |||
| 214 | pub fn list_from_remotes( | ||
| 215 | term: &console::Term, | ||
| 216 | git_repo: &Repo, | ||
| 217 | git_servers: &Vec<String>, | ||
| 218 | decoded_nostr_url: &NostrUrlDecoded, | ||
| 219 | grasp_servers: &[String], | ||
| 220 | ) -> HashMap<String, (HashMap<String, String>, bool)> { | ||
| 221 | let mut remote_states = HashMap::new(); | ||
| 222 | let mut errors = HashMap::new(); | ||
| 223 | for url in git_servers { | ||
| 224 | let is_grasp_server = is_grasp_server(url, grasp_servers); | ||
| 225 | match list_from_remote(term, git_repo, url, decoded_nostr_url, is_grasp_server) { | ||
| 226 | Err(error) => { | ||
| 227 | errors.insert(url, error); | ||
| 228 | } | ||
| 229 | Ok(state) => { | ||
| 230 | remote_states.insert(url.to_string(), (state, is_grasp_server)); | ||
| 231 | } | ||
| 232 | } | ||
| 233 | } | ||
| 234 | remote_states | ||
| 235 | } | ||
| 236 | |||
| 237 | pub fn list_from_remote( | ||
| 238 | term: &console::Term, | ||
| 239 | git_repo: &Repo, | ||
| 240 | git_server_url: &str, | ||
| 241 | decoded_nostr_url: &NostrUrlDecoded, | ||
| 242 | is_grasp_server: bool, | ||
| 243 | ) -> Result<HashMap<String, String>> { | ||
| 244 | let server_url = git_server_url.parse::<CloneUrl>()?; | ||
| 245 | let protocols_to_attempt = | ||
| 246 | get_read_protocols_to_try(git_repo, &server_url, decoded_nostr_url, is_grasp_server); | ||
| 247 | |||
| 248 | let mut failed_protocols = vec![]; | ||
| 249 | let mut remote_state: Option<HashMap<String, String>> = None; | ||
| 250 | |||
| 251 | for protocol in &protocols_to_attempt { | ||
| 252 | term.write_line( | ||
| 253 | format!( | ||
| 254 | "fetching {} ref list over {protocol}...", | ||
| 255 | server_url.short_name(), | ||
| 256 | ) | ||
| 257 | .as_str(), | ||
| 258 | )?; | ||
| 259 | |||
| 260 | let formatted_url = server_url.format_as(protocol, &decoded_nostr_url.user)?; | ||
| 261 | let res = list_from_remote_url( | ||
| 262 | git_repo, | ||
| 263 | &formatted_url, | ||
| 264 | [ServerProtocol::UnauthHttps, ServerProtocol::UnauthHttp].contains(protocol), | ||
| 265 | term, | ||
| 266 | ); | ||
| 267 | |||
| 268 | match res { | ||
| 269 | Ok(state) => { | ||
| 270 | remote_state = Some(state); | ||
| 271 | term.clear_last_lines(1)?; | ||
| 272 | if !failed_protocols.is_empty() { | ||
| 273 | term.write_line( | ||
| 274 | format!( | ||
| 275 | "list: succeeded over {protocol} from {}", | ||
| 276 | server_url.short_name(), | ||
| 277 | ) | ||
| 278 | .as_str(), | ||
| 279 | )?; | ||
| 280 | let _ = | ||
| 281 | set_protocol_preference(git_repo, protocol, &server_url, &Direction::Fetch); | ||
| 282 | } | ||
| 283 | break; | ||
| 284 | } | ||
| 285 | Err(error) => { | ||
| 286 | term.clear_last_lines(1)?; | ||
| 287 | term.write_line( | ||
| 288 | format!("list: {formatted_url} failed over {protocol}: {error}").as_str(), | ||
| 289 | )?; | ||
| 290 | failed_protocols.push(protocol); | ||
| 291 | } | ||
| 292 | } | ||
| 293 | } | ||
| 294 | if let Some(remote_state) = remote_state { | ||
| 295 | if failed_protocols.is_empty() { | ||
| 296 | term.clear_last_lines(1)?; | ||
| 297 | } | ||
| 298 | Ok(remote_state) | ||
| 299 | } else { | ||
| 300 | let error = anyhow!( | ||
| 301 | "{} failed over {}{}", | ||
| 302 | server_url.short_name(), | ||
| 303 | join_with_and(&failed_protocols), | ||
| 304 | if decoded_nostr_url.protocol.is_some() { | ||
| 305 | " and nostr url contains protocol override so no other protocols were attempted" | ||
| 306 | } else { | ||
| 307 | "" | ||
| 308 | }, | ||
| 309 | ); | ||
| 310 | term.write_line(format!("list: {error}").as_str())?; | ||
| 311 | Err(error) | ||
| 312 | } | ||
| 313 | } | ||
| 314 | |||
| 315 | fn list_from_remote_url( | ||
| 316 | git_repo: &Repo, | ||
| 317 | git_server_remote_url: &str, | ||
| 318 | dont_authenticate: bool, | ||
| 319 | term: &console::Term, | ||
| 320 | ) -> Result<HashMap<String, String>> { | ||
| 321 | let git_config = git_repo.git_repo.config()?; | ||
| 322 | |||
| 323 | let mut git_server_remote = git_repo.git_repo.remote_anonymous(git_server_remote_url)?; | ||
| 324 | // authentication may be required | ||
| 325 | let auth = GitAuthenticator::default(); | ||
| 326 | let mut remote_callbacks = git2::RemoteCallbacks::new(); | ||
| 327 | if !dont_authenticate { | ||
| 328 | remote_callbacks.credentials(auth.credentials(&git_config)); | ||
| 329 | } | ||
| 330 | term.write_line("list: connecting...")?; | ||
| 331 | git_server_remote.connect_auth(git2::Direction::Fetch, Some(remote_callbacks), None)?; | ||
| 332 | term.clear_last_lines(1)?; | ||
| 333 | let mut state = HashMap::new(); | ||
| 334 | for head in git_server_remote.list()? { | ||
| 335 | if let Some(symbolic_reference) = head.symref_target() { | ||
| 336 | state.insert( | ||
| 337 | head.name().to_string(), | ||
| 338 | format!("ref: {symbolic_reference}"), | ||
| 339 | ); | ||
| 340 | // ignore dereferenced tags | ||
| 341 | } else if !head.name().to_string().ends_with("^{}") { | ||
| 342 | state.insert(head.name().to_string(), head.oid().to_string()); | ||
| 343 | } | ||
| 344 | } | ||
| 345 | git_server_remote.disconnect()?; | ||
| 346 | Ok(state) | ||
| 347 | } | ||
| 348 | |||
| 349 | fn get_ahead_behind( | ||
| 350 | git_repo: &Repo, | ||
| 351 | base_ref_or_oid: &str, | ||
| 352 | latest_ref_or_oid: &str, | ||
| 353 | ) -> Result<(Vec<Sha1Hash>, Vec<Sha1Hash>)> { | ||
| 354 | let base = git_repo.get_commit_or_tip_of_reference(base_ref_or_oid)?; | ||
| 355 | let latest = git_repo.get_commit_or_tip_of_reference(latest_ref_or_oid)?; | ||
| 356 | git_repo.get_commits_ahead_behind(&base, &latest) | ||
| 357 | } | ||
diff --git a/src/bin/git_remote_nostr/main.rs b/src/bin/git_remote_nostr/main.rs index cf47a30..aac626b 100644 --- a/src/bin/git_remote_nostr/main.rs +++ b/src/bin/git_remote_nostr/main.rs | |||
| @@ -18,16 +18,15 @@ use ngit::{ | |||
| 18 | client::{self, Params}, | 18 | client::{self, Params}, |
| 19 | git::{self, utils::set_git_timeout}, | 19 | git::{self, utils::set_git_timeout}, |
| 20 | login::existing::load_existing_login, | 20 | login::existing::load_existing_login, |
| 21 | utils::read_line, | ||
| 21 | }; | 22 | }; |
| 22 | use nostr::nips::nip19::Nip19Coordinate; | 23 | use nostr::nips::nip19::Nip19Coordinate; |
| 23 | use utils::read_line; | ||
| 24 | 24 | ||
| 25 | use crate::{client::Client, git::Repo}; | 25 | use crate::{client::Client, git::Repo}; |
| 26 | 26 | ||
| 27 | mod fetch; | 27 | mod fetch; |
| 28 | mod list; | 28 | mod list; |
| 29 | mod push; | 29 | mod push; |
| 30 | mod utils; | ||
| 31 | 30 | ||
| 32 | #[tokio::main] | 31 | #[tokio::main] |
| 33 | async fn main() -> Result<()> { | 32 | async fn main() -> Result<()> { |
diff --git a/src/bin/git_remote_nostr/push.rs b/src/bin/git_remote_nostr/push.rs index 909a0ab..74e98f9 100644 --- a/src/bin/git_remote_nostr/push.rs +++ b/src/bin/git_remote_nostr/push.rs | |||
| @@ -25,9 +25,15 @@ use ngit::{ | |||
| 25 | oid_to_shorthand_string, | 25 | oid_to_shorthand_string, |
| 26 | }, | 26 | }, |
| 27 | git_events::{self, KIND_PULL_REQUEST, event_to_cover_letter, get_event_root}, | 27 | git_events::{self, KIND_PULL_REQUEST, event_to_cover_letter, get_event_root}, |
| 28 | list::list_from_remotes, | ||
| 28 | login::{self, user::UserRef}, | 29 | login::{self, user::UserRef}, |
| 29 | repo_ref::{self, get_repo_config_from_yaml, is_grasp_server, normalize_grasp_server_url}, | 30 | repo_ref::{self, get_repo_config_from_yaml, is_grasp_server, normalize_grasp_server_url}, |
| 30 | repo_state, | 31 | repo_state, |
| 32 | utils::{ | ||
| 33 | Direction, find_proposal_and_patches_by_branch_name, get_all_proposals, | ||
| 34 | get_remote_name_by_url, get_short_git_server_name, get_write_protocols_to_try, | ||
| 35 | join_with_and, read_line, set_protocol_preference, | ||
| 36 | }, | ||
| 31 | }; | 37 | }; |
| 32 | use nostr::{event::UnsignedEvent, nips::nip10::Marker}; | 38 | use nostr::{event::UnsignedEvent, nips::nip10::Marker}; |
| 33 | use nostr_sdk::{ | 39 | use nostr_sdk::{ |
| @@ -37,16 +43,7 @@ use nostr_sdk::{ | |||
| 37 | use repo_ref::RepoRef; | 43 | use repo_ref::RepoRef; |
| 38 | use repo_state::RepoState; | 44 | use repo_state::RepoState; |
| 39 | 45 | ||
| 40 | use crate::{ | 46 | use crate::{client::Client, git::Repo}; |
| 41 | client::Client, | ||
| 42 | git::Repo, | ||
| 43 | list::list_from_remotes, | ||
| 44 | utils::{ | ||
| 45 | Direction, find_proposal_and_patches_by_branch_name, get_all_proposals, | ||
| 46 | get_remote_name_by_url, get_short_git_server_name, get_write_protocols_to_try, | ||
| 47 | join_with_and, read_line, set_protocol_preference, | ||
| 48 | }, | ||
| 49 | }; | ||
| 50 | 47 | ||
| 51 | #[allow(clippy::too_many_lines)] | 48 | #[allow(clippy::too_many_lines)] |
| 52 | #[allow(clippy::type_complexity)] | 49 | #[allow(clippy::type_complexity)] |
diff --git a/src/bin/git_remote_nostr/utils.rs b/src/bin/git_remote_nostr/utils.rs deleted file mode 100644 index 2cb85bf..0000000 --- a/src/bin/git_remote_nostr/utils.rs +++ /dev/null | |||
| @@ -1,448 +0,0 @@ | |||
| 1 | use core::str; | ||
| 2 | use std::{ | ||
| 3 | collections::HashMap, | ||
| 4 | fmt, | ||
| 5 | io::{self, Stdin}, | ||
| 6 | str::FromStr, | ||
| 7 | }; | ||
| 8 | |||
| 9 | use anyhow::{Context, Result, bail}; | ||
| 10 | use git2::Repository; | ||
| 11 | use ngit::{ | ||
| 12 | client::{ | ||
| 13 | get_all_proposal_patch_pr_pr_update_events_from_cache, get_events_from_local_cache, | ||
| 14 | get_proposals_and_revisions_from_cache, | ||
| 15 | }, | ||
| 16 | git::{ | ||
| 17 | Repo, RepoActions, | ||
| 18 | nostr_url::{CloneUrl, NostrUrlDecoded, ServerProtocol}, | ||
| 19 | }, | ||
| 20 | git_events::{ | ||
| 21 | event_is_revision_root, get_pr_tip_event_or_most_recent_patch_with_ancestors, get_status, | ||
| 22 | is_event_proposal_root_for_branch, status_kinds, | ||
| 23 | }, | ||
| 24 | repo_ref::RepoRef, | ||
| 25 | }; | ||
| 26 | use nostr_sdk::{Event, EventId, Kind, PublicKey, Url}; | ||
| 27 | |||
| 28 | pub fn get_short_git_server_name(git_repo: &Repo, url: &str) -> std::string::String { | ||
| 29 | if let Ok(name) = get_remote_name_by_url(&git_repo.git_repo, url) { | ||
| 30 | return name; | ||
| 31 | } | ||
| 32 | if let Ok(url) = Url::parse(url) { | ||
| 33 | if let Some(domain) = url.domain() { | ||
| 34 | return domain.to_string(); | ||
| 35 | } | ||
| 36 | } | ||
| 37 | url.to_string() | ||
| 38 | } | ||
| 39 | |||
| 40 | pub fn get_remote_name_by_url(git_repo: &Repository, url: &str) -> Result<String> { | ||
| 41 | let remotes = git_repo.remotes()?; | ||
| 42 | Ok(remotes | ||
| 43 | .iter() | ||
| 44 | .find(|r| { | ||
| 45 | if let Some(name) = r { | ||
| 46 | if let Some(remote_url) = git_repo.find_remote(name).unwrap().url() { | ||
| 47 | url == remote_url | ||
| 48 | } else { | ||
| 49 | false | ||
| 50 | } | ||
| 51 | } else { | ||
| 52 | false | ||
| 53 | } | ||
| 54 | }) | ||
| 55 | .context("could not find remote with matching url")? | ||
| 56 | .context("remote with matching url must be named")? | ||
| 57 | .to_string()) | ||
| 58 | } | ||
| 59 | |||
| 60 | pub fn get_oids_from_fetch_batch( | ||
| 61 | stdin: &Stdin, | ||
| 62 | initial_oid: &str, | ||
| 63 | initial_refstr: &str, | ||
| 64 | ) -> Result<HashMap<String, String>> { | ||
| 65 | let mut line = String::new(); | ||
| 66 | let mut batch = HashMap::new(); | ||
| 67 | batch.insert(initial_refstr.to_string(), initial_oid.to_string()); | ||
| 68 | loop { | ||
| 69 | let tokens = read_line(stdin, &mut line)?; | ||
| 70 | match tokens.as_slice() { | ||
| 71 | ["fetch", oid, refstr] => { | ||
| 72 | batch.insert((*refstr).to_string(), (*oid).to_string()); | ||
| 73 | } | ||
| 74 | [] => break, | ||
| 75 | _ => bail!( | ||
| 76 | "after a `fetch` command we are only expecting another fetch or an empty line" | ||
| 77 | ), | ||
| 78 | } | ||
| 79 | } | ||
| 80 | Ok(batch) | ||
| 81 | } | ||
| 82 | |||
| 83 | /// Read one line from stdin, and split it into tokens. | ||
| 84 | pub fn read_line<'a>(stdin: &io::Stdin, line: &'a mut String) -> io::Result<Vec<&'a str>> { | ||
| 85 | line.clear(); | ||
| 86 | |||
| 87 | let read = stdin.read_line(line)?; | ||
| 88 | if read == 0 { | ||
| 89 | return Ok(vec![]); | ||
| 90 | } | ||
| 91 | let line = line.trim(); | ||
| 92 | let tokens = line.split(' ').filter(|t| !t.is_empty()).collect(); | ||
| 93 | |||
| 94 | Ok(tokens) | ||
| 95 | } | ||
| 96 | |||
| 97 | pub async fn get_open_or_draft_proposals( | ||
| 98 | git_repo: &Repo, | ||
| 99 | repo_ref: &RepoRef, | ||
| 100 | ) -> Result<HashMap<EventId, (Event, Vec<Event>)>> { | ||
| 101 | let git_repo_path = git_repo.get_path()?; | ||
| 102 | let proposals: Vec<nostr::Event> = | ||
| 103 | get_proposals_and_revisions_from_cache(git_repo_path, repo_ref.coordinates()) | ||
| 104 | .await? | ||
| 105 | .iter() | ||
| 106 | .filter(|e| | ||
| 107 | // If we wanted to treat to list Pull Requests that revise a Patch we would do this: | ||
| 108 | // e.kind.eq(&KIND_PULL_REQUEST) || | ||
| 109 | !event_is_revision_root(e)) | ||
| 110 | .cloned() | ||
| 111 | .collect(); | ||
| 112 | |||
| 113 | let statuses: Vec<nostr::Event> = { | ||
| 114 | let mut statuses = get_events_from_local_cache( | ||
| 115 | git_repo_path, | ||
| 116 | vec![ | ||
| 117 | nostr::Filter::default() | ||
| 118 | .kinds(status_kinds().clone()) | ||
| 119 | .events(proposals.iter().map(|e| e.id)), | ||
| 120 | ], | ||
| 121 | ) | ||
| 122 | .await?; | ||
| 123 | statuses.sort_by_key(|e| e.created_at); | ||
| 124 | statuses.reverse(); | ||
| 125 | statuses | ||
| 126 | }; | ||
| 127 | let mut open_or_draft_proposals = HashMap::new(); | ||
| 128 | |||
| 129 | for proposal in &proposals { | ||
| 130 | let status = get_status(proposal, repo_ref, &statuses, &proposals); | ||
| 131 | if [Kind::GitStatusOpen, Kind::GitStatusDraft].contains(&status) { | ||
| 132 | if let Ok(commits_events) = get_all_proposal_patch_pr_pr_update_events_from_cache( | ||
| 133 | git_repo_path, | ||
| 134 | repo_ref, | ||
| 135 | &proposal.id, | ||
| 136 | ) | ||
| 137 | .await | ||
| 138 | { | ||
| 139 | if let Ok(most_recent_proposal_patch_chain) = | ||
| 140 | get_pr_tip_event_or_most_recent_patch_with_ancestors(commits_events.clone()) | ||
| 141 | { | ||
| 142 | open_or_draft_proposals.insert( | ||
| 143 | proposal.id, | ||
| 144 | (proposal.clone(), most_recent_proposal_patch_chain), | ||
| 145 | ); | ||
| 146 | } | ||
| 147 | } | ||
| 148 | } | ||
| 149 | } | ||
| 150 | Ok(open_or_draft_proposals) | ||
| 151 | } | ||
| 152 | |||
| 153 | pub async fn get_all_proposals( | ||
| 154 | git_repo: &Repo, | ||
| 155 | repo_ref: &RepoRef, | ||
| 156 | ) -> Result<HashMap<EventId, (Event, Vec<Event>)>> { | ||
| 157 | let git_repo_path = git_repo.get_path()?; | ||
| 158 | let proposals: Vec<nostr::Event> = | ||
| 159 | get_proposals_and_revisions_from_cache(git_repo_path, repo_ref.coordinates()) | ||
| 160 | .await? | ||
| 161 | .iter() | ||
| 162 | .filter(|e| | ||
| 163 | // If we wanted to treat to list Pull Requests that revise a Patch we would do this: | ||
| 164 | // e.kind.eq(&KIND_PULL_REQUEST) || | ||
| 165 | !event_is_revision_root(e)) | ||
| 166 | .cloned() | ||
| 167 | .collect(); | ||
| 168 | |||
| 169 | let mut all_proposals = HashMap::new(); | ||
| 170 | |||
| 171 | for proposal in proposals { | ||
| 172 | if let Ok(commits_events) = get_all_proposal_patch_pr_pr_update_events_from_cache( | ||
| 173 | git_repo_path, | ||
| 174 | repo_ref, | ||
| 175 | &proposal.id, | ||
| 176 | ) | ||
| 177 | .await | ||
| 178 | { | ||
| 179 | if let Ok(most_recent_proposal_patch_chain) = | ||
| 180 | get_pr_tip_event_or_most_recent_patch_with_ancestors(commits_events.clone()) | ||
| 181 | { | ||
| 182 | all_proposals.insert(proposal.id, (proposal, most_recent_proposal_patch_chain)); | ||
| 183 | } | ||
| 184 | } | ||
| 185 | } | ||
| 186 | Ok(all_proposals) | ||
| 187 | } | ||
| 188 | |||
| 189 | pub fn find_proposal_and_patches_by_branch_name<'a>( | ||
| 190 | refstr: &'a str, | ||
| 191 | proposals: &'a HashMap<EventId, (Event, Vec<Event>)>, | ||
| 192 | current_user: Option<&PublicKey>, | ||
| 193 | ) -> Option<(&'a EventId, &'a (Event, Vec<Event>))> { | ||
| 194 | proposals.iter().find(|(_, (proposal, _))| { | ||
| 195 | is_event_proposal_root_for_branch(proposal, refstr, current_user).unwrap_or(false) | ||
| 196 | }) | ||
| 197 | } | ||
| 198 | |||
| 199 | pub fn join_with_and<T: ToString>(items: &[T]) -> String { | ||
| 200 | match items.len() { | ||
| 201 | 0 => String::new(), | ||
| 202 | 1 => items[0].to_string(), | ||
| 203 | _ => { | ||
| 204 | let last_item = items.last().unwrap().to_string(); | ||
| 205 | let rest = &items[..items.len() - 1]; | ||
| 206 | format!( | ||
| 207 | "{} and {}", | ||
| 208 | rest.iter() | ||
| 209 | .map(std::string::ToString::to_string) | ||
| 210 | .collect::<Vec<_>>() | ||
| 211 | .join(", "), | ||
| 212 | last_item | ||
| 213 | ) | ||
| 214 | } | ||
| 215 | } | ||
| 216 | } | ||
| 217 | |||
| 218 | /// get an ordered vector of server protocols to attempt | ||
| 219 | pub fn get_read_protocols_to_try( | ||
| 220 | git_repo: &Repo, | ||
| 221 | server_url: &CloneUrl, | ||
| 222 | decoded_nostr_url: &NostrUrlDecoded, | ||
| 223 | is_grasp_server: bool, | ||
| 224 | ) -> Vec<ServerProtocol> { | ||
| 225 | if is_grasp_server { | ||
| 226 | if server_url.protocol() == ServerProtocol::Http { | ||
| 227 | vec![(ServerProtocol::UnauthHttp)] | ||
| 228 | } else { | ||
| 229 | vec![(ServerProtocol::UnauthHttps)] | ||
| 230 | } | ||
| 231 | } else if server_url.protocol() == ServerProtocol::Filesystem { | ||
| 232 | vec![(ServerProtocol::Filesystem)] | ||
| 233 | } else if let Some(protocol) = &decoded_nostr_url.protocol { | ||
| 234 | vec![protocol.clone()] | ||
| 235 | } else { | ||
| 236 | let mut list = if server_url.protocol() == ServerProtocol::Http { | ||
| 237 | vec![ | ||
| 238 | ServerProtocol::UnauthHttp, | ||
| 239 | ServerProtocol::Ssh, | ||
| 240 | // note: list and fetch stop here if ssh was authenticated | ||
| 241 | ServerProtocol::Http, | ||
| 242 | ] | ||
| 243 | } else if server_url.protocol() == ServerProtocol::Ftp { | ||
| 244 | vec![ServerProtocol::Ftp, ServerProtocol::Ssh] | ||
| 245 | } else if server_url.protocol() == ServerProtocol::Git { | ||
| 246 | vec![ | ||
| 247 | ServerProtocol::Git, | ||
| 248 | ServerProtocol::UnauthHttps, | ||
| 249 | ServerProtocol::Ssh, | ||
| 250 | // note: list and fetch stop here if ssh was authenticated | ||
| 251 | ServerProtocol::Https, | ||
| 252 | ] | ||
| 253 | } else { | ||
| 254 | vec![ | ||
| 255 | ServerProtocol::UnauthHttps, | ||
| 256 | ServerProtocol::Ssh, | ||
| 257 | // note: list and fetch stop here if ssh was authenticated | ||
| 258 | ServerProtocol::Https, | ||
| 259 | ] | ||
| 260 | }; | ||
| 261 | if let Some(protocol) = get_protocol_preference(git_repo, server_url, &Direction::Fetch) { | ||
| 262 | if let Some(pos) = list.iter().position(|p| *p == protocol) { | ||
| 263 | list.remove(pos); | ||
| 264 | list.insert(0, protocol); | ||
| 265 | } | ||
| 266 | } | ||
| 267 | list | ||
| 268 | } | ||
| 269 | } | ||
| 270 | |||
| 271 | /// get an ordered vector of server protocols to attempt | ||
| 272 | pub fn get_write_protocols_to_try( | ||
| 273 | git_repo: &Repo, | ||
| 274 | server_url: &CloneUrl, | ||
| 275 | decoded_nostr_url: &NostrUrlDecoded, | ||
| 276 | is_grasp_server: bool, | ||
| 277 | ) -> Vec<ServerProtocol> { | ||
| 278 | if is_grasp_server { | ||
| 279 | if server_url.protocol() == ServerProtocol::Http { | ||
| 280 | vec![(ServerProtocol::UnauthHttp)] | ||
| 281 | } else { | ||
| 282 | vec![(ServerProtocol::UnauthHttps)] | ||
| 283 | } | ||
| 284 | } else if server_url.protocol() == ServerProtocol::Filesystem { | ||
| 285 | vec![(ServerProtocol::Filesystem)] | ||
| 286 | } else if let Some(protocol) = &decoded_nostr_url.protocol { | ||
| 287 | vec![protocol.clone()] | ||
| 288 | } else { | ||
| 289 | let mut list = if server_url.protocol() == ServerProtocol::Http { | ||
| 290 | vec![ | ||
| 291 | ServerProtocol::Ssh, | ||
| 292 | // note: list and fetch stop here if ssh was authenticated | ||
| 293 | ServerProtocol::Http, | ||
| 294 | ] | ||
| 295 | } else if server_url.protocol() == ServerProtocol::Ftp { | ||
| 296 | vec![ServerProtocol::Ssh, ServerProtocol::Ftp] | ||
| 297 | } else if server_url.protocol() == ServerProtocol::Git { | ||
| 298 | vec![ | ||
| 299 | ServerProtocol::Ssh, | ||
| 300 | ServerProtocol::Git, | ||
| 301 | // note: list and fetch stop here if ssh was authenticated | ||
| 302 | ServerProtocol::Https, | ||
| 303 | ] | ||
| 304 | } else { | ||
| 305 | vec![ | ||
| 306 | ServerProtocol::Ssh, | ||
| 307 | // note: list and fetch stop here if ssh was authenticated | ||
| 308 | ServerProtocol::Https, | ||
| 309 | ] | ||
| 310 | }; | ||
| 311 | if let Some(protocol) = get_protocol_preference(git_repo, server_url, &Direction::Push) { | ||
| 312 | if let Some(pos) = list.iter().position(|p| *p == protocol) { | ||
| 313 | list.remove(pos); | ||
| 314 | list.insert(0, protocol); | ||
| 315 | } | ||
| 316 | } | ||
| 317 | |||
| 318 | list | ||
| 319 | } | ||
| 320 | } | ||
| 321 | |||
| 322 | #[derive(Debug, PartialEq)] | ||
| 323 | pub enum Direction { | ||
| 324 | Push, | ||
| 325 | Fetch, | ||
| 326 | } | ||
| 327 | impl fmt::Display for Direction { | ||
| 328 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
| 329 | match self { | ||
| 330 | Direction::Push => write!(f, "push"), | ||
| 331 | Direction::Fetch => write!(f, "fetch"), | ||
| 332 | } | ||
| 333 | } | ||
| 334 | } | ||
| 335 | |||
| 336 | pub fn get_protocol_preference( | ||
| 337 | git_repo: &Repo, | ||
| 338 | server_url: &CloneUrl, | ||
| 339 | direction: &Direction, | ||
| 340 | ) -> Option<ServerProtocol> { | ||
| 341 | let server_short_name = server_url.short_name(); | ||
| 342 | if let Ok(Some(list)) = | ||
| 343 | git_repo.get_git_config_item(format!("nostr.protocol-{direction}").as_str(), Some(false)) | ||
| 344 | { | ||
| 345 | for item in list.split(';') { | ||
| 346 | let pair = item.split(',').collect::<Vec<&str>>(); | ||
| 347 | if let Some(url) = pair.get(1) { | ||
| 348 | if *url == server_short_name { | ||
| 349 | if let Some(protocol) = pair.first() { | ||
| 350 | if let Ok(protocol) = ServerProtocol::from_str(protocol) { | ||
| 351 | return Some(protocol); | ||
| 352 | } | ||
| 353 | } | ||
| 354 | } | ||
| 355 | } | ||
| 356 | } | ||
| 357 | } | ||
| 358 | None | ||
| 359 | } | ||
| 360 | |||
| 361 | pub fn set_protocol_preference( | ||
| 362 | git_repo: &Repo, | ||
| 363 | protocol: &ServerProtocol, | ||
| 364 | server_url: &CloneUrl, | ||
| 365 | direction: &Direction, | ||
| 366 | ) -> Result<()> { | ||
| 367 | let server_short_name = server_url.short_name(); | ||
| 368 | let mut new = String::new(); | ||
| 369 | if let Some(list) = | ||
| 370 | git_repo.get_git_config_item(format!("nostr.protocol-{direction}").as_str(), Some(false))? | ||
| 371 | { | ||
| 372 | for item in list.split(';') { | ||
| 373 | let pair = item.split(',').collect::<Vec<&str>>(); | ||
| 374 | if let Some(url) = pair.get(1) { | ||
| 375 | if *url != server_short_name && !item.is_empty() { | ||
| 376 | new.push_str(format!("{item};").as_str()); | ||
| 377 | } | ||
| 378 | } | ||
| 379 | } | ||
| 380 | } | ||
| 381 | new.push_str(format!("{protocol},{server_short_name};").as_str()); | ||
| 382 | |||
| 383 | git_repo.save_git_config_item( | ||
| 384 | format!("nostr.protocol-{direction}").as_str(), | ||
| 385 | new.as_str(), | ||
| 386 | false, | ||
| 387 | ) | ||
| 388 | } | ||
| 389 | |||
| 390 | pub fn error_might_be_authentication_related(error: &anyhow::Error) -> bool { | ||
| 391 | let error_str = error.to_string(); | ||
| 392 | for s in [ | ||
| 393 | "no ssh keys found", | ||
| 394 | "invalid or unknown remote ssh hostkey", | ||
| 395 | "authentication", | ||
| 396 | "Permission", | ||
| 397 | "permission", | ||
| 398 | "not found", | ||
| 399 | ] { | ||
| 400 | if error_str.contains(s) { | ||
| 401 | return true; | ||
| 402 | } | ||
| 403 | } | ||
| 404 | false | ||
| 405 | } | ||
| 406 | |||
| 407 | #[cfg(test)] | ||
| 408 | mod tests { | ||
| 409 | use super::*; | ||
| 410 | mod join_with_and { | ||
| 411 | use super::*; | ||
| 412 | #[test] | ||
| 413 | fn test_empty() { | ||
| 414 | let items: Vec<&str> = vec![]; | ||
| 415 | assert_eq!(join_with_and(&items), ""); | ||
| 416 | } | ||
| 417 | |||
| 418 | #[test] | ||
| 419 | fn test_single_item() { | ||
| 420 | let items = vec!["apple"]; | ||
| 421 | assert_eq!(join_with_and(&items), "apple"); | ||
| 422 | } | ||
| 423 | |||
| 424 | #[test] | ||
| 425 | fn test_two_items() { | ||
| 426 | let items = vec!["apple", "banana"]; | ||
| 427 | assert_eq!(join_with_and(&items), "apple and banana"); | ||
| 428 | } | ||
| 429 | |||
| 430 | #[test] | ||
| 431 | fn test_three_items() { | ||
| 432 | let items = vec!["apple", "banana", "cherry"]; | ||
| 433 | assert_eq!(join_with_and(&items), "apple, banana and cherry"); | ||
| 434 | } | ||
| 435 | |||
| 436 | #[test] | ||
| 437 | fn test_four_items() { | ||
| 438 | let items = vec!["apple", "banana", "cherry", "date"]; | ||
| 439 | assert_eq!(join_with_and(&items), "apple, banana, cherry and date"); | ||
| 440 | } | ||
| 441 | |||
| 442 | #[test] | ||
| 443 | fn test_multiple_items() { | ||
| 444 | let items = vec!["one", "two", "three", "four", "five"]; | ||
| 445 | assert_eq!(join_with_and(&items), "one, two, three, four and five"); | ||
| 446 | } | ||
| 447 | } | ||
| 448 | } | ||