ngit 2.4.1

nostr plugin for git
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
use core::str;
use std::{
    collections::HashMap,
    fmt,
    io::{self, Stdin},
    path::Path,
    str::FromStr,
};

use anyhow::{Context, Result, bail};
use git2::Repository;
use nostr::nips::nip19::ToBech32;
use nostr_sdk::{Event, EventId, Kind, PublicKey};

use crate::{
    client::{
        get_all_proposal_patch_pr_pr_update_events_from_cache, get_events_from_local_cache,
        get_proposals_and_revisions_from_cache,
    },
    git::{
        Repo, RepoActions,
        nostr_url::{CloneUrl, NostrUrlDecoded, ServerProtocol},
    },
    git_events::{
        KIND_PULL_REQUEST, KIND_PULL_REQUEST_UPDATE, event_is_revision_root,
        get_pr_tip_event_or_most_recent_patch_with_ancestors, get_status,
        is_event_proposal_root_for_branch, status_kinds,
    },
    repo_ref::{RepoRef, extract_npub, is_grasp_server_clone_url},
};

pub fn get_short_git_server_name(url: &str) -> std::string::String {
    // Check if this is a grasp server URL
    if is_grasp_server_clone_url(url) {
        // Try to extract and format the grasp server URL
        if let Ok(npub) = extract_npub(url) {
            // Parse the URL to get the domain and identifier
            if let Ok(clone_url) = CloneUrl::from_str(url) {
                let domain = clone_url.domain();
                let path = clone_url.short_name();

                // Extract the identifier from the path (after /{npub}/)
                if let Some(after_npub) = path.split(&format!("/{}/", npub)).nth(1) {
                    // Truncate npub to show first 10 and last 5 characters
                    let truncated_npub = if npub.len() > 20 {
                        format!("{}...{}", &npub[..4], &npub[npub.len() - 5..])
                    } else {
                        npub.to_string()
                    };

                    return format!("{}/{}/{}", domain, truncated_npub, after_npub);
                }
            }
        }
    }

    // Fall back to default behavior for non-grasp server URLs
    CloneUrl::from_str(url)
        .map(|u| u.short_name())
        .unwrap_or_else(|_| url.to_string())
}

pub fn get_remote_name_by_url(git_repo: &Repository, url: &str) -> Result<String> {
    let remotes = git_repo.remotes()?;
    Ok(remotes
        .iter()
        .find(|r| {
            if let Some(name) = r {
                if let Some(remote_url) = git_repo.find_remote(name).unwrap().url() {
                    url == remote_url
                } else {
                    false
                }
            } else {
                false
            }
        })
        .context("could not find remote with matching url")?
        .context("remote with matching url must be named")?
        .to_string())
}

pub fn get_oids_from_fetch_batch(
    stdin: &Stdin,
    initial_oid: &str,
    initial_refstr: &str,
) -> Result<HashMap<String, String>> {
    let mut line = String::new();
    let mut batch = HashMap::new();
    batch.insert(initial_refstr.to_string(), initial_oid.to_string());
    loop {
        let tokens = read_line(stdin, &mut line)?;
        match tokens.as_slice() {
            ["fetch", oid, refstr] => {
                batch.insert((*refstr).to_string(), (*oid).to_string());
            }
            [] => break,
            _ => bail!(
                "after a `fetch` command we are only expecting another fetch or an empty line"
            ),
        }
    }
    Ok(batch)
}

/// Read one line from stdin, and split it into tokens.
pub fn read_line<'a>(stdin: &io::Stdin, line: &'a mut String) -> io::Result<Vec<&'a str>> {
    line.clear();

    let read = stdin.read_line(line)?;
    if read == 0 {
        return Ok(vec![]);
    }
    let line = line.trim();
    let tokens = line.split(' ').filter(|t| !t.is_empty()).collect();

    Ok(tokens)
}

