diff options
Diffstat (limited to 'src/bin/git_remote_nostr/utils.rs')
| -rw-r--r-- | src/bin/git_remote_nostr/utils.rs | 448 |
1 files changed, 0 insertions, 448 deletions
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 | } | ||