radicle_cli/commands/
init.rs

1#![allow(clippy::or_fun_call)]
2#![allow(clippy::collapsible_else_if)]
3use std::collections::HashSet;
4use std::convert::TryFrom;
5use std::env;
6use std::ffi::OsString;
7use std::path::PathBuf;
8use std::str::FromStr;
9
10use anyhow::{anyhow, bail, Context as _};
11use serde_json as json;
12
13use radicle::crypto::ssh;
14use radicle::explorer::ExplorerUrl;
15use radicle::git::raw;
16use radicle::git::RefString;
17use radicle::identity::project::ProjectName;
18use radicle::identity::{Doc, RepoId, Visibility};
19use radicle::node::events::UploadPack;
20use radicle::node::policy::Scope;
21use radicle::node::{Event, Handle, NodeId, DEFAULT_SUBSCRIBE_TIMEOUT};
22use radicle::storage::ReadStorage as _;
23use radicle::{profile, Node};
24
25use crate::commands;
26use crate::git;
27use crate::terminal as term;
28use crate::terminal::args::{Args, Error, Help};
29use crate::terminal::Interactive;
30
31pub const HELP: Help = Help {
32    name: "init",
33    description: "Initialize a Radicle repository",
34    version: env!("RADICLE_VERSION"),
35    usage: r#"
36Usage
37
38    rad init [<path>] [<option>...]
39
40Options
41
42        --name <string>            Name of the repository
43        --description <string>     Description of the repository
44        --default-branch <name>    The default branch of the repository
45        --scope <scope>            Repository follow scope: `followed` or `all` (default: all)
46        --private                  Set repository visibility to *private*
47        --public                   Set repository visibility to *public*
48        --existing <rid>           Setup repository as an existing Radicle repository
49    -u, --set-upstream             Setup the upstream of the default branch
50        --setup-signing            Setup the radicle key as a signing key for this repository
51        --no-confirm               Don't ask for confirmation during setup
52        --no-seed                  Don't seed this repository after initializing it
53    -v, --verbose                  Verbose mode
54        --help                     Print help
55"#,
56};
57
58#[derive(Default)]
59pub struct Options {
60    pub path: Option<PathBuf>,
61    pub name: Option<ProjectName>,
62    pub description: Option<String>,
63    pub branch: Option<String>,
64    pub interactive: Interactive,
65    pub visibility: Option<Visibility>,
66    pub existing: Option<RepoId>,
67    pub setup_signing: bool,
68    pub scope: Scope,
69    pub set_upstream: bool,
70    pub verbose: bool,
71    pub seed: bool,
72}
73
74impl Args for Options {
75    fn from_args(args: Vec<OsString>) -> anyhow::Result<(Self, Vec<OsString>)> {
76        use lexopt::prelude::*;
77
78        let mut parser = lexopt::Parser::from_args(args);
79        let mut path: Option<PathBuf> = None;
80
81        let mut name = None;
82        let mut description = None;
83        let mut branch = None;
84        let mut interactive = Interactive::Yes;
85        let mut set_upstream = false;
86        let mut setup_signing = false;
87        let mut scope = Scope::All;
88        let mut existing = None;
89        let mut seed = true;
90        let mut verbose = false;
91        let mut visibility = None;
92
93        while let Some(arg) = parser.next()? {
94            match arg {
95                Long("name") if name.is_none() => {
96                    let value = parser.value()?;
97                    let value = term::args::string(&value);
98                    let value = ProjectName::try_from(value)?;
99
100                    name = Some(value);
101                }
102                Long("description") if description.is_none() => {
103                    let value = parser
104                        .value()?
105                        .to_str()
106                        .ok_or(anyhow::anyhow!(
107                            "invalid repository description specified with `--description`"
108                        ))?
109                        .to_owned();
110
111                    description = Some(value);
112                }
113                Long("default-branch") if branch.is_none() => {
114                    let value = parser
115                        .value()?
116                        .to_str()
117                        .ok_or(anyhow::anyhow!(
118                            "invalid branch specified with `--default-branch`"
119                        ))?
120                        .to_owned();
121
122                    branch = Some(value);
123                }
124                Long("scope") => {
125                    let value = parser.value()?;
126
127                    scope = term::args::parse_value("scope", value)?;
128                }
129                Long("set-upstream") | Short('u') => {
130                    set_upstream = true;
131                }
132                Long("setup-signing") => {
133                    setup_signing = true;
134                }
135                Long("no-confirm") => {
136                    interactive = Interactive::No;
137                }
138                Long("no-seed") => {
139                    seed = false;
140                }
141                Long("private") => {
142                    visibility = Some(Visibility::private([]));
143                }
144                Long("public") => {
145                    visibility = Some(Visibility::Public);
146                }
147                Long("existing") if existing.is_none() => {
148                    let val = parser.value()?;
149                    let rid = term::args::rid(&val)?;
150
151                    existing = Some(rid);
152                }
153                Long("verbose") | Short('v') => {
154                    verbose = true;
155                }
156                Long("help") | Short('h') => {
157                    return Err(Error::Help.into());
158                }
159                Value(val) if path.is_none() => {
160                    path = Some(val.into());
161                }
162                _ => anyhow::bail!(arg.unexpected()),
163            }
164        }
165
166        Ok((
167            Options {
168                path,
169                name,
170                description,
171                branch,
172                scope,
173                existing,
174                interactive,
175                set_upstream,
176                setup_signing,
177                seed,
178                visibility,
179                verbose,
180            },
181            vec![],
182        ))
183    }
184}
185
186pub fn run(options: Options, ctx: impl term::Context) -> anyhow::Result<()> {
187    let profile = ctx.profile()?;
188    let cwd = env::current_dir()?;
189    let path = options.path.as_deref().unwrap_or(cwd.as_path());
190    let repo = match git::Repository::open(path) {
191        Ok(r) => r,
192        Err(e) if radicle::git::ext::is_not_found_err(&e) => {
193            anyhow::bail!("a Git repository was not found at the given path")
194        }
195        Err(e) => return Err(e.into()),
196    };
197    if let Ok((remote, _)) = git::rad_remote(&repo) {
198        if let Some(remote) = remote.url() {
199            bail!("repository is already initialized with remote {remote}");
200        }
201    }
202
203    if let Some(rid) = options.existing {
204        init_existing(repo, rid, options, &profile)
205    } else {
206        init(repo, options, &profile)
207    }
208}
209
210pub fn init(
211    repo: git::Repository,
212    options: Options,
213    profile: &profile::Profile,
214) -> anyhow::Result<()> {
215    let path = dunce::canonicalize(repo.workdir().unwrap_or_else(|| repo.path()))?;
216    let interactive = options.interactive;
217
218    let default_branch = match find_default_branch(&repo) {
219        Err(err @ DefaultBranchError::Head) => {
220            term::error(err);
221            term::hint("try `git checkout <default branch>` or set `git config set --local init.defaultBranch <default branch>`");
222            anyhow::bail!("aborting `rad init`")
223        }
224        Err(err @ DefaultBranchError::NoHead) => {
225            term::error(err);
226            term::hint("perhaps you need to create a branch?");
227            anyhow::bail!("aborting `rad init`")
228        }
229        Err(err) => anyhow::bail!(err),
230        Ok(branch) => branch,
231    };
232
233    term::headline(format!(
234        "Initializing{}radicle 👾 repository in {}..",
235        if let Some(visibility) = &options.visibility {
236            term::format::spaced(term::format::visibility(visibility))
237        } else {
238            term::format::default(" ").into()
239        },
240        term::format::dim(path.display())
241    ));
242
243    let name: ProjectName = match options.name {
244        Some(name) => name,
245        None => {
246            let default = path.file_name().map(|f| f.to_string_lossy().to_string());
247            term::input(
248                "Name",
249                default,
250                Some("The name of your repository, eg. 'acme'"),
251            )?
252            .try_into()?
253        }
254    };
255    let description = match options.description {
256        Some(desc) => desc,
257        None => term::input("Description", None, Some("You may leave this blank"))?,
258    };
259    let branch = match options.branch {
260        Some(branch) => branch,
261        None if interactive.yes() => term::input(
262            "Default branch",
263            Some(default_branch),
264            Some("Please specify an existing branch"),
265        )?,
266        None => default_branch,
267    };
268    let branch = RefString::try_from(branch.clone())
269        .map_err(|e| anyhow!("invalid branch name {:?}: {}", branch, e))?;
270    let visibility = if let Some(v) = options.visibility {
271        v
272    } else {
273        let selected = term::select(
274            "Visibility",
275            &["public", "private"],
276            "Public repositories are accessible by anyone on the network after initialization",
277        )?;
278        Visibility::from_str(selected)?
279    };
280
281    let signer = term::signer(profile)?;
282    let mut node = radicle::Node::new(profile.socket());
283    let mut spinner = term::spinner("Initializing...");
284    let mut push_cmd = String::from("git push");
285
286    match radicle::rad::init(
287        &repo,
288        name,
289        &description,
290        branch.clone(),
291        visibility,
292        &signer,
293        &profile.storage,
294    ) {
295        Ok((rid, doc, _)) => {
296            let proj = doc.project()?;
297
298            spinner.message(format!(
299                "Repository {} created.",
300                term::format::highlight(proj.name())
301            ));
302            spinner.finish();
303
304            if options.verbose {
305                term::blob(json::to_string_pretty(&proj)?);
306            }
307            // It's important to seed our own repositories to make sure that our node signals
308            // interest for them. This ensures that messages relating to them are relayed to us.
309            if options.seed {
310                profile.seed(rid, options.scope, &mut node)?;
311
312                if doc.is_public() {
313                    profile.add_inventory(rid, &mut node)?;
314                }
315            }
316
317            if options.set_upstream || git::branch_remote(&repo, proj.default_branch()).is_err() {
318                // Setup eg. `master` -> `rad/master`
319                radicle::git::set_upstream(
320                    &repo,
321                    &*radicle::rad::REMOTE_NAME,
322                    proj.default_branch(),
323                    radicle::git::refs::workdir::branch(proj.default_branch()),
324                )?;
325            } else {
326                push_cmd = format!("git push {} {branch}", *radicle::rad::REMOTE_NAME);
327            }
328
329            if options.setup_signing {
330                // Setup radicle signing key.
331                self::setup_signing(profile.id(), &repo, interactive)?;
332            }
333
334            term::blank();
335            term::info!(
336                "Your Repository ID {} is {}.",
337                term::format::dim("(RID)"),
338                term::format::highlight(rid.urn())
339            );
340            let directory = if path == env::current_dir()? {
341                "this directory".to_owned()
342            } else {
343                term::format::tertiary(path.display()).to_string()
344            };
345            term::info!(
346                "You can show it any time by running {} from {directory}.",
347                term::format::command("rad .")
348            );
349            term::blank();
350
351            // Announce inventory to network.
352            if let Err(e) = announce(rid, doc, &mut node, &profile.config) {
353                term::blank();
354                term::warning(format!(
355                    "There was an error announcing your repository to the network: {e}"
356                ));
357                term::warning("Try again with `rad sync --announce`, or check your logs with `rad node logs`.");
358                term::blank();
359            }
360            term::info!("To push changes, run {}.", term::format::command(push_cmd));
361        }
362        Err(err) => {
363            spinner.failed();
364            anyhow::bail!(err);
365        }
366    }
367
368    Ok(())
369}
370
371pub fn init_existing(
372    working: git::Repository,
373    rid: RepoId,
374    options: Options,
375    profile: &profile::Profile,
376) -> anyhow::Result<()> {
377    let stored = profile.storage.repository(rid)?;
378    let project = stored.project()?;
379    let url = radicle::git::Url::from(rid);
380
381    radicle::git::configure_repository(&working)?;
382    radicle::git::configure_remote(
383        &working,
384        &radicle::rad::REMOTE_NAME,
385        &url,
386        &url.clone().with_namespace(profile.public_key),
387    )?;
388
389    if options.set_upstream {
390        // Setup eg. `master` -> `rad/master`
391        radicle::git::set_upstream(
392            &working,
393            &*radicle::rad::REMOTE_NAME,
394            project.default_branch(),
395            radicle::git::refs::workdir::branch(project.default_branch()),
396        )?;
397    }
398
399    term::success!(
400        "Initialized existing repository {} in {}..",
401        term::format::tertiary(rid),
402        term::format::dim(
403            working
404                .workdir()
405                .unwrap_or_else(|| working.path())
406                .display()
407        ),
408    );
409
410    Ok(())
411}
412
413#[derive(Debug)]
414enum SyncResult<T> {
415    NodeStopped,
416    NoPeersConnected,
417    NotSynced,
418    Synced { result: T },
419}
420
421fn sync(
422    rid: RepoId,
423    node: &mut Node,
424    config: &profile::Config,
425) -> Result<SyncResult<Option<ExplorerUrl>>, radicle::node::Error> {
426    if !node.is_running() {
427        return Ok(SyncResult::NodeStopped);
428    }
429    let mut spinner = term::spinner("Updating inventory..");
430    // N.b. indefinitely subscribe to events and set a lower timeout on events
431    // below.
432    let events = node.subscribe(DEFAULT_SUBSCRIBE_TIMEOUT)?;
433    let sessions = node.sessions()?;
434
435    spinner.message("Announcing..");
436
437    if !sessions.iter().any(|s| s.is_connected()) {
438        return Ok(SyncResult::NoPeersConnected);
439    }
440
441    // Connect to preferred seeds in case we aren't connected.
442    for seed in config.preferred_seeds.iter() {
443        if !sessions.iter().any(|s| s.nid == seed.id) {
444            commands::rad_node::control::connect(
445                node,
446                seed.id,
447                seed.addr.clone(),
448                radicle::node::DEFAULT_TIMEOUT,
449            )
450            .ok();
451        }
452    }
453    // Announce our new inventory to connected nodes.
454    node.announce_inventory()?;
455
456    spinner.message("Syncing..");
457
458    let mut replicas = HashSet::new();
459    // Start upload pack as None and set it if we encounter an event
460    let mut upload_pack = term::upload_pack::UploadPack::new();
461
462    for e in events {
463        match e {
464            Ok(Event::RefsSynced {
465                remote, rid: rid_, ..
466            }) if rid == rid_ => {
467                term::success!("Repository successfully synced to {remote}");
468                replicas.insert(remote);
469                // If we manage to replicate to one of our preferred seeds, we can stop waiting.
470                if config.preferred_seeds.iter().any(|s| s.id == remote) {
471                    break;
472                }
473            }
474            Ok(Event::UploadPack(UploadPack::Write {
475                rid: rid_,
476                remote,
477                progress,
478            })) if rid == rid_ => {
479                log::debug!("Upload progress for {remote}: {progress}");
480            }
481            Ok(Event::UploadPack(UploadPack::PackProgress {
482                rid: rid_,
483                remote,
484                transmitted,
485            })) if rid == rid_ => spinner.message(upload_pack.transmitted(remote, transmitted)),
486            Ok(Event::UploadPack(UploadPack::Done {
487                rid: rid_,
488                remote,
489                status,
490            })) if rid == rid_ => {
491                log::debug!("Upload done for {rid} to {remote} with status: {status}");
492                spinner.message(upload_pack.done(&remote));
493            }
494            Ok(Event::UploadPack(UploadPack::Error {
495                rid: rid_,
496                remote,
497                err,
498            })) if rid == rid_ => {
499                term::warning(format!("Upload error for {rid} to {remote}: {err}"));
500            }
501            Ok(_) => {
502                // Some other irrelevant event received.
503            }
504            Err(radicle::node::Error::TimedOut) => {
505                break;
506            }
507            Err(e) => {
508                spinner.error(&e);
509                return Err(e);
510            }
511        }
512    }
513
514    if !replicas.is_empty() {
515        spinner.message(format!(
516            "Repository successfully synced to {} node(s).",
517            replicas.len()
518        ));
519        spinner.finish();
520
521        for seed in config.preferred_seeds.iter() {
522            if replicas.contains(&seed.id) {
523                return Ok(SyncResult::Synced {
524                    result: Some(config.public_explorer.url(seed.addr.host.to_string(), rid)),
525                });
526            }
527        }
528        Ok(SyncResult::Synced { result: None })
529    } else {
530        spinner.message("Repository successfully announced to the network.");
531        spinner.finish();
532
533        Ok(SyncResult::NotSynced)
534    }
535}
536
537pub fn announce(
538    rid: RepoId,
539    doc: Doc,
540    node: &mut Node,
541    config: &profile::Config,
542) -> anyhow::Result<()> {
543    if doc.is_public() {
544        match sync(rid, node, config) {
545            Ok(SyncResult::Synced {
546                result: Some(url), ..
547            }) => {
548                term::blank();
549                term::info!(
550                    "Your repository has been synced to the network and is \
551                    now discoverable by peers.",
552                );
553                term::info!("View it in your browser at:");
554                term::blank();
555                term::indented(term::format::tertiary(url));
556                term::blank();
557            }
558            Ok(SyncResult::Synced { result: None, .. }) => {
559                term::blank();
560                term::info!(
561                    "Your repository has been synced to the network and is \
562                    now discoverable by peers.",
563                );
564                if !config.preferred_seeds.is_empty() {
565                    term::info!(
566                        "Unfortunately, you were unable to replicate your repository to \
567                        your preferred seeds."
568                    );
569                }
570            }
571            Ok(SyncResult::NotSynced) => {
572                term::blank();
573                term::info!(
574                    "Your repository has been announced to the network and is \
575                    now discoverable by peers.",
576                );
577                term::info!(
578                    "You can check for any nodes that have replicated your repository by running \
579                    `rad sync status`."
580                );
581                term::blank();
582            }
583            Ok(SyncResult::NoPeersConnected) => {
584                term::blank();
585                term::info!(
586                    "You are not connected to any peers. Your repository will be announced as soon as \
587                    your node establishes a connection with the network.");
588                term::info!("Check for peer connections with `rad node status`.");
589                term::blank();
590            }
591            Ok(SyncResult::NodeStopped) => {
592                term::info!(
593                    "Your repository will be announced to the network when you start your node."
594                );
595                term::info!(
596                    "You can start your node with {}.",
597                    term::format::command("rad node start")
598                );
599            }
600            Err(e) => {
601                return Err(e.into());
602            }
603        }
604    } else {
605        term::info!(
606            "You have created a {} repository.",
607            term::format::visibility(doc.visibility())
608        );
609        term::info!(
610            "This repository will only be visible to you, \
611            and to peers you explicitly allow.",
612        );
613        term::blank();
614        term::info!(
615            "To make it public, run {}.",
616            term::format::command("rad publish")
617        );
618    }
619
620    Ok(())
621}
622
623/// Setup radicle key as commit signing key in repository.
624pub fn setup_signing(
625    node_id: &NodeId,
626    repo: &git::Repository,
627    interactive: Interactive,
628) -> anyhow::Result<()> {
629    let repo = repo
630        .workdir()
631        .ok_or(anyhow!("cannot setup signing in bare repository"))?;
632    let key = ssh::fmt::fingerprint(node_id);
633    let yes = if !git::is_signing_configured(repo)? {
634        term::headline(format!(
635            "Configuring radicle signing key {}...",
636            term::format::tertiary(key)
637        ));
638        true
639    } else if interactive.yes() {
640        term::confirm(format!(
641            "Configure radicle signing key {} in local checkout?",
642            term::format::tertiary(key),
643        ))
644    } else {
645        true
646    };
647
648    if yes {
649        match git::write_gitsigners(repo, [node_id]) {
650            Ok(file) => {
651                git::ignore(repo, file.as_path())?;
652
653                term::success!("Created {} file", term::format::tertiary(file.display()));
654            }
655            Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {
656                let ssh_key = ssh::fmt::key(node_id);
657                let gitsigners = term::format::tertiary(".gitsigners");
658                term::success!("Found existing {} file", gitsigners);
659
660                let ssh_keys =
661                    git::read_gitsigners(repo).context("error reading .gitsigners file")?;
662
663                if ssh_keys.contains(&ssh_key) {
664                    term::success!("Signing key is already in {gitsigners} file");
665                } else if term::confirm(format!("Add signing key to {gitsigners}?")) {
666                    git::add_gitsigners(repo, [node_id])?;
667                }
668            }
669            Err(err) => {
670                return Err(err.into());
671            }
672        }
673        git::configure_signing(repo, node_id)?;
674
675        term::success!(
676            "Signing configured in {}",
677            term::format::tertiary(".git/config")
678        );
679    }
680    Ok(())
681}
682
683#[derive(Debug, thiserror::Error)]
684enum DefaultBranchError {
685    #[error("could not determine default branch in repository")]
686    NoHead,
687    #[error("in detached HEAD state")]
688    Head,
689    #[error("could not determine default branch in repository: {0}")]
690    Git(raw::Error),
691}
692
693fn find_default_branch(repo: &raw::Repository) -> Result<String, DefaultBranchError> {
694    match find_init_default_branch(repo).ok().flatten() {
695        Some(refname) => Ok(refname),
696        None => Ok(find_repository_head(repo)?),
697    }
698}
699
700fn find_init_default_branch(repo: &raw::Repository) -> Result<Option<String>, raw::Error> {
701    let config = repo.config().and_then(|mut c| c.snapshot())?;
702    let default_branch = config.get_str("init.defaultbranch")?;
703    let branch = repo.find_branch(default_branch, raw::BranchType::Local)?;
704    Ok(branch.into_reference().shorthand().map(ToOwned::to_owned))
705}
706
707fn find_repository_head(repo: &raw::Repository) -> Result<String, DefaultBranchError> {
708    match repo.head() {
709        Err(e) if e.code() == raw::ErrorCode::UnbornBranch => Err(DefaultBranchError::NoHead),
710        Err(e) => Err(DefaultBranchError::Git(e)),
711        Ok(head) => head
712            .shorthand()
713            .filter(|refname| *refname != "HEAD")
714            .ok_or(DefaultBranchError::Head)
715            .map(|refname| refname.to_owned()),
716    }
717}