diff options
| author | DanConwayDev <DanConwayDev@protonmail.com> | 2025-07-28 14:10:03 +0100 |
|---|---|---|
| committer | DanConwayDev <DanConwayDev@protonmail.com> | 2025-07-28 14:10:03 +0100 |
| commit | caed1d751eb29d329119c1372c99a651980f42a4 (patch) | |
| tree | 469a3c1ba4681c209997e8f55dc5a7f7fd9baf74 | |
| parent | e89dbc142f5a0a517f197562f5f228681d9aed47 (diff) | |
| parent | ee50baf800f4cb46d17858ba87a3648bb084d8b9 (diff) | |
Merge branch 'add-ngit-sync-cmd'
| -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 | 319 | ||||
| -rw-r--r-- | src/bin/ngit/cli.rs | 3 | ||||
| -rw-r--r-- | src/bin/ngit/main.rs | 1 | ||||
| -rw-r--r-- | src/bin/ngit/sub_commands/mod.rs | 1 | ||||
| -rw-r--r-- | src/bin/ngit/sub_commands/sync.rs | 161 | ||||
| -rw-r--r-- | src/lib/list.rs | 159 | ||||
| -rw-r--r-- | src/lib/mod.rs | 3 | ||||
| -rw-r--r-- | src/lib/push.rs | 310 | ||||
| -rw-r--r-- | src/lib/utils.rs (renamed from src/bin/git_remote_nostr/utils.rs) | 5 |
12 files changed, 662 insertions, 476 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..4e0d760 100644 --- a/src/bin/git_remote_nostr/push.rs +++ b/src/bin/git_remote_nostr/push.rs | |||
| @@ -2,12 +2,10 @@ use core::str; | |||
| 2 | use std::{ | 2 | use std::{ |
| 3 | collections::{HashMap, HashSet}, | 3 | collections::{HashMap, HashSet}, |
| 4 | io::Stdin, | 4 | io::Stdin, |
| 5 | sync::{Arc, Mutex}, | 5 | sync::Arc, |
| 6 | time::Instant, | ||
| 7 | }; | 6 | }; |
| 8 | 7 | ||
| 9 | use anyhow::{Context, Result, anyhow, bail}; | 8 | use anyhow::{Context, Result, bail}; |
| 10 | use auth_git2::GitAuthenticator; | ||
| 11 | use client::{get_events_from_local_cache, get_state_from_cache, send_events, sign_event}; | 9 | use client::{get_events_from_local_cache, get_state_from_cache, send_events, sign_event}; |
| 12 | use console::Term; | 10 | use console::Term; |
| 13 | use git::{RepoActions, sha1_to_oid}; | 11 | use git::{RepoActions, sha1_to_oid}; |
| @@ -17,17 +15,18 @@ use git_events::{ | |||
| 17 | }; | 15 | }; |
| 18 | use git2::{Oid, Repository}; | 16 | use git2::{Oid, Repository}; |
| 19 | use ngit::{ | 17 | use ngit::{ |
| 20 | cli_interactor::count_lines_per_msg_vec, | ||
| 21 | client::{self, get_event_from_cache_by_id, sign_draft_event}, | 18 | client::{self, get_event_from_cache_by_id, sign_draft_event}, |
| 22 | git::{ | 19 | git::{self, nostr_url::NostrUrlDecoded}, |
| 23 | self, | ||
| 24 | nostr_url::{CloneUrl, NostrUrlDecoded}, | ||
| 25 | oid_to_shorthand_string, | ||
| 26 | }, | ||
| 27 | git_events::{self, KIND_PULL_REQUEST, event_to_cover_letter, get_event_root}, | 20 | git_events::{self, KIND_PULL_REQUEST, event_to_cover_letter, get_event_root}, |
| 21 | list::list_from_remotes, | ||
| 28 | login::{self, user::UserRef}, | 22 | login::{self, user::UserRef}, |
| 23 | push::{push_to_remote, push_to_remote_url}, | ||
| 29 | repo_ref::{self, get_repo_config_from_yaml, is_grasp_server, normalize_grasp_server_url}, | 24 | repo_ref::{self, get_repo_config_from_yaml, is_grasp_server, normalize_grasp_server_url}, |
| 30 | repo_state, | 25 | repo_state, |
| 26 | utils::{ | ||
| 27 | find_proposal_and_patches_by_branch_name, get_all_proposals, get_remote_name_by_url, | ||
| 28 | get_short_git_server_name, read_line, | ||
| 29 | }, | ||
| 31 | }; | 30 | }; |
| 32 | use nostr::{event::UnsignedEvent, nips::nip10::Marker}; | 31 | use nostr::{event::UnsignedEvent, nips::nip10::Marker}; |
| 33 | use nostr_sdk::{ | 32 | use nostr_sdk::{ |
| @@ -37,16 +36,7 @@ use nostr_sdk::{ | |||
| 37 | use repo_ref::RepoRef; | 36 | use repo_ref::RepoRef; |
| 38 | use repo_state::RepoState; | 37 | use repo_state::RepoState; |
| 39 | 38 | ||
| 40 | use crate::{ | 39 | 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 | 40 | ||
| 51 | #[allow(clippy::too_many_lines)] | 41 | #[allow(clippy::too_many_lines)] |
| 52 | #[allow(clippy::type_complexity)] | 42 | #[allow(clippy::type_complexity)] |
| @@ -590,295 +580,6 @@ async fn generate_patches_or_pr_event_or_pr_updates( | |||
| 590 | Ok(events) | 580 | Ok(events) |
| 591 | } | 581 | } |
| 592 | 582 | ||
| 593 | fn push_to_remote( | ||
| 594 | git_repo: &Repo, | ||
| 595 | git_server_url: &str, | ||
| 596 | decoded_nostr_url: &NostrUrlDecoded, | ||
| 597 | remote_refspecs: &[String], | ||
| 598 | term: &Term, | ||
| 599 | is_grasp_server: bool, | ||
| 600 | ) -> Result<()> { | ||
| 601 | let server_url = git_server_url.parse::<CloneUrl>()?; | ||
| 602 | let protocols_to_attempt = | ||
| 603 | get_write_protocols_to_try(git_repo, &server_url, decoded_nostr_url, is_grasp_server); | ||
| 604 | |||
| 605 | let mut failed_protocols = vec![]; | ||
| 606 | let mut success = false; | ||
| 607 | |||
| 608 | for protocol in &protocols_to_attempt { | ||
| 609 | term.write_line(format!("push: {} over {protocol}...", server_url.short_name(),).as_str())?; | ||
| 610 | |||
| 611 | let formatted_url = server_url.format_as(protocol, &decoded_nostr_url.user)?; | ||
| 612 | |||
| 613 | if let Err(error) = push_to_remote_url(git_repo, &formatted_url, remote_refspecs, term) { | ||
| 614 | term.write_line( | ||
| 615 | format!("push: {formatted_url} failed over {protocol}: {error}").as_str(), | ||
| 616 | )?; | ||
| 617 | failed_protocols.push(protocol); | ||
| 618 | } else { | ||
| 619 | success = true; | ||
| 620 | if !failed_protocols.is_empty() { | ||
| 621 | term.write_line(format!("push: succeeded over {protocol}").as_str())?; | ||
| 622 | let _ = set_protocol_preference(git_repo, protocol, &server_url, &Direction::Push); | ||
| 623 | } | ||
| 624 | break; | ||
| 625 | } | ||
| 626 | } | ||
| 627 | if success { | ||
| 628 | Ok(()) | ||
| 629 | } else { | ||
| 630 | let error = anyhow!( | ||
| 631 | "{} failed over {}{}", | ||
| 632 | server_url.short_name(), | ||
| 633 | join_with_and(&failed_protocols), | ||
| 634 | if decoded_nostr_url.protocol.is_some() { | ||
| 635 | " and nostr url contains protocol override so no other protocols were attempted" | ||
| 636 | } else { | ||
| 637 | "" | ||
| 638 | }, | ||
| 639 | ); | ||
| 640 | term.write_line(format!("push: {error}").as_str())?; | ||
| 641 | Err(error) | ||
| 642 | } | ||
| 643 | } | ||
| 644 | |||
| 645 | fn push_to_remote_url( | ||
| 646 | git_repo: &Repo, | ||
| 647 | git_server_url: &str, | ||
| 648 | remote_refspecs: &[String], | ||
| 649 | term: &Term, | ||
| 650 | ) -> Result<()> { | ||
| 651 | let git_config = git_repo.git_repo.config()?; | ||
| 652 | let mut git_server_remote = git_repo.git_repo.remote_anonymous(git_server_url)?; | ||
| 653 | let auth = GitAuthenticator::default(); | ||
| 654 | let mut push_options = git2::PushOptions::new(); | ||
| 655 | let mut remote_callbacks = git2::RemoteCallbacks::new(); | ||
| 656 | let push_reporter = Arc::new(Mutex::new(PushReporter::new(term))); | ||
| 657 | |||
| 658 | remote_callbacks.credentials(auth.credentials(&git_config)); | ||
| 659 | |||
| 660 | remote_callbacks.push_update_reference({ | ||
| 661 | let push_reporter = Arc::clone(&push_reporter); | ||
| 662 | move |name, error| { | ||
| 663 | let mut reporter = push_reporter.lock().unwrap(); | ||
| 664 | if let Some(error) = error { | ||
| 665 | let existing_lines = reporter.count_all_existing_lines(); | ||
| 666 | reporter.update_reference_errors.push(format!( | ||
| 667 | "WARNING: {} failed to push {name} error: {error}", | ||
| 668 | get_short_git_server_name(git_repo, git_server_url), | ||
| 669 | )); | ||
| 670 | reporter.write_all(existing_lines); | ||
| 671 | } | ||
| 672 | Ok(()) | ||
| 673 | } | ||
| 674 | }); | ||
| 675 | |||
| 676 | remote_callbacks.push_negotiation({ | ||
| 677 | let push_reporter = Arc::clone(&push_reporter); | ||
| 678 | move |updates| { | ||
| 679 | let mut reporter = push_reporter.lock().unwrap(); | ||
| 680 | let existing_lines = reporter.count_all_existing_lines(); | ||
| 681 | |||
| 682 | for update in updates { | ||
| 683 | let dst_refname = update | ||
| 684 | .dst_refname() | ||
| 685 | .unwrap_or("") | ||
| 686 | .replace("refs/heads/", "") | ||
| 687 | .replace("refs/tags/", "tags/"); | ||
| 688 | let msg = if update.dst().is_zero() { | ||
| 689 | format!("push: - [delete] {dst_refname}") | ||
| 690 | } else if update.src().is_zero() { | ||
| 691 | if update.dst_refname().unwrap_or("").contains("refs/tags") { | ||
| 692 | format!("push: * [new tag] {dst_refname}") | ||
| 693 | } else { | ||
| 694 | format!("push: * [new branch] {dst_refname}") | ||
| 695 | } | ||
| 696 | } else { | ||
| 697 | let force = remote_refspecs | ||
| 698 | .iter() | ||
| 699 | .any(|r| r.contains(&dst_refname) && r.contains('+')); | ||
| 700 | format!( | ||
| 701 | "push: {} {}..{} {} -> {dst_refname}", | ||
| 702 | if force { "+" } else { " " }, | ||
| 703 | oid_to_shorthand_string(update.src()).unwrap(), | ||
| 704 | oid_to_shorthand_string(update.dst()).unwrap(), | ||
| 705 | update | ||
| 706 | .src_refname() | ||
| 707 | .unwrap_or("") | ||
| 708 | .replace("refs/heads/", "") | ||
| 709 | .replace("refs/tags/", "tags/"), | ||
| 710 | ) | ||
| 711 | }; | ||
| 712 | // other possibilities will result in push to fail but better reporting is | ||
| 713 | // needed: | ||
| 714 | // deleting a non-existant branch: | ||
| 715 | // ! [remote rejected] <old-branch-name> -> <old-branch-name> (not found) | ||
| 716 | // adding a branch that already exists: | ||
| 717 | // ! [remote rejected] <new-branch-name> -> <new-branch-name> (already exists) | ||
| 718 | // pushing without non-fast-forward without force: | ||
| 719 | // ! [rejected] <branch-name> -> <branch-name> (non-fast-forward) | ||
| 720 | reporter.negotiation.push(msg); | ||
| 721 | } | ||
| 722 | reporter.write_all(existing_lines); | ||
| 723 | Ok(()) | ||
| 724 | } | ||
| 725 | }); | ||
| 726 | |||
| 727 | remote_callbacks.push_transfer_progress({ | ||
| 728 | let push_reporter = Arc::clone(&push_reporter); | ||
| 729 | #[allow(clippy::cast_precision_loss)] | ||
| 730 | move |current, total, bytes| { | ||
| 731 | let mut reporter = push_reporter.lock().unwrap(); | ||
| 732 | reporter.process_transfer_progress_update(current, total, bytes); | ||
| 733 | } | ||
| 734 | }); | ||
| 735 | |||
| 736 | remote_callbacks.sideband_progress({ | ||
| 737 | let push_reporter = Arc::clone(&push_reporter); | ||
| 738 | move |data| { | ||
| 739 | let mut reporter = push_reporter.lock().unwrap(); | ||
| 740 | reporter.process_remote_msg(data); | ||
| 741 | true | ||
| 742 | } | ||
| 743 | }); | ||
| 744 | push_options.remote_callbacks(remote_callbacks); | ||
| 745 | git_server_remote.push(remote_refspecs, Some(&mut push_options))?; | ||
| 746 | let _ = git_server_remote.disconnect(); | ||
| 747 | Ok(()) | ||
| 748 | } | ||
| 749 | |||
| 750 | #[allow(clippy::cast_precision_loss)] | ||
| 751 | #[allow(clippy::float_cmp)] | ||
| 752 | #[allow(clippy::needless_pass_by_value)] | ||
| 753 | fn report_on_transfer_progress( | ||
| 754 | current: usize, | ||
| 755 | total: usize, | ||
| 756 | bytes: usize, | ||
| 757 | start_time: &Instant, | ||
| 758 | end_time: Option<&Instant>, | ||
| 759 | ) -> Option<String> { | ||
| 760 | if total == 0 { | ||
| 761 | return None; | ||
| 762 | } | ||
| 763 | let percentage = ((current as f64 / total as f64) * 100.0) | ||
| 764 | // always round down because 100% complete is misleading when its not complete | ||
| 765 | .floor(); | ||
| 766 | let (size, unit) = if bytes as f64 >= (1024.0 * 1024.0) { | ||
| 767 | (bytes as f64 / (1024.0 * 1024.0), "MiB") | ||
| 768 | } else { | ||
| 769 | (bytes as f64 / 1024.0, "KiB") | ||
| 770 | }; | ||
| 771 | let speed = { | ||
| 772 | let duration = if let Some(end_time) = end_time { | ||
| 773 | (*end_time - *start_time).as_millis() as f64 | ||
| 774 | } else { | ||
| 775 | start_time.elapsed().as_millis() as f64 | ||
| 776 | }; | ||
| 777 | |||
| 778 | if duration > 0.0 { | ||
| 779 | (bytes as f64 / (1024.0 * 1024.0)) / (duration / 1000.0) // Convert bytes to MiB and milliseconds to seconds | ||
| 780 | } else { | ||
| 781 | 0.0 | ||
| 782 | } | ||
| 783 | }; | ||
| 784 | |||
| 785 | Some(format!( | ||
| 786 | "push: Writing objects: {percentage}% ({current}/{total}) {size:.2} {unit} | {speed:.2} MiB/s{}", | ||
| 787 | if current == total { ", done." } else { "" }, | ||
| 788 | )) | ||
| 789 | } | ||
| 790 | |||
| 791 | struct PushReporter<'a> { | ||
| 792 | remote_msgs: Vec<String>, | ||
| 793 | negotiation: Vec<String>, | ||
| 794 | transfer_progress_msgs: Vec<String>, | ||
| 795 | update_reference_errors: Vec<String>, | ||
| 796 | term: &'a console::Term, | ||
| 797 | start_time: Option<Instant>, | ||
| 798 | end_time: Option<Instant>, | ||
| 799 | } | ||
| 800 | impl<'a> PushReporter<'a> { | ||
| 801 | fn new(term: &'a console::Term) -> Self { | ||
| 802 | Self { | ||
| 803 | remote_msgs: vec![], | ||
| 804 | negotiation: vec![], | ||
| 805 | transfer_progress_msgs: vec![], | ||
| 806 | update_reference_errors: vec![], | ||
| 807 | term, | ||
| 808 | start_time: None, | ||
| 809 | end_time: None, | ||
| 810 | } | ||
| 811 | } | ||
| 812 | fn write_all(&self, lines_to_clear: usize) { | ||
| 813 | let _ = self.term.clear_last_lines(lines_to_clear); | ||
| 814 | for msg in &self.remote_msgs { | ||
| 815 | let _ = self.term.write_line(format!("remote: {msg}").as_str()); | ||
| 816 | } | ||
| 817 | for msg in &self.negotiation { | ||
| 818 | let _ = self.term.write_line(msg); | ||
| 819 | } | ||
| 820 | for msg in &self.transfer_progress_msgs { | ||
| 821 | let _ = self.term.write_line(msg); | ||
| 822 | } | ||
| 823 | for msg in &self.update_reference_errors { | ||
| 824 | let _ = self.term.write_line(msg); | ||
| 825 | } | ||
| 826 | } | ||
| 827 | |||
| 828 | fn count_all_existing_lines(&self) -> usize { | ||
| 829 | let width = self.term.size().1; | ||
| 830 | count_lines_per_msg_vec(width, &self.remote_msgs, "remote: ".len()) | ||
| 831 | + count_lines_per_msg_vec(width, &self.negotiation, 0) | ||
| 832 | + count_lines_per_msg_vec(width, &self.transfer_progress_msgs, 0) | ||
| 833 | + count_lines_per_msg_vec(width, &self.update_reference_errors, 0) | ||
| 834 | } | ||
| 835 | fn process_remote_msg(&mut self, data: &[u8]) { | ||
| 836 | if let Ok(data) = str::from_utf8(data) { | ||
| 837 | let data = data | ||
| 838 | .split(['\n', '\r']) | ||
| 839 | .map(str::trim) | ||
| 840 | .filter(|line| !line.trim().is_empty()) | ||
| 841 | .collect::<Vec<&str>>(); | ||
| 842 | for data in data { | ||
| 843 | let existing_lines = self.count_all_existing_lines(); | ||
| 844 | let msg = data.to_string(); | ||
| 845 | if let Some(last) = self.remote_msgs.last() { | ||
| 846 | if (last.contains('%') && !last.contains("100%")) | ||
| 847 | || last == &msg.replace(", done.", "") | ||
| 848 | { | ||
| 849 | self.remote_msgs.pop(); | ||
| 850 | self.remote_msgs.push(msg); | ||
| 851 | } else { | ||
| 852 | self.remote_msgs.push(msg); | ||
| 853 | } | ||
| 854 | } else { | ||
| 855 | self.remote_msgs.push(msg); | ||
| 856 | } | ||
| 857 | self.write_all(existing_lines); | ||
| 858 | } | ||
| 859 | } | ||
| 860 | } | ||
| 861 | fn process_transfer_progress_update(&mut self, current: usize, total: usize, bytes: usize) { | ||
| 862 | if self.start_time.is_none() { | ||
| 863 | self.start_time = Some(Instant::now()); | ||
| 864 | } | ||
| 865 | if let Some(report) = report_on_transfer_progress( | ||
| 866 | current, | ||
| 867 | total, | ||
| 868 | bytes, | ||
| 869 | &self.start_time.unwrap(), | ||
| 870 | self.end_time.as_ref(), | ||
| 871 | ) { | ||
| 872 | let existing_lines = self.count_all_existing_lines(); | ||
| 873 | if report.contains("100%") { | ||
| 874 | self.end_time = Some(Instant::now()); | ||
| 875 | } | ||
| 876 | self.transfer_progress_msgs = vec![report]; | ||
| 877 | self.write_all(existing_lines); | ||
| 878 | } | ||
| 879 | } | ||
| 880 | } | ||
| 881 | |||
| 882 | type HashMapUrlRefspecs = HashMap<String, Vec<String>>; | 583 | type HashMapUrlRefspecs = HashMap<String, Vec<String>>; |
| 883 | 584 | ||
| 884 | #[allow(clippy::too_many_lines)] | 585 | #[allow(clippy::too_many_lines)] |
diff --git a/src/bin/ngit/cli.rs b/src/bin/ngit/cli.rs index 843c904..76874c3 100644 --- a/src/bin/ngit/cli.rs +++ b/src/bin/ngit/cli.rs | |||
| @@ -96,6 +96,9 @@ pub enum Commands { | |||
| 96 | Send(sub_commands::send::SubCommandArgs), | 96 | Send(sub_commands::send::SubCommandArgs), |
| 97 | /// list PRs; checkout, apply or download selected | 97 | /// list PRs; checkout, apply or download selected |
| 98 | List, | 98 | List, |
| 99 | /// update repo git servers to reflect nostr state (add, update or delete | ||
| 100 | /// remote refs) | ||
| 101 | Sync(sub_commands::sync::SubCommandArgs), | ||
| 99 | /// login, logout or export keys | 102 | /// login, logout or export keys |
| 100 | Account(AccountSubCommandArgs), | 103 | Account(AccountSubCommandArgs), |
| 101 | } | 104 | } |
diff --git a/src/bin/ngit/main.rs b/src/bin/ngit/main.rs index f896e97..f07203a 100644 --- a/src/bin/ngit/main.rs +++ b/src/bin/ngit/main.rs | |||
| @@ -32,6 +32,7 @@ async fn main() -> Result<()> { | |||
| 32 | Commands::Init(args) => sub_commands::init::launch(&cli, args).await, | 32 | Commands::Init(args) => sub_commands::init::launch(&cli, args).await, |
| 33 | Commands::List => sub_commands::list::launch().await, | 33 | Commands::List => sub_commands::list::launch().await, |
| 34 | Commands::Send(args) => sub_commands::send::launch(&cli, args, false).await, | 34 | Commands::Send(args) => sub_commands::send::launch(&cli, args, false).await, |
| 35 | Commands::Sync(args) => sub_commands::sync::launch(args).await, | ||
| 35 | } | 36 | } |
| 36 | } else { | 37 | } else { |
| 37 | // Handle the case where no command is provided | 38 | // Handle the case where no command is provided |
diff --git a/src/bin/ngit/sub_commands/mod.rs b/src/bin/ngit/sub_commands/mod.rs index b59b88f..b2e7c9a 100644 --- a/src/bin/ngit/sub_commands/mod.rs +++ b/src/bin/ngit/sub_commands/mod.rs | |||
| @@ -4,3 +4,4 @@ pub mod list; | |||
| 4 | pub mod login; | 4 | pub mod login; |
| 5 | pub mod logout; | 5 | pub mod logout; |
| 6 | pub mod send; | 6 | pub mod send; |
| 7 | pub mod sync; | ||
diff --git a/src/bin/ngit/sub_commands/sync.rs b/src/bin/ngit/sub_commands/sync.rs new file mode 100644 index 0000000..c1a3484 --- /dev/null +++ b/src/bin/ngit/sub_commands/sync.rs | |||
| @@ -0,0 +1,161 @@ | |||
| 1 | use anyhow::{Context, Result}; | ||
| 2 | use ngit::{ | ||
| 3 | client::{ | ||
| 4 | Client, Connect, Params, fetching_with_report, get_repo_ref_from_cache, | ||
| 5 | get_state_from_cache, | ||
| 6 | }, | ||
| 7 | git::{Repo, RepoActions}, | ||
| 8 | list::{get_ahead_behind, list_from_remotes}, | ||
| 9 | push::push_to_remote, | ||
| 10 | repo_ref::get_repo_coordinates_when_remote_unknown, | ||
| 11 | utils::get_short_git_server_name, | ||
| 12 | }; | ||
| 13 | |||
| 14 | #[derive(Debug, clap::Args)] | ||
| 15 | pub struct SubCommandArgs { | ||
| 16 | /// force push updates and delete refs from non-grasp git servers | ||
| 17 | #[arg(long, action)] | ||
| 18 | force: bool, | ||
| 19 | } | ||
| 20 | |||
| 21 | #[allow(clippy::too_many_lines)] | ||
| 22 | pub async fn launch(args: &SubCommandArgs) -> Result<()> { | ||
| 23 | let git_repo = Repo::discover().context("failed to find a git repository")?; | ||
| 24 | let git_repo_path = git_repo.get_path()?; | ||
| 25 | |||
| 26 | let client = Client::new(Params::with_git_config_relay_defaults(&Some(&git_repo))); | ||
| 27 | |||
| 28 | let (nostr_remote_name, decoded_nostr_url) = git_repo | ||
| 29 | .get_first_nostr_remote_when_in_ngit_binary() | ||
| 30 | .await.context("failed to list git remotes")? | ||
| 31 | .context("no `nostr://` remote detected. `ngit sync` must be run from a repo with a nostr remote")?; | ||
| 32 | |||
| 33 | let repo_coordinate = get_repo_coordinates_when_remote_unknown(&git_repo, &client).await?; | ||
| 34 | |||
| 35 | let _ = fetching_with_report(git_repo_path, &client, &repo_coordinate).await?; | ||
| 36 | |||
| 37 | // TODO push announcement event, then state event to grasps | ||
| 38 | |||
| 39 | let repo_ref = get_repo_ref_from_cache(Some(git_repo_path), &repo_coordinate).await?; | ||
| 40 | |||
| 41 | let nostr_state = get_state_from_cache(Some(git_repo_path), &repo_ref).await?; | ||
| 42 | |||
| 43 | let term = console::Term::stderr(); | ||
| 44 | |||
| 45 | let remote_states = list_from_remotes( | ||
| 46 | &term, | ||
| 47 | &git_repo, | ||
| 48 | &repo_ref.git_server, | ||
| 49 | &repo_ref.to_nostr_git_url(&None), | ||
| 50 | &repo_ref.grasp_servers(), | ||
| 51 | ); | ||
| 52 | |||
| 53 | for (url, (remote_state, is_grasp_server)) in &remote_states { | ||
| 54 | let remote_name = get_short_git_server_name(&git_repo, url); | ||
| 55 | let mut refspecs = vec![]; | ||
| 56 | // delete ref from remote | ||
| 57 | let mut not_deleted = vec![]; | ||
| 58 | for remote_ref_name in remote_state.keys() { | ||
| 59 | if (!remote_ref_name.starts_with("refs/heads/pr/") | ||
| 60 | && (remote_ref_name.starts_with("refs/heads/") | ||
| 61 | || remote_ref_name.starts_with("refs/tags/"))) | ||
| 62 | && !nostr_state | ||
| 63 | .state | ||
| 64 | .keys() | ||
| 65 | .any(|nostr_ref| nostr_ref.eq(remote_ref_name)) | ||
| 66 | { | ||
| 67 | if *is_grasp_server || args.force { | ||
| 68 | // delete branches / tags not on nostr | ||
| 69 | refspecs.push(format!(":{remote_ref_name}")); | ||
| 70 | } else { | ||
| 71 | not_deleted.push(remote_ref_name); | ||
| 72 | } | ||
| 73 | } | ||
| 74 | } | ||
| 75 | // add or update ref on remote | ||
| 76 | let mut not_updated = vec![]; | ||
| 77 | for nostr_ref_name in nostr_state.state.keys() { | ||
| 78 | if nostr_ref_name.starts_with("refs/heads/") | ||
| 79 | || nostr_ref_name.starts_with("refs/tags/") | ||
| 80 | || !nostr_ref_name.starts_with("refs/heads/pr/") | ||
| 81 | { | ||
| 82 | // ensure nostr_state only supports refs/heads and refs/tags/ | ||
| 83 | // and not refs/heads/prs/* | ||
| 84 | } else if let Some(remote_ref_value) = remote_state.get(nostr_ref_name) { | ||
| 85 | // update ref | ||
| 86 | let force_required = { | ||
| 87 | if let Ok((ahead, _)) = | ||
| 88 | get_ahead_behind(&git_repo, nostr_ref_name, remote_ref_value) | ||
| 89 | { | ||
| 90 | !ahead.is_empty() | ||
| 91 | } else { | ||
| 92 | true | ||
| 93 | } | ||
| 94 | }; | ||
| 95 | if nostr_state | ||
| 96 | .state | ||
| 97 | .get(nostr_ref_name) | ||
| 98 | .is_none_or(|nostr_ref_value| nostr_ref_value.eq(remote_ref_value)) | ||
| 99 | { | ||
| 100 | // no action if ref in sync | ||
| 101 | } else if remote_ref_value.starts_with("ref ") && !(args.force || *is_grasp_server) | ||
| 102 | { | ||
| 103 | // dont try and sync push symbolic refs | ||
| 104 | } else if !force_required { | ||
| 105 | refspecs.push(format!( | ||
| 106 | "refs/remotes/{nostr_remote_name}/{nostr_ref_name}:{nostr_ref_name}", | ||
| 107 | )); | ||
| 108 | } else if *is_grasp_server || args.force { | ||
| 109 | refspecs.push(format!( | ||
| 110 | "+refs/remotes/{nostr_remote_name}/{nostr_ref_name}:{nostr_ref_name}", | ||
| 111 | )); | ||
| 112 | } else { | ||
| 113 | not_updated.push(nostr_ref_name); | ||
| 114 | } | ||
| 115 | } else { | ||
| 116 | // add missing refs | ||
| 117 | refspecs.push(format!( | ||
| 118 | "refs/remotes/{nostr_remote_name}/{nostr_ref_name}:{nostr_ref_name}", | ||
| 119 | )); | ||
| 120 | } | ||
| 121 | } | ||
| 122 | |||
| 123 | if refspecs.is_empty() { | ||
| 124 | if !not_updated.is_empty() || !not_deleted.is_empty() { | ||
| 125 | term.write_line(&format!("{remote_name} in sync excluding"))?; | ||
| 126 | } else { | ||
| 127 | term.write_line(&format!("{remote_name} already in sync"))?; | ||
| 128 | } | ||
| 129 | // report already in sync | ||
| 130 | } else if let Err(error) = push_to_remote( | ||
| 131 | &git_repo, | ||
| 132 | url, | ||
| 133 | &decoded_nostr_url, | ||
| 134 | &refspecs, | ||
| 135 | &term, | ||
| 136 | *is_grasp_server, | ||
| 137 | ) { | ||
| 138 | term.write_line(&format!( | ||
| 139 | "error pushing updates to {remote_name}: error: {error}" | ||
| 140 | ))?; | ||
| 141 | } else if *is_grasp_server || args.force { | ||
| 142 | term.write_line(&format!("{remote_name} sync completed"))?; | ||
| 143 | // TODO we only know if there was an error but not if it | ||
| 144 | // rejected any updates | ||
| 145 | } else { | ||
| 146 | // we should report on refs not force pushed | ||
| 147 | term.write_line(&format!("{remote_name} sync completed"))?; | ||
| 148 | } | ||
| 149 | for name in ¬_deleted { | ||
| 150 | term.write_line(&format!(" - {name} not deleted"))?; | ||
| 151 | } | ||
| 152 | for name in ¬_updated { | ||
| 153 | term.write_line(&format!(" - {name} not updated due to conflicts"))?; | ||
| 154 | } | ||
| 155 | if !not_updated.is_empty() || !not_deleted.is_empty() { | ||
| 156 | term.write_line("run `ngit sync --force` to delete refs or overwrite conflicts and potentially lose work")?; | ||
| 157 | } | ||
| 158 | } | ||
| 159 | |||
| 160 | Ok(()) | ||
| 161 | } | ||
diff --git a/src/lib/list.rs b/src/lib/list.rs new file mode 100644 index 0000000..b940546 --- /dev/null +++ b/src/lib/list.rs | |||
| @@ -0,0 +1,159 @@ | |||
| 1 | use std::collections::HashMap; | ||
| 2 | |||
| 3 | use anyhow::{Result, anyhow}; | ||
| 4 | use auth_git2::GitAuthenticator; | ||
| 5 | use nostr::hashes::sha1::Hash as Sha1Hash; | ||
| 6 | |||
| 7 | use crate::{ | ||
| 8 | git::{ | ||
| 9 | Repo, RepoActions, | ||
| 10 | nostr_url::{CloneUrl, NostrUrlDecoded, ServerProtocol}, | ||
| 11 | }, | ||
| 12 | repo_ref::is_grasp_server, | ||
| 13 | utils::{Direction, get_read_protocols_to_try, join_with_and, set_protocol_preference}, | ||
| 14 | }; | ||
| 15 | |||
| 16 | pub fn list_from_remotes( | ||
| 17 | term: &console::Term, | ||
| 18 | git_repo: &Repo, | ||
| 19 | git_servers: &Vec<String>, | ||
| 20 | decoded_nostr_url: &NostrUrlDecoded, | ||
| 21 | grasp_servers: &[String], | ||
| 22 | ) -> HashMap<String, (HashMap<String, String>, bool)> { | ||
| 23 | let mut remote_states = HashMap::new(); | ||
| 24 | let mut errors = HashMap::new(); | ||
| 25 | for url in git_servers { | ||
| 26 | let is_grasp_server = is_grasp_server(url, grasp_servers); | ||
| 27 | match list_from_remote(term, git_repo, url, decoded_nostr_url, is_grasp_server) { | ||
| 28 | Err(error) => { | ||
| 29 | errors.insert(url, error); | ||
| 30 | } | ||
| 31 | Ok(state) => { | ||
| 32 | remote_states.insert(url.to_string(), (state, is_grasp_server)); | ||
| 33 | } | ||
| 34 | } | ||
| 35 | } | ||
| 36 | remote_states | ||
| 37 | } | ||
| 38 | |||
| 39 | pub fn list_from_remote( | ||
| 40 | term: &console::Term, | ||
| 41 | git_repo: &Repo, | ||
| 42 | git_server_url: &str, | ||
| 43 | decoded_nostr_url: &NostrUrlDecoded, | ||
| 44 | is_grasp_server: bool, | ||
| 45 | ) -> Result<HashMap<String, String>> { | ||
| 46 | let server_url = git_server_url.parse::<CloneUrl>()?; | ||
| 47 | let protocols_to_attempt = | ||
| 48 | get_read_protocols_to_try(git_repo, &server_url, decoded_nostr_url, is_grasp_server); | ||
| 49 | |||
| 50 | let mut failed_protocols = vec![]; | ||
| 51 | let mut remote_state: Option<HashMap<String, String>> = None; | ||
| 52 | |||
| 53 | for protocol in &protocols_to_attempt { | ||
| 54 | term.write_line( | ||
| 55 | format!( | ||
| 56 | "fetching {} ref list over {protocol}...", | ||
| 57 | server_url.short_name(), | ||
| 58 | ) | ||
| 59 | .as_str(), | ||
| 60 | )?; | ||
| 61 | |||
| 62 | let formatted_url = server_url.format_as(protocol, &decoded_nostr_url.user)?; | ||
| 63 | let res = list_from_remote_url( | ||
| 64 | git_repo, | ||
| 65 | &formatted_url, | ||
| 66 | [ServerProtocol::UnauthHttps, ServerProtocol::UnauthHttp].contains(protocol), | ||
| 67 | term, | ||
| 68 | ); | ||
| 69 | |||
| 70 | match res { | ||
| 71 | Ok(state) => { | ||
| 72 | remote_state = Some(state); | ||
| 73 | term.clear_last_lines(1)?; | ||
| 74 | if !failed_protocols.is_empty() { | ||
| 75 | term.write_line( | ||
| 76 | format!( | ||
| 77 | "list: succeeded over {protocol} from {}", | ||
| 78 | server_url.short_name(), | ||
| 79 | ) | ||
| 80 | .as_str(), | ||
| 81 | )?; | ||
| 82 | let _ = | ||
| 83 | set_protocol_preference(git_repo, protocol, &server_url, &Direction::Fetch); | ||
| 84 | } | ||
| 85 | break; | ||
| 86 | } | ||
| 87 | Err(error) => { | ||
| 88 | term.clear_last_lines(1)?; | ||
| 89 | term.write_line( | ||
| 90 | format!("list: {formatted_url} failed over {protocol}: {error}").as_str(), | ||
| 91 | )?; | ||
| 92 | failed_protocols.push(protocol); | ||
| 93 | } | ||
| 94 | } | ||
| 95 | } | ||
| 96 | if let Some(remote_state) = remote_state { | ||
| 97 | if failed_protocols.is_empty() { | ||
| 98 | term.clear_last_lines(1)?; | ||
| 99 | } | ||
| 100 | Ok(remote_state) | ||
| 101 | } else { | ||
| 102 | let error = anyhow!( | ||
| 103 | "{} failed over {}{}", | ||
| 104 | server_url.short_name(), | ||
| 105 | join_with_and(&failed_protocols), | ||
| 106 | if decoded_nostr_url.protocol.is_some() { | ||
| 107 | " and nostr url contains protocol override so no other protocols were attempted" | ||
| 108 | } else { | ||
| 109 | "" | ||
| 110 | }, | ||
| 111 | ); | ||
| 112 | term.write_line(format!("list: {error}").as_str())?; | ||
| 113 | Err(error) | ||
| 114 | } | ||
| 115 | } | ||
| 116 | |||
| 117 | fn list_from_remote_url( | ||
| 118 | git_repo: &Repo, | ||
| 119 | git_server_remote_url: &str, | ||
| 120 | dont_authenticate: bool, | ||
| 121 | term: &console::Term, | ||
| 122 | ) -> Result<HashMap<String, String>> { | ||
| 123 | let git_config = git_repo.git_repo.config()?; | ||
| 124 | |||
| 125 | let mut git_server_remote = git_repo.git_repo.remote_anonymous(git_server_remote_url)?; | ||
| 126 | // authentication may be required | ||
| 127 | let auth = GitAuthenticator::default(); | ||
| 128 | let mut remote_callbacks = git2::RemoteCallbacks::new(); | ||
| 129 | if !dont_authenticate { | ||
| 130 | remote_callbacks.credentials(auth.credentials(&git_config)); | ||
| 131 | } | ||
| 132 | term.write_line("list: connecting...")?; | ||
| 133 | git_server_remote.connect_auth(git2::Direction::Fetch, Some(remote_callbacks), None)?; | ||
| 134 | term.clear_last_lines(1)?; | ||
| 135 | let mut state = HashMap::new(); | ||
| 136 | for head in git_server_remote.list()? { | ||
| 137 | if let Some(symbolic_reference) = head.symref_target() { | ||
| 138 | state.insert( | ||
| 139 | head.name().to_string(), | ||
| 140 | format!("ref: {symbolic_reference}"), | ||
| 141 | ); | ||
| 142 | // ignore dereferenced tags | ||
| 143 | } else if !head.name().to_string().ends_with("^{}") { | ||
| 144 | state.insert(head.name().to_string(), head.oid().to_string()); | ||
| 145 | } | ||
| 146 | } | ||
| 147 | git_server_remote.disconnect()?; | ||
| 148 | Ok(state) | ||
| 149 | } | ||
| 150 | |||
| 151 | pub fn get_ahead_behind( | ||
| 152 | git_repo: &Repo, | ||
| 153 | base_ref_or_oid: &str, | ||
| 154 | latest_ref_or_oid: &str, | ||
| 155 | ) -> Result<(Vec<Sha1Hash>, Vec<Sha1Hash>)> { | ||
| 156 | let base = git_repo.get_commit_or_tip_of_reference(base_ref_or_oid)?; | ||
| 157 | let latest = git_repo.get_commit_or_tip_of_reference(latest_ref_or_oid)?; | ||
| 158 | git_repo.get_commits_ahead_behind(&base, &latest) | ||
| 159 | } | ||
diff --git a/src/lib/mod.rs b/src/lib/mod.rs index 7c7bd6a..265dd6b 100644 --- a/src/lib/mod.rs +++ b/src/lib/mod.rs | |||
| @@ -2,9 +2,12 @@ pub mod cli_interactor; | |||
| 2 | pub mod client; | 2 | pub mod client; |
| 3 | pub mod git; | 3 | pub mod git; |
| 4 | pub mod git_events; | 4 | pub mod git_events; |
| 5 | pub mod list; | ||
| 5 | pub mod login; | 6 | pub mod login; |
| 7 | pub mod push; | ||
| 6 | pub mod repo_ref; | 8 | pub mod repo_ref; |
| 7 | pub mod repo_state; | 9 | pub mod repo_state; |
| 10 | pub mod utils; | ||
| 8 | 11 | ||
| 9 | use anyhow::{Result, anyhow}; | 12 | use anyhow::{Result, anyhow}; |
| 10 | use directories::ProjectDirs; | 13 | use directories::ProjectDirs; |
diff --git a/src/lib/push.rs b/src/lib/push.rs new file mode 100644 index 0000000..0d0ec93 --- /dev/null +++ b/src/lib/push.rs | |||
| @@ -0,0 +1,310 @@ | |||
| 1 | use std::{ | ||
| 2 | sync::{Arc, Mutex}, | ||
| 3 | time::Instant, | ||
| 4 | }; | ||
| 5 | |||
| 6 | use anyhow::{Result, anyhow}; | ||
| 7 | use auth_git2::GitAuthenticator; | ||
| 8 | use console::Term; | ||
| 9 | |||
| 10 | use crate::{ | ||
| 11 | cli_interactor::count_lines_per_msg_vec, | ||
| 12 | git::{ | ||
| 13 | Repo, | ||
| 14 | nostr_url::{CloneUrl, NostrUrlDecoded}, | ||
| 15 | oid_to_shorthand_string, | ||
| 16 | }, | ||
| 17 | utils::{ | ||
| 18 | Direction, get_short_git_server_name, get_write_protocols_to_try, join_with_and, | ||
| 19 | set_protocol_preference, | ||
| 20 | }, | ||
| 21 | }; | ||
| 22 | |||
| 23 | pub fn push_to_remote( | ||
| 24 | git_repo: &Repo, | ||
| 25 | git_server_url: &str, | ||
| 26 | decoded_nostr_url: &NostrUrlDecoded, | ||
| 27 | remote_refspecs: &[String], | ||
| 28 | term: &Term, | ||
| 29 | is_grasp_server: bool, | ||
| 30 | ) -> Result<()> { | ||
| 31 | let server_url = git_server_url.parse::<CloneUrl>()?; | ||
| 32 | let protocols_to_attempt = | ||
| 33 | get_write_protocols_to_try(git_repo, &server_url, decoded_nostr_url, is_grasp_server); | ||
| 34 | |||
| 35 | let mut failed_protocols = vec![]; | ||
| 36 | let mut success = false; | ||
| 37 | |||
| 38 | for protocol in &protocols_to_attempt { | ||
| 39 | term.write_line(format!("push: {} over {protocol}...", server_url.short_name(),).as_str())?; | ||
| 40 | |||
| 41 | let formatted_url = server_url.format_as(protocol, &decoded_nostr_url.user)?; | ||
| 42 | |||
| 43 | if let Err(error) = push_to_remote_url(git_repo, &formatted_url, remote_refspecs, term) { | ||
| 44 | term.write_line( | ||
| 45 | format!("push: {formatted_url} failed over {protocol}: {error}").as_str(), | ||
| 46 | )?; | ||
| 47 | failed_protocols.push(protocol); | ||
| 48 | } else { | ||
| 49 | success = true; | ||
| 50 | if !failed_protocols.is_empty() { | ||
| 51 | term.write_line(format!("push: succeeded over {protocol}").as_str())?; | ||
| 52 | let _ = set_protocol_preference(git_repo, protocol, &server_url, &Direction::Push); | ||
| 53 | } | ||
| 54 | break; | ||
| 55 | } | ||
| 56 | } | ||
| 57 | if success { | ||
| 58 | Ok(()) | ||
| 59 | } else { | ||
| 60 | let error = anyhow!( | ||
| 61 | "{} failed over {}{}", | ||
| 62 | server_url.short_name(), | ||
| 63 | join_with_and(&failed_protocols), | ||
| 64 | if decoded_nostr_url.protocol.is_some() { | ||
| 65 | " and nostr url contains protocol override so no other protocols were attempted" | ||
| 66 | } else { | ||
| 67 | "" | ||
| 68 | }, | ||
| 69 | ); | ||
| 70 | term.write_line(format!("push: {error}").as_str())?; | ||
| 71 | Err(error) | ||
| 72 | } | ||
| 73 | } | ||
| 74 | |||
| 75 | pub fn push_to_remote_url( | ||
| 76 | git_repo: &Repo, | ||
| 77 | git_server_url: &str, | ||
| 78 | remote_refspecs: &[String], | ||
| 79 | term: &Term, | ||
| 80 | ) -> Result<()> { | ||
| 81 | let git_config = git_repo.git_repo.config()?; | ||
| 82 | let mut git_server_remote = git_repo.git_repo.remote_anonymous(git_server_url)?; | ||
| 83 | let auth = GitAuthenticator::default(); | ||
| 84 | let mut push_options = git2::PushOptions::new(); | ||
| 85 | let mut remote_callbacks = git2::RemoteCallbacks::new(); | ||
| 86 | let push_reporter = Arc::new(Mutex::new(PushReporter::new(term))); | ||
| 87 | |||
| 88 | remote_callbacks.credentials(auth.credentials(&git_config)); | ||
| 89 | |||
| 90 | remote_callbacks.push_update_reference({ | ||
| 91 | let push_reporter = Arc::clone(&push_reporter); | ||
| 92 | move |name, error| { | ||
| 93 | let mut reporter = push_reporter.lock().unwrap(); | ||
| 94 | if let Some(error) = error { | ||
| 95 | let existing_lines = reporter.count_all_existing_lines(); | ||
| 96 | reporter.update_reference_errors.push(format!( | ||
| 97 | "WARNING: {} failed to push {name} error: {error}", | ||
| 98 | get_short_git_server_name(git_repo, git_server_url), | ||
| 99 | )); | ||
| 100 | reporter.write_all(existing_lines); | ||
| 101 | } | ||
| 102 | Ok(()) | ||
| 103 | } | ||
| 104 | }); | ||
| 105 | |||
| 106 | remote_callbacks.push_negotiation({ | ||
| 107 | let push_reporter = Arc::clone(&push_reporter); | ||
| 108 | move |updates| { | ||
| 109 | let mut reporter = push_reporter.lock().unwrap(); | ||
| 110 | let existing_lines = reporter.count_all_existing_lines(); | ||
| 111 | |||
| 112 | for update in updates { | ||
| 113 | let dst_refname = update | ||
| 114 | .dst_refname() | ||
| 115 | .unwrap_or("") | ||
| 116 | .replace("refs/heads/", "") | ||
| 117 | .replace("refs/tags/", "tags/"); | ||
| 118 | let msg = if update.dst().is_zero() { | ||
| 119 | format!("push: - [delete] {dst_refname}") | ||
| 120 | } else if update.src().is_zero() { | ||
| 121 | if update.dst_refname().unwrap_or("").contains("refs/tags") { | ||
| 122 | format!("push: * [new tag] {dst_refname}") | ||
| 123 | } else { | ||
| 124 | format!("push: * [new branch] {dst_refname}") | ||
| 125 | } | ||
| 126 | } else { | ||
| 127 | let force = remote_refspecs | ||
| 128 | .iter() | ||
| 129 | .any(|r| r.contains(&dst_refname) && r.contains('+')); | ||
| 130 | format!( | ||
| 131 | "push: {} {}..{} {} -> {dst_refname}", | ||
| 132 | if force { "+" } else { " " }, | ||
| 133 | oid_to_shorthand_string(update.src()).unwrap(), | ||
| 134 | oid_to_shorthand_string(update.dst()).unwrap(), | ||
| 135 | update | ||
| 136 | .src_refname() | ||
| 137 | .unwrap_or("") | ||
| 138 | .replace("refs/heads/", "") | ||
| 139 | .replace("refs/tags/", "tags/"), | ||
| 140 | ) | ||
| 141 | }; | ||
| 142 | // other possibilities will result in push to fail but better reporting is | ||
| 143 | // needed: | ||
| 144 | // deleting a non-existant branch: | ||
| 145 | // ! [remote rejected] <old-branch-name> -> <old-branch-name> (not found) | ||
| 146 | // adding a branch that already exists: | ||
| 147 | // ! [remote rejected] <new-branch-name> -> <new-branch-name> (already exists) | ||
| 148 | // pushing without non-fast-forward without force: | ||
| 149 | // ! [rejected] <branch-name> -> <branch-name> (non-fast-forward) | ||
| 150 | reporter.negotiation.push(msg); | ||
| 151 | } | ||
| 152 | reporter.write_all(existing_lines); | ||
| 153 | Ok(()) | ||
| 154 | } | ||
| 155 | }); | ||
| 156 | |||
| 157 | remote_callbacks.push_transfer_progress({ | ||
| 158 | let push_reporter = Arc::clone(&push_reporter); | ||
| 159 | #[allow(clippy::cast_precision_loss)] | ||
| 160 | move |current, total, bytes| { | ||
| 161 | let mut reporter = push_reporter.lock().unwrap(); | ||
| 162 | reporter.process_transfer_progress_update(current, total, bytes); | ||
| 163 | } | ||
| 164 | }); | ||
| 165 | |||
| 166 | remote_callbacks.sideband_progress({ | ||
| 167 | let push_reporter = Arc::clone(&push_reporter); | ||
| 168 | move |data| { | ||
| 169 | let mut reporter = push_reporter.lock().unwrap(); | ||
| 170 | reporter.process_remote_msg(data); | ||
| 171 | true | ||
| 172 | } | ||
| 173 | }); | ||
| 174 | push_options.remote_callbacks(remote_callbacks); | ||
| 175 | git_server_remote.push(remote_refspecs, Some(&mut push_options))?; | ||
| 176 | let _ = git_server_remote.disconnect(); | ||
| 177 | Ok(()) | ||
| 178 | } | ||
| 179 | |||
| 180 | #[allow(clippy::cast_precision_loss)] | ||
| 181 | #[allow(clippy::float_cmp)] | ||
| 182 | #[allow(clippy::needless_pass_by_value)] | ||
| 183 | fn report_on_transfer_progress( | ||
| 184 | current: usize, | ||
| 185 | total: usize, | ||
| 186 | bytes: usize, | ||
| 187 | start_time: &Instant, | ||
| 188 | end_time: Option<&Instant>, | ||
| 189 | ) -> Option<String> { | ||
| 190 | if total == 0 { | ||
| 191 | return None; | ||
| 192 | } | ||
| 193 | let percentage = ((current as f64 / total as f64) * 100.0) | ||
| 194 | // always round down because 100% complete is misleading when its not complete | ||
| 195 | .floor(); | ||
| 196 | let (size, unit) = if bytes as f64 >= (1024.0 * 1024.0) { | ||
| 197 | (bytes as f64 / (1024.0 * 1024.0), "MiB") | ||
| 198 | } else { | ||
| 199 | (bytes as f64 / 1024.0, "KiB") | ||
| 200 | }; | ||
| 201 | let speed = { | ||
| 202 | let duration = if let Some(end_time) = end_time { | ||
| 203 | (*end_time - *start_time).as_millis() as f64 | ||
| 204 | } else { | ||
| 205 | start_time.elapsed().as_millis() as f64 | ||
| 206 | }; | ||
| 207 | |||
| 208 | if duration > 0.0 { | ||
| 209 | (bytes as f64 / (1024.0 * 1024.0)) / (duration / 1000.0) // Convert bytes to MiB and milliseconds to seconds | ||
| 210 | } else { | ||
| 211 | 0.0 | ||
| 212 | } | ||
| 213 | }; | ||
| 214 | |||
| 215 | Some(format!( | ||
| 216 | "push: Writing objects: {percentage}% ({current}/{total}) {size:.2} {unit} | {speed:.2} MiB/s{}", | ||
| 217 | if current == total { ", done." } else { "" }, | ||
| 218 | )) | ||
| 219 | } | ||
| 220 | |||
| 221 | pub struct PushReporter<'a> { | ||
| 222 | remote_msgs: Vec<String>, | ||
| 223 | negotiation: Vec<String>, | ||
| 224 | transfer_progress_msgs: Vec<String>, | ||
| 225 | update_reference_errors: Vec<String>, | ||
| 226 | term: &'a console::Term, | ||
| 227 | start_time: Option<Instant>, | ||
| 228 | end_time: Option<Instant>, | ||
| 229 | } | ||
| 230 | impl<'a> PushReporter<'a> { | ||
| 231 | fn new(term: &'a console::Term) -> Self { | ||
| 232 | Self { | ||
| 233 | remote_msgs: vec![], | ||
| 234 | negotiation: vec![], | ||
| 235 | transfer_progress_msgs: vec![], | ||
| 236 | update_reference_errors: vec![], | ||
| 237 | term, | ||
| 238 | start_time: None, | ||
| 239 | end_time: None, | ||
| 240 | } | ||
| 241 | } | ||
| 242 | fn write_all(&self, lines_to_clear: usize) { | ||
| 243 | let _ = self.term.clear_last_lines(lines_to_clear); | ||
| 244 | for msg in &self.remote_msgs { | ||
| 245 | let _ = self.term.write_line(format!("remote: {msg}").as_str()); | ||
| 246 | } | ||
| 247 | for msg in &self.negotiation { | ||
| 248 | let _ = self.term.write_line(msg); | ||
| 249 | } | ||
| 250 | for msg in &self.transfer_progress_msgs { | ||
| 251 | let _ = self.term.write_line(msg); | ||
| 252 | } | ||
| 253 | for msg in &self.update_reference_errors { | ||
| 254 | let _ = self.term.write_line(msg); | ||
| 255 | } | ||
| 256 | } | ||
| 257 | |||
| 258 | fn count_all_existing_lines(&self) -> usize { | ||
| 259 | let width = self.term.size().1; | ||
| 260 | count_lines_per_msg_vec(width, &self.remote_msgs, "remote: ".len()) | ||
| 261 | + count_lines_per_msg_vec(width, &self.negotiation, 0) | ||
| 262 | + count_lines_per_msg_vec(width, &self.transfer_progress_msgs, 0) | ||
| 263 | + count_lines_per_msg_vec(width, &self.update_reference_errors, 0) | ||
| 264 | } | ||
| 265 | fn process_remote_msg(&mut self, data: &[u8]) { | ||
| 266 | if let Ok(data) = str::from_utf8(data) { | ||
| 267 | let data = data | ||
| 268 | .split(['\n', '\r']) | ||
| 269 | .map(str::trim) | ||
| 270 | .filter(|line| !line.trim().is_empty()) | ||
| 271 | .collect::<Vec<&str>>(); | ||
| 272 | for data in data { | ||
| 273 | let existing_lines = self.count_all_existing_lines(); | ||
| 274 | let msg = data.to_string(); | ||
| 275 | if let Some(last) = self.remote_msgs.last() { | ||
| 276 | if (last.contains('%') && !last.contains("100%")) | ||
| 277 | || last == &msg.replace(", done.", "") | ||
| 278 | { | ||
| 279 | self.remote_msgs.pop(); | ||
| 280 | self.remote_msgs.push(msg); | ||
| 281 | } else { | ||
| 282 | self.remote_msgs.push(msg); | ||
| 283 | } | ||
| 284 | } else { | ||
| 285 | self.remote_msgs.push(msg); | ||
| 286 | } | ||
| 287 | self.write_all(existing_lines); | ||
| 288 | } | ||
| 289 | } | ||
| 290 | } | ||
| 291 | fn process_transfer_progress_update(&mut self, current: usize, total: usize, bytes: usize) { | ||
| 292 | if self.start_time.is_none() { | ||
| 293 | self.start_time = Some(Instant::now()); | ||
| 294 | } | ||
| 295 | if let Some(report) = report_on_transfer_progress( | ||
| 296 | current, | ||
| 297 | total, | ||
| 298 | bytes, | ||
| 299 | &self.start_time.unwrap(), | ||
| 300 | self.end_time.as_ref(), | ||
| 301 | ) { | ||
| 302 | let existing_lines = self.count_all_existing_lines(); | ||
| 303 | if report.contains("100%") { | ||
| 304 | self.end_time = Some(Instant::now()); | ||
| 305 | } | ||
| 306 | self.transfer_progress_msgs = vec![report]; | ||
| 307 | self.write_all(existing_lines); | ||
| 308 | } | ||
| 309 | } | ||
| 310 | } | ||
diff --git a/src/bin/git_remote_nostr/utils.rs b/src/lib/utils.rs index 2cb85bf..431757f 100644 --- a/src/bin/git_remote_nostr/utils.rs +++ b/src/lib/utils.rs | |||
| @@ -8,7 +8,9 @@ use std::{ | |||
| 8 | 8 | ||
| 9 | use anyhow::{Context, Result, bail}; | 9 | use anyhow::{Context, Result, bail}; |
| 10 | use git2::Repository; | 10 | use git2::Repository; |
| 11 | use ngit::{ | 11 | use nostr_sdk::{Event, EventId, Kind, PublicKey, Url}; |
| 12 | |||
| 13 | use crate::{ | ||
| 12 | client::{ | 14 | client::{ |
| 13 | get_all_proposal_patch_pr_pr_update_events_from_cache, get_events_from_local_cache, | 15 | get_all_proposal_patch_pr_pr_update_events_from_cache, get_events_from_local_cache, |
| 14 | get_proposals_and_revisions_from_cache, | 16 | get_proposals_and_revisions_from_cache, |
| @@ -23,7 +25,6 @@ use ngit::{ | |||
| 23 | }, | 25 | }, |
| 24 | repo_ref::RepoRef, | 26 | repo_ref::RepoRef, |
| 25 | }; | 27 | }; |
| 26 | use nostr_sdk::{Event, EventId, Kind, PublicKey, Url}; | ||
| 27 | 28 | ||
| 28 | pub fn get_short_git_server_name(git_repo: &Repo, url: &str) -> std::string::String { | 29 | 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 | if let Ok(name) = get_remote_name_by_url(&git_repo.git_repo, url) { |