upleb.uk

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

summaryrefslogtreecommitdiff
path: root/src/bin/ngit/sub_commands/init.rs
blob: c9c88739c91985a1e6ce8694d8206e62fe1a0087 (plain)
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
use std::collections::HashMap;

use anyhow::{Context, Result};
use console::Style;
use ngit::{cli_interactor::PromptConfirmParms, git::nostr_url::NostrUrlDecoded};
use nostr::{nips::nip01::Coordinate, FromBech32, PublicKey, ToBech32};
use nostr_sdk::{Kind, RelayUrl};

use crate::{
    cli::{extract_signer_cli_arguments, Cli},
    cli_interactor::{Interactor, InteractorPrompt, PromptInputParms},
    client::{fetching_with_report, get_repo_ref_from_cache, send_events, Client, Connect},
    git::{nostr_url::convert_clone_url_to_https, Repo, RepoActions},
    login,
    repo_ref::{
        extract_pks, get_repo_config_from_yaml, save_repo_config_to_yaml,
        try_and_get_repo_coordinates_when_remote_unknown, RepoRef,
    },
};

#[derive(Debug, clap::Args)]
pub struct SubCommandArgs {
    #[clap(short, long)]
    /// name of repository
    title: Option<String>,
    #[clap(short, long)]
    /// optional description
    description: Option<String>,
    #[clap(long)]
    /// git server url users can clone from
    clone_url: Vec<String>,
    #[clap(short, long, value_parser, num_args = 1..)]
    /// homepage
    web: Vec<String>,
    #[clap(short, long, value_parser, num_args = 1..)]
    /// relays contributors push patches and comments to
    relays: Vec<String>,
    #[clap(short, long, value_parser, num_args = 1..)]
    /// npubs of other maintainers
    other_maintainers: Vec<String>,
    #[clap(long)]
    /// usually root commit but will be more recent commit for forks
    earliest_unique_commit: Option<String>,
    #[clap(short, long)]
    /// shortname with no spaces or special characters
    identifier: Option<String>,
}

