upleb.uk

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

summaryrefslogtreecommitdiff
path: root/src/lib/utils.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/lib/utils.rs')
-rw-r--r--src/lib/utils.rs449
1 files changed, 449 insertions, 0 deletions
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}