pub async fn get_open_or_draft_proposals(
    git_repo: &Repo,
    repo_ref: &RepoRef,
) -> Result<HashMap<EventId, (Event, Vec<Event>)>> {
    let git_repo_path = git_repo.get_path()?;
    let proposals: Vec<nostr::Event> =
        get_proposals_and_revisions_from_cache(git_repo_path, repo_ref.coordinates())
            .await?
            .iter()
            .filter(|e|
                // If we wanted to treat to list Pull Requests that revise a Patch we would do this:
                // e.kind.eq(&KIND_PULL_REQUEST) ||
                !event_is_revision_root(e))
            .cloned()
            .collect();

    let statuses: Vec<nostr::Event> = {
        let mut statuses = get_events_from_local_cache(
            git_repo_path,
            vec![
                nostr::Filter::default()
                    .kinds(status_kinds().clone())
                    .events(proposals.iter().map(|e| e.id)),
            ],
        )
        .await?;
        statuses.sort_by_key(|e| e.created_at);
        statuses.reverse();
        statuses
    };
    let mut open_or_draft_proposals = HashMap::new();

    for proposal in &proposals {
        let status = get_status(proposal, repo_ref, &statuses, &proposals);
        if [Kind::GitStatusOpen, Kind::GitStatusDraft].contains(&status) {
            if let Ok(commits_events) = get_all_proposal_patch_pr_pr_update_events_from_cache(
                git_repo_path,
                repo_ref,
                &proposal.id,
            )
            .await
            {
                if let Ok(most_recent_proposal_patch_chain) =
                    get_pr_tip_event_or_most_recent_patch_with_ancestors(commits_events.clone())
                {
                    open_or_draft_proposals.insert(
                        proposal.id,
                        (proposal.clone(), most_recent_proposal_patch_chain),
                    );
                }
            }
        }
    }
    Ok(open_or_draft_proposals)
}

pub async fn get_all_proposals(
    git_repo: &Repo,
    repo_ref: &RepoRef,
) -> Result<HashMap<EventId, (Event, Vec<Event>)>> {
    let git_repo_path = git_repo.get_path()?;
    let proposals: Vec<nostr::Event> =
        get_proposals_and_revisions_from_cache(git_repo_path, repo_ref.coordinates())
            .await?
            .iter()
            .filter(|e|
                // If we wanted to treat to list Pull Requests that revise a Patch we would do this:
                // e.kind.eq(&KIND_PULL_REQUEST) ||
                !event_is_revision_root(e))
            .cloned()
            .collect();

    let mut all_proposals = HashMap::new();

    for proposal in proposals {
        if let Ok(commits_events) = get_all_proposal_patch_pr_pr_update_events_from_cache(
            git_repo_path,
            repo_ref,
            &proposal.id,
        )
        .await
        {
            if let Ok(most_recent_proposal_patch_chain) =
                get_pr_tip_event_or_most_recent_patch_with_ancestors(commits_events.clone())
            {
                all_proposals.insert(proposal.id, (proposal, most_recent_proposal_patch_chain));
            }
        }
    }
    Ok(all_proposals)
}

pub async fn proposal_tip_is_pr_or_pr_update(
    git_repo_path: &Path,
    repo_ref: &RepoRef,
    proposal_id: &EventId,
) -> Result<bool> {
    let commits_events =
        get_all_proposal_patch_pr_pr_update_events_from_cache(git_repo_path, repo_ref, proposal_id)
            .await
            .context(format!(
                "cannot get existing proposal events for {}",
                proposal_id.to_bech32()?
            ))?;
    let most_recent_proposal_patch_chain = get_pr_tip_event_or_most_recent_patch_with_ancestors(
        commits_events.clone(),
    )
    .context(format!(
        "cannot find tip from proposal events for {}",
        proposal_id.to_bech32()?,
    ))?;

    Ok([KIND_PULL_REQUEST, KIND_PULL_REQUEST_UPDATE].contains(
        &most_recent_proposal_patch_chain
            .first()
            .context(format!(
                "cannot find any proposal events for {}",
                proposal_id.to_bech32()?
            ))?
            .kind,
    ))
}

