upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

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