#[allow(clippy::too_many_lines)]
pub async fn launch(cli_args: &Cli, args: &SubCommandArgs) -> Result<()> {
    let git_repo = Repo::discover().context("failed to find a git repository")?;
    let git_repo_path = git_repo.get_path()?;

    let root_commit = git_repo
        .get_root_commit()
        .context("failed to get root commit of the repository")?;

    // TODO: check for empty repo
    // TODO: check for existing maintaiers file

    let mut client = Client::default();

    let repo_coordinate = if let Ok(repo_coordinate) =
        try_and_get_repo_coordinates_when_remote_unknown(&git_repo).await
    {
        Some(repo_coordinate)
    } else {
        None
    };

    let repo_ref = if let Some(repo_coordinate) = &repo_coordinate {
        fetching_with_report(git_repo_path, &client, repo_coordinate).await?;
        if let Ok(repo_ref) = get_repo_ref_from_cache(Some(git_repo_path), repo_coordinate).await {
            Some(repo_ref)
        } else {
            None
        }
    } else {
        None
    };

    let (signer, user_ref, _) = login::login_or_signup(
        &Some(&git_repo),
        &extract_signer_cli_arguments(cli_args).unwrap_or(None),
        &cli_args.password,
        Some(&client),
    )
    .await?;

    let repo_config_result = get_repo_config_from_yaml(&git_repo);
    // TODO: check for other claims

    let name = match &args.title {
        Some(t) => t.clone(),
        None => Interactor::default().input(
            PromptInputParms::default()
                .with_prompt("repo name")
                .with_default(if let Some(repo_ref) = &repo_ref {
                    repo_ref.name.clone()
                } else if let Some(coordinate) = &repo_coordinate {
                    coordinate.identifier.clone()
                } else {
                    String::new()
                }),
        )?,
    };

    let identifier = match &args.identifier {
        Some(t) => t.clone(),
        None => Interactor::default().input(
            PromptInputParms::default()
                .with_prompt(
                    "repo identifier (typically the short name with hypens instead of spaces)",
                )
                .with_default(if let Some(repo_ref) = &repo_ref {
                    repo_ref.identifier.clone()
                } else if let Some(repo_coordinate) = &repo_coordinate {
                    repo_coordinate.identifier.clone()
                } else {
                    let fallback = name
                        .clone()
                        .replace(' ', "-")
                        .chars()
                        .map(|c| {
                            if c.is_ascii_alphanumeric() || c.eq(&'/') {
                                c
                            } else {
                                '-'
                            }
                        })
                        .collect();
                    if let Ok(config) = &repo_config_result {
                        if let Some(identifier) = &config.identifier {
                            identifier.to_string()
                        } else {
                            fallback
                        }
                    } else {
                        fallback
                    }
                }),
        )?,
    };

    let description = match &args.description {
        Some(t) => t.clone(),
        None => Interactor::default().input(
            PromptInputParms::default()
                .with_prompt("repo description (one sentance)")
                .optional()
                .with_default(if let Some(repo_ref) = &repo_ref {
                    repo_ref.description.clone()
                } else {
                    String::new()
                }),
        )?,
    };

    let maintainers: Vec<PublicKey> = {
        let mut dont_ask = !args.other_maintainers.is_empty();
        let mut maintainers_string = if !args.other_maintainers.is_empty() {
            [args.other_maintainers.clone()].concat().join(" ")
        } else if repo_ref.is_none() && repo_config_result.is_err() {
            user_ref.public_key.to_bech32()?
        } else {
            let maintainers = if let Ok(config) = &repo_config_result {
                config.maintainers.clone()
            } else if let Some(repo_ref) = &repo_ref {
                repo_ref
                    .maintainers
                    .clone()
                    .iter()
                    .map(|k| k.to_bech32().unwrap())
                    .collect()
            } else {
                //unreachable
                vec![user_ref.public_key.to_bech32()?]
            };
            // add current user if not present
            if maintainers.iter().any(|m| {
                if let Ok(m_pubkey) = PublicKey::from_bech32(m) {
                    user_ref.public_key.eq(&m_pubkey)
                } else {
                    false
                }
            }) {
                maintainers.join(" ")
            } else {
                [maintainers, vec![user_ref.public_key.to_bech32()?]]
                    .concat()
                    .join(" ")
            }
        };
        'outer: loop {
            if !dont_ask && user_ref.public_key.to_bech32()?.eq(&maintainers_string) {
                if Interactor::default().confirm(
                    PromptConfirmParms::default()
                        .with_prompt("are you the only maintainer?")
                        .with_default(true),
                )? {
                    dont_ask = true;
                } else {
                    let mut opt_out_default = false;
                    if !Interactor::default().confirm(
                        PromptConfirmParms::default()
                            .with_prompt("are the other maintainers on nostr?")
                            .with_default(true),
                    )? {
                        opt_out_default = true;
                        dont_ask = true;
                    }
                    println!(
                        "nostr can reduce the trust placed in git servers by storing the state of git branches and tags. if you have other maintainers not using git via nostr, the verifiable state can fall behind the git server."
                    );

                    if Interactor::default().confirm(
                        PromptConfirmParms::default()
                            .with_prompt("opt-out of storing git state on nostr and relay on git server for now? you will still receive PRs and issues via nostr")
                            .with_default(true),
                    )? {
                        git_repo.save_git_config_item("nostr.nostate", "true", opt_out_default)?;
                    }
                }
            }
            if !dont_ask {
                println!("{}", &maintainers_string);
                maintainers_string = Interactor::default().input(
                    PromptInputParms::default()
                        .with_prompt("maintainers - space seperated list of npubs")
                        .with_default(maintainers_string),
                )?;
            }
            let mut maintainers: Vec<PublicKey> = vec![];
            for m in maintainers_string.split(' ') {
                if let Ok(m_pubkey) = PublicKey::from_bech32(m) {
                    maintainers.push(m_pubkey);
                } else {
                    println!("not a valid set of space seperated npubs");
                    dont_ask = false;
                    continue 'outer;
                }
            }
            // add current user incase removed
            if !maintainers.iter().any(|m| user_ref.public_key.eq(m)) {
                maintainers.push(user_ref.public_key);
            }
            break maintainers;
        }
    };

    let git_server = if args.clone_url.is_empty() {
        let no_state = if let Ok(Some(s)) = git_repo.get_git_config_item("nostr.nostate", None) {
            s == "true"
        } else {
            false
        };
        if no_state {
            println!(
                "you have opted out of storing git state on nostr, so a git server must be used for the state of authoritative branches, tags and related git objects."
            );
        } else {
            println!(
                "your repository state will be stored on nostr, but a git server is still required to store the git objects associated with this state."
            );
        }
        println!(
            "you can change this git server at any time and even configure multiple servers for redundancy. In this case, the git plugin will push to all of them when using the nostr remote."
        );
        println!("only maintainers need write access as PRs are sent over nostr.");
        println!(
            "a lightweight git server implementation for use with nostr, requiring no signup, is in development. several providers have shown interest in hosting it. for now use github, codeberg, or self-hosted song, forge, etc."
        );
        Interactor::default()
            .input(
                PromptInputParms::default()
                    .with_prompt("git server remote url(s) (space seperated)")
                    .with_default(if let Some(repo_ref) = &repo_ref {
                        repo_ref.git_server.clone().join(" ")
                    } else if let Ok(url) = git_repo.get_origin_url() {
                        if let Ok(fetch_url) = convert_clone_url_to_https(&url) {
                            fetch_url
                        } else if url.starts_with("nostr://") {
                            // nostr added as origin remote before repo announcement sent
                            String::new()
                        } else {
                            // local repo or custom protocol
                            url
                        }
                    } else {
                        String::new()
                    }),
            )?
            .split(' ')
            .map(std::string::ToString::to_string)
            .collect()
    } else {
        args.clone_url.clone()
    };

    // TODO: when NIP-66 is functional, use this to reccommend relays and filter out
    //       relays that won't accept contributors events. NIP-11 'limitations'
    //       isn't widely used enough to be usedful.

    let relays: Vec<RelayUrl> = {
        let mut default = if let Ok(config) = &repo_config_result {
            config.relays.clone()
        } else if let Some(repo_ref) = &repo_ref {
            repo_ref
                .relays
                .iter()
                .map(std::string::ToString::to_string)
                .collect::<Vec<String>>()
        } else if user_ref.relays.read().is_empty() {
            client.get_fallback_relays().clone()
        } else {
            user_ref.relays.read().clone()
        }
        .join(" ");
        'outer: loop {
            let relays: Vec<String> = if args.relays.is_empty() {
                Interactor::default()
                    .input(
                        PromptInputParms::default()
                            .with_prompt("relays")
                            .with_default(default),
                    )?
                    .split(' ')
                    .map(std::string::ToString::to_string)
                    .collect()
            } else {
                args.relays.clone()
            };
            let mut relay_urls = vec![];
            for r in &relays {
                if let Ok(r) = RelayUrl::parse(r) {
                    relay_urls.push(r);
                } else {
                    eprintln!("{r} is not a valid relay url");
                    default = relays.join(" ");
                    continue 'outer;
                }
            }
            break relay_urls;
        }
    };

    let web: Vec<String> = if args.web.is_empty() {
        Interactor::default()
            .input(
                PromptInputParms::default()
                    .with_prompt("repo website")
                    .optional()
                    .with_default(if let Some(repo_ref) = &repo_ref {
                        repo_ref.web.clone().join(" ")
                    } else {
                        format!("https://gitworkshop.dev/repo/{}", &identifier)
                    }),
            )?
            .split(' ')
            .map(std::string::ToString::to_string)
            .collect()
    } else {
        args.web.clone()
    };

    let earliest_unique_commit = match &args.earliest_unique_commit {
        Some(t) => t.clone(),
        None => {
            let mut earliest_unique_commit = if let Some(repo_ref) = &repo_ref {
                repo_ref.root_commit.clone()
            } else {
                root_commit.to_string()
            };
            println!(
                "the earliest unique commit helps with discoverability. It defaults to the root commit. Only change this if your repo has completely forked off an has formed its own identity."
            );
            loop {
                earliest_unique_commit = Interactor::default().input(
                    PromptInputParms::default()
                        .with_prompt("earliest unique commit (to help with discoverability)")
                        .with_default(earliest_unique_commit.clone()),
                )?;
                if let Ok(exists) = git_repo.does_commit_exist(&earliest_unique_commit) {
                    if exists {
                        break earliest_unique_commit;
                    }
                    println!("commit does not exist on current repository");
                } else {
                    println!("commit id not formatted correctly");
                }
                if earliest_unique_commit.len().ne(&40) {
                    println!("commit id must be 40 characters long");
                }
            }
        }
    };

    println!("publishing repostory reference...");

    let repo_ref = RepoRef {
        identifier: identifier.clone(),
        name,
        description,
        root_commit: earliest_unique_commit,
        git_server,
        web,
        relays: relays.clone(),
        trusted_maintainer: user_ref.public_key,
        maintainers: maintainers.clone(),
        events: HashMap::new(),
    };
    let repo_event = repo_ref.to_event(&signer).await?;

    client.set_signer(signer).await;

    send_events(
        &client,
        Some(git_repo_path),
        vec![repo_event],
        user_ref.relays.write(),
        relays.clone(),
        !cli_args.disable_cli_spinners,
        false,
    )
    .await?;

    // TODO - does this git config item do more harm than good?
    git_repo.save_git_config_item(
        "nostr.repo",
        &Coordinate {
            kind: Kind::GitRepoAnnouncement,
            public_key: user_ref.public_key,
            identifier: identifier.clone(),
            relays: vec![],
        }
        .to_bech32()?,
        false,
    )?;

    let relays = relays
        .iter()
        .map(std::string::ToString::to_string)
        .collect::<Vec<String>>();

    prompt_to_set_nostr_url_as_origin(&repo_ref, &git_repo).await?;

    // TODO: if no state event exists and there is currently a remote called
    // "origin", automtically push rather than waiting for the next commit

    // no longer create a new maintainers.yaml file - its too confusing for users
    // as it falls out of sync with data in nostr event . update if it already
    // exists
    if match &repo_config_result {
        Ok(config) => {
            !<std::option::Option<std::string::String> as Clone>::clone(&config.identifier)
                .unwrap_or_default()
                .eq(&identifier)
                || !extract_pks(config.maintainers.clone())?.eq(&maintainers)
                || !config.relays.eq(&relays)
        }
        Err(_) => false,
    } {
        let title_style = Style::new().bold().fg(console::Color::Yellow);
        println!("{}", title_style.apply_to("maintainers.yaml"));
        save_repo_config_to_yaml(
            &git_repo,
            identifier.clone(),
            maintainers.clone(),
            relays.clone(),
        )?;
        println!(
            "maintainers.yaml {}. commit and push.",
            if repo_config_result.is_err() {
                "created"
            } else {
                "updated"
            }
        );
        println!(
            "this optional file helps in identifying who the maintainers are over time through the commit history"
        );
    }
    Ok(())
}