pub fn find_proposal_and_patches_by_branch_name<'a>(
    refstr: &'a str,
    proposals: &'a HashMap<EventId, (Event, Vec<Event>)>,
    current_user: Option<&PublicKey>,
) -> Option<(&'a EventId, &'a (Event, Vec<Event>))> {
    proposals.iter().find(|(_, (proposal, _))| {
        is_event_proposal_root_for_branch(proposal, refstr, current_user).unwrap_or(false)
    })
}

pub fn join_with_and<T: ToString>(items: &[T]) -> String {
    match items.len() {
        0 => String::new(),
        1 => items[0].to_string(),
        _ => {
            let last_item = items.last().unwrap().to_string();
            let rest = &items[..items.len() - 1];
            format!(
                "{} and {}",
                rest.iter()
                    .map(std::string::ToString::to_string)
                    .collect::<Vec<_>>()
                    .join(", "),
                last_item
            )
        }
    }
}

/// get an ordered vector of server protocols to attempt
pub fn get_read_protocols_to_try(
    git_repo: &Repo,
    server_url: &CloneUrl,
    decoded_nostr_url: &NostrUrlDecoded,
    is_grasp_server: bool,
) -> Vec<ServerProtocol> {
    if is_grasp_server {
        if server_url.protocol() == ServerProtocol::Http {
            vec![(ServerProtocol::UnauthHttp)]
        } else {
            vec![(ServerProtocol::UnauthHttps)]
        }
    } else if server_url.protocol() == ServerProtocol::Filesystem {
        vec![(ServerProtocol::Filesystem)]
    } else if let Some(protocol) = &decoded_nostr_url.protocol {
        vec![protocol.clone()]
    } else {
        let mut list = if server_url.protocol() == ServerProtocol::Http {
            vec![
                ServerProtocol::UnauthHttp,
                ServerProtocol::Ssh,
                // note: list and fetch stop here if ssh was authenticated
                ServerProtocol::Http,
            ]
        } else if server_url.protocol() == ServerProtocol::Ftp {
            vec![ServerProtocol::Ftp, ServerProtocol::Ssh]
        } else if server_url.protocol() == ServerProtocol::Git {
            vec![
                ServerProtocol::Git,
                ServerProtocol::UnauthHttps,
                ServerProtocol::Ssh,
                // note: list and fetch stop here if ssh was authenticated
                ServerProtocol::Https,
            ]
        } else {
            vec![
                ServerProtocol::UnauthHttps,
                ServerProtocol::Ssh,
                // note: list and fetch stop here if ssh was authenticated
                ServerProtocol::Https,
            ]
        };
        if let Some(protocol) = get_protocol_preference(git_repo, server_url, &Direction::Fetch) {
            if let Some(pos) = list.iter().position(|p| *p == protocol) {
                list.remove(pos);
                list.insert(0, protocol);
            }
        }
        list
    }
}

/// get an ordered vector of server protocols to attempt
pub fn get_write_protocols_to_try(
    git_repo: &Repo,
    server_url: &CloneUrl,
    decoded_nostr_url: &NostrUrlDecoded,
    is_grasp_server: bool,
) -> Vec<ServerProtocol> {
    if is_grasp_server {
        if server_url.protocol() == ServerProtocol::Http {
            vec![(ServerProtocol::UnauthHttp)]
        } else {
            vec![(ServerProtocol::UnauthHttps)]
        }
    } else if server_url.protocol() == ServerProtocol::Filesystem {
        vec![(ServerProtocol::Filesystem)]
    } else if let Some(protocol) = &decoded_nostr_url.protocol {
        vec![protocol.clone()]
    } else {
        let mut list = if server_url.protocol() == ServerProtocol::Http {
            vec![
                ServerProtocol::Ssh,
                // note: list and fetch stop here if ssh was authenticated
                ServerProtocol::Http,
            ]
        } else if server_url.protocol() == ServerProtocol::Ftp {
            vec![ServerProtocol::Ssh, ServerProtocol::Ftp]
        } else if server_url.protocol() == ServerProtocol::Git {
            vec![
                ServerProtocol::Ssh,
                ServerProtocol::Git,
                // note: list and fetch stop here if ssh was authenticated
                ServerProtocol::Https,
            ]
        } else {
            vec![
                ServerProtocol::Ssh,
                // note: list and fetch stop here if ssh was authenticated
                ServerProtocol::Https,
            ]
        };
        if let Some(protocol) = get_protocol_preference(git_repo, server_url, &Direction::Push) {
            if let Some(pos) = list.iter().position(|p| *p == protocol) {
                list.remove(pos);
                list.insert(0, protocol);
            }
        }

        list
    }
}