async fn prompt_to_set_nostr_url_as_origin(repo_ref: &RepoRef, git_repo: &Repo) -> Result<()> {
    println!(
        "starting from your next commit, when you `git push` to a remote that uses your nostr url, it will store your repository state on nostr and update the state of the git server(s) you just listed."
    );
    println!(
        "in addition, any remote branches beginning with `pr/` are open PRs from contributors. they can submit these by simply pushing a branch with this `pr/` prefix."
    );

    if let Ok(origin_remote) = git_repo.git_repo.find_remote("origin") {
        if let Some(origin_url) = origin_remote.url() {
            if let Ok(nostr_url) =
                NostrUrlDecoded::parse_and_resolve(origin_url, &Some(git_repo)).await
            {
                if nostr_url.coordinate.identifier == repo_ref.identifier {
                    if nostr_url.coordinate.public_key == repo_ref.trusted_maintainer {
                        return Ok(());
                    }
                    // origin is set to a different trusted maintainer
                    println!(
                        "warning: currently git remote 'origin' is set to a different trusted maintainer with the same identifier"
                    );
                    ask_to_set_origin_remote(repo_ref, git_repo)?;
                } else {
                    // origin is linked to a different identifier
                    println!(
                        "warning: currently git remote 'origin' is set to a different repository identifier"
                    );
                    ask_to_set_origin_remote(repo_ref, git_repo)?;
                }
            } else {
                // remote is non-nostr url
                ask_to_set_origin_remote(repo_ref, git_repo)?;
            }
        } else {
            // no origin remote
            ask_to_create_new_origin_remote(repo_ref, git_repo)?;
        }
    }
    println!("contributors can clone your repository by installing ngit and using this clone url:");
    println!("{}", repo_ref.to_nostr_git_url());

    Ok(())
}

fn ask_to_set_origin_remote(repo_ref: &RepoRef, git_repo: &Repo) -> Result<()> {
    if Interactor::default().confirm(
        PromptConfirmParms::default()
            .with_default(true)
            .with_prompt("set remote \"origin\" to the nostr url of your repository?"),
    )? {
        git_repo
            .git_repo
            .remote_set_url("origin", &repo_ref.to_nostr_git_url())?;
    }
    Ok(())
}

fn ask_to_create_new_origin_remote(repo_ref: &RepoRef, git_repo: &Repo) -> Result<()> {
    if Interactor::default().confirm(
        PromptConfirmParms::default()
            .with_default(true)
            .with_prompt("set remote \"origin\" to the nostr url of your repository?"),
    )? {
        git_repo
            .git_repo
            .remote("origin", &repo_ref.to_nostr_git_url())?;
    }
    Ok(())
}