#[derive(Debug, PartialEq)]
pub enum Direction {
    Push,
    Fetch,
}
impl fmt::Display for Direction {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Direction::Push => write!(f, "push"),
            Direction::Fetch => write!(f, "fetch"),
        }
    }
}

pub fn get_protocol_preference(
    git_repo: &Repo,
    server_url: &CloneUrl,
    direction: &Direction,
) -> Option<ServerProtocol> {
    let server_short_name = server_url.short_name();
    if let Ok(Some(list)) =
        git_repo.get_git_config_item(format!("nostr.protocol-{direction}").as_str(), Some(false))
    {
        for item in list.split(';') {
            let pair = item.split(',').collect::<Vec<&str>>();
            if let Some(url) = pair.get(1) {
                if *url == server_short_name {
                    if let Some(protocol) = pair.first() {
                        if let Ok(protocol) = ServerProtocol::from_str(protocol) {
                            return Some(protocol);
                        }
                    }
                }
            }
        }
    }
    None
}

pub fn set_protocol_preference(
    git_repo: &Repo,
    protocol: &ServerProtocol,
    server_url: &CloneUrl,
    direction: &Direction,
) -> Result<()> {
    let server_short_name = server_url.short_name();
    let mut new = String::new();
    if let Some(list) =
        git_repo.get_git_config_item(format!("nostr.protocol-{direction}").as_str(), Some(false))?
    {
        for item in list.split(';') {
            let pair = item.split(',').collect::<Vec<&str>>();
            if let Some(url) = pair.get(1) {
                if *url != server_short_name && !item.is_empty() {
                    new.push_str(format!("{item};").as_str());
                }
            }
        }
    }
    new.push_str(format!("{protocol},{server_short_name};").as_str());

    git_repo.save_git_config_item(
        format!("nostr.protocol-{direction}").as_str(),
        new.as_str(),
        false,
    )
}

pub fn error_might_be_authentication_related(error: &anyhow::Error) -> bool {
    let error_str = error.to_string();
    for s in [
        "no ssh keys found",
        "invalid or unknown remote ssh hostkey",
        "authentication",
        "Permission",
        "permission",
        "not found",
    ] {
        if error_str.contains(s) {
            return true;
        }
    }
    false
}

#[cfg(test)]
mod tests {
    use super::*;
    mod join_with_and {
        use super::*;
        #[test]
        fn test_empty() {
            let items: Vec<&str> = vec![];
            assert_eq!(join_with_and(&items), "");
        }

        #[test]
        fn test_single_item() {
            let items = vec!["apple"];
            assert_eq!(join_with_and(&items), "apple");
        }

        #[test]
        fn test_two_items() {
            let items = vec!["apple", "banana"];
            assert_eq!(join_with_and(&items), "apple and banana");
        }

        #[test]
        fn test_three_items() {
            let items = vec!["apple", "banana", "cherry"];
            assert_eq!(join_with_and(&items), "apple, banana and cherry");
        }

        #[test]
        fn test_four_items() {
            let items = vec!["apple", "banana", "cherry", "date"];
            assert_eq!(join_with_and(&items), "apple, banana, cherry and date");
        }

        #[test]
        fn test_multiple_items() {
            let items = vec!["one", "two", "three", "four", "five"];
            assert_eq!(join_with_and(&items), "one, two, three, four and five");
        }
    }
}