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:
Diffstat (limited to 'src/lib')
-rw-r--r--src/lib/cli_interactor.rs148
-rw-r--r--src/lib/client.rs14
-rw-r--r--src/lib/login/fresh.rs179
3 files changed, 307 insertions, 34 deletions
diff --git a/src/lib/cli_interactor.rs b/src/lib/cli_interactor.rs
index e944bf9..881b988 100644
--- a/src/lib/cli_interactor.rs
+++ b/src/lib/cli_interactor.rs
@@ -1,4 +1,7 @@
1use anyhow::{Context, Result}; 1use std::fmt;
2
3use anyhow::{Context, Result, bail};
4use console::Style;
2use dialoguer::{ 5use dialoguer::{
3 Confirm, Input, Password, 6 Confirm, Input, Password,
4 theme::{ColorfulTheme, Theme}, 7 theme::{ColorfulTheme, Theme},
@@ -7,9 +10,93 @@ use indicatif::TermLike;
7#[cfg(test)] 10#[cfg(test)]
8use mockall::*; 11use mockall::*;
9 12
13/// Sentinel error type indicating the error has already been printed to stderr.
14///
15/// When this propagates up to `main()`, it signals "already printed styled
16/// output to stderr, don't double-print". This is the same pattern clap uses
17/// internally.
18#[derive(Debug)]
19pub struct CliError;
20
21impl fmt::Display for CliError {
22 fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
23 // Empty display — the error message was already printed to stderr
24 Ok(())
25 }
26}
27
28impl std::error::Error for CliError {}
29
30/// Print a styled CLI error to stderr and return an `anyhow::Error` wrapping
31/// [`CliError`].
32///
33/// - `message`: the main error text (printed after the red `error:` prefix)
34/// - `details`: flag/description pairs shown as gray indented lines (for
35/// multiple missing fields). Descriptions are aligned to the longest flag.
36/// - `suggestions`: command suggestions shown in yellow
37///
38/// This function does NOT call `process::exit()`. It prints to stderr and
39/// returns an error that the caller should propagate with `?` or `return Err`.
40pub fn cli_error(message: &str, details: &[(&str, &str)], suggestions: &[&str]) -> anyhow::Error {
41 let dim = Style::new().for_stderr().color256(247);
42
43 eprint!(
44 "{} {}",
45 console::style("error:").for_stderr().red(),
46 message
47 );
48 if details.is_empty() {
49 eprintln!();
50 } else {
51 let max_flag_len = details
52 .iter()
53 .map(|(flag, _)| flag.len())
54 .max()
55 .unwrap_or(0);
56 eprintln!();
57 for (flag, desc) in details {
58 eprintln!(
59 " {:width$} {}",
60 dim.apply_to(flag),
61 dim.apply_to(desc),
62 width = max_flag_len
63 );
64 }
65 }
66
67 if !suggestions.is_empty() {
68 eprintln!();
69 for cmd in suggestions {
70 eprintln!(
71 "{}",
72 console::style(format!(" {cmd}")).for_stderr().yellow(),
73 );
74 }
75 }
76
77 CliError.into()
78}
79
10#[derive(Default)] 80#[derive(Default)]
11pub struct Interactor { 81pub struct Interactor {
12 theme: ColorfulTheme, 82 theme: ColorfulTheme,
83 non_interactive: bool,
84}
85
86impl Interactor {
87 pub fn new(non_interactive: bool) -> Self {
88 Self {
89 theme: ColorfulTheme::default(),
90 non_interactive,
91 }
92 }
93
94 /// Returns true if running in non-interactive mode (the default).
95 /// Interactive mode is only enabled when NGIT_INTERACTIVE_MODE env var is
96 /// set (via -i flag).
97 pub fn is_non_interactive() -> bool {
98 std::env::var("NGIT_INTERACTIVE_MODE").is_err()
99 }
13} 100}
14 101
15#[cfg_attr(test, automock)] 102#[cfg_attr(test, automock)]
@@ -22,6 +109,21 @@ pub trait InteractorPrompt {
22} 109}
23impl InteractorPrompt for Interactor { 110impl InteractorPrompt for Interactor {
24 fn input(&self, parms: PromptInputParms) -> Result<String> { 111 fn input(&self, parms: PromptInputParms) -> Result<String> {
112 if self.non_interactive || Self::is_non_interactive() {
113 if parms.optional || !parms.default.is_empty() {
114 return Ok(parms.default);
115 }
116 let flag_hint = parms
117 .flag_name
118 .as_ref()
119 .map(|f| format!(" (provide {} or use -i/-d)", f))
120 .unwrap_or_else(|| " (use -i for interactive mode or -d for defaults)".to_string());
121 bail!(
122 "interactive input required but running in non-interactive mode: {}{}",
123 parms.prompt,
124 flag_hint
125 );
126 }
25 let mut input = Input::with_theme(&self.theme) 127 let mut input = Input::with_theme(&self.theme)
26 .with_prompt(parms.prompt) 128 .with_prompt(parms.prompt)
27 .allow_empty(parms.optional) 129 .allow_empty(parms.optional)
@@ -32,6 +134,12 @@ impl InteractorPrompt for Interactor {
32 Ok(input.interact_text()?) 134 Ok(input.interact_text()?)
33 } 135 }
34 fn password(&self, parms: PromptPasswordParms) -> Result<String> { 136 fn password(&self, parms: PromptPasswordParms) -> Result<String> {
137 if self.non_interactive || Self::is_non_interactive() {
138 bail!(
139 "password input required but running in non-interactive mode: {}",
140 parms.prompt
141 );
142 }
35 let mut p = Password::with_theme(&self.theme) 143 let mut p = Password::with_theme(&self.theme)
36 .with_prompt(parms.prompt) 144 .with_prompt(parms.prompt)
37 .report(parms.report); 145 .report(parms.report);
@@ -42,6 +150,9 @@ impl InteractorPrompt for Interactor {
42 Ok(pass) 150 Ok(pass)
43 } 151 }
44 fn confirm(&self, params: PromptConfirmParms) -> Result<bool> { 152 fn confirm(&self, params: PromptConfirmParms) -> Result<bool> {
153 if self.non_interactive || Self::is_non_interactive() {
154 return Ok(params.default);
155 }
45 let confirm: bool = Confirm::with_theme(&self.theme) 156 let confirm: bool = Confirm::with_theme(&self.theme)
46 .with_prompt(params.prompt) 157 .with_prompt(params.prompt)
47 .default(params.default) 158 .default(params.default)
@@ -49,6 +160,15 @@ impl InteractorPrompt for Interactor {
49 Ok(confirm) 160 Ok(confirm)
50 } 161 }
51 fn choice(&self, parms: PromptChoiceParms) -> Result<usize> { 162 fn choice(&self, parms: PromptChoiceParms) -> Result<usize> {
163 if self.non_interactive || Self::is_non_interactive() {
164 if let Some(default) = parms.default {
165 return Ok(default);
166 }
167 bail!(
168 "interactive choice required but running in non-interactive mode: {}",
169 parms.prompt
170 );
171 }
52 let mut choice = dialoguer::Select::with_theme(&self.theme) 172 let mut choice = dialoguer::Select::with_theme(&self.theme)
53 .with_prompt(parms.prompt) 173 .with_prompt(parms.prompt)
54 .report(parms.report) 174 .report(parms.report)
@@ -61,6 +181,17 @@ impl InteractorPrompt for Interactor {
61 choice.interact().context("failed to get choice") 181 choice.interact().context("failed to get choice")
62 } 182 }
63 fn multi_choice(&self, parms: PromptMultiChoiceParms) -> Result<Vec<usize>> { 183 fn multi_choice(&self, parms: PromptMultiChoiceParms) -> Result<Vec<usize>> {
184 if self.non_interactive || Self::is_non_interactive() {
185 if let Some(defaults) = &parms.defaults {
186 return Ok(defaults
187 .iter()
188 .enumerate()
189 .filter(|(_, &selected)| selected)
190 .map(|(i, _)| i)
191 .collect());
192 }
193 return Ok(vec![]); // Empty selection if no defaults
194 }
64 // the colorful theme is not very clear so falling back to default 195 // the colorful theme is not very clear so falling back to default
65 let mut choice = dialoguer::MultiSelect::default() 196 let mut choice = dialoguer::MultiSelect::default()
66 .with_prompt(parms.prompt) 197 .with_prompt(parms.prompt)
@@ -73,11 +204,20 @@ impl InteractorPrompt for Interactor {
73 } 204 }
74} 205}
75 206
207/// Parameters for interactive input prompts.
208///
209/// Supports both interactive and non-interactive modes:
210/// - Interactive mode (NGIT_INTERACTIVE_MODE set): prompts user
211/// - Non-interactive mode (default): returns default value or errors
212///
213/// The `flag_name` field improves error messages by telling users
214/// which CLI flag would provide the missing value.
76pub struct PromptInputParms { 215pub struct PromptInputParms {
77 pub prompt: String, 216 pub prompt: String,
78 pub default: String, 217 pub default: String,
79 pub report: bool, 218 pub report: bool,
80 pub optional: bool, 219 pub optional: bool,
220 pub flag_name: Option<String>,
81} 221}
82 222
83impl Default for PromptInputParms { 223impl Default for PromptInputParms {
@@ -87,6 +227,7 @@ impl Default for PromptInputParms {
87 default: String::new(), 227 default: String::new(),
88 optional: false, 228 optional: false,
89 report: true, 229 report: true,
230 flag_name: None,
90 } 231 }
91 } 232 }
92} 233}
@@ -109,6 +250,11 @@ impl PromptInputParms {
109 self.report = false; 250 self.report = false;
110 self 251 self
111 } 252 }
253
254 pub fn with_flag_name<S: Into<String>>(mut self, flag_name: S) -> Self {
255 self.flag_name = Some(flag_name.into());
256 self
257 }
112} 258}
113 259
114pub struct PromptPasswordParms { 260pub struct PromptPasswordParms {
diff --git a/src/lib/client.rs b/src/lib/client.rs
index 4643392..fcb7a40 100644
--- a/src/lib/client.rs
+++ b/src/lib/client.rs
@@ -1300,6 +1300,11 @@ pub async fn get_repo_ref_from_cache(
1300 Some(repo_coordinate.public_key), 1300 Some(repo_coordinate.public_key),
1301 ))?; 1301 ))?;
1302 1302
1303 // Use name/description/web from the latest event across all maintainers
1304 let latest_metadata = repo_events
1305 .last()
1306 .and_then(|e| RepoRef::try_from((e.clone(), None)).ok());
1307
1303 let mut events: HashMap<Nip19Coordinate, nostr::Event> = HashMap::new(); 1308 let mut events: HashMap<Nip19Coordinate, nostr::Event> = HashMap::new();
1304 for m in &maintainers { 1309 for m in &maintainers {
1305 if let Some(e) = repo_events.iter().find(|e| e.pubkey.eq(m)) { 1310 if let Some(e) = repo_events.iter().find(|e| e.pubkey.eq(m)) {
@@ -1364,6 +1369,15 @@ pub async fn get_repo_ref_from_cache(
1364 git_server, 1369 git_server,
1365 events, 1370 events,
1366 maintainers_without_annoucnement: Some(maintainers_without_annoucnement), 1371 maintainers_without_annoucnement: Some(maintainers_without_annoucnement),
1372 name: latest_metadata
1373 .as_ref()
1374 .map_or_else(|| repo_ref.name.clone(), |r| r.name.clone()),
1375 description: latest_metadata
1376 .as_ref()
1377 .map_or_else(|| repo_ref.description.clone(), |r| r.description.clone()),
1378 web: latest_metadata
1379 .as_ref()
1380 .map_or_else(|| repo_ref.web.clone(), |r| r.web.clone()),
1367 ..repo_ref 1381 ..repo_ref
1368 }) 1382 })
1369} 1383}
diff --git a/src/lib/login/fresh.rs b/src/lib/login/fresh.rs
index e01d4c3..886b0e4 100644
--- a/src/lib/login/fresh.rs
+++ b/src/lib/login/fresh.rs
@@ -25,7 +25,7 @@ use crate::{
25 Interactor, InteractorPrompt, Printer, PromptChoiceParms, PromptConfirmParms, 25 Interactor, InteractorPrompt, Printer, PromptChoiceParms, PromptConfirmParms,
26 PromptInputParms, PromptPasswordParms, 26 PromptInputParms, PromptPasswordParms,
27 }, 27 },
28 client::{Connect, nip05_query, send_events}, 28 client::{Connect, nip05_query, save_event_in_global_cache, send_events},
29 git::{Repo, RepoActions, remove_git_config_item, save_git_config_item}, 29 git::{Repo, RepoActions, remove_git_config_item, save_git_config_item},
30}; 30};
31 31
@@ -123,7 +123,7 @@ pub async fn get_fresh_nsec_signer() -> Result<
123 .input( 123 .input(
124 PromptInputParms::default() 124 PromptInputParms::default()
125 .with_prompt("nsec") 125 .with_prompt("nsec")
126 .optional() 126 .with_flag_name("--nsec")
127 .dont_report(), 127 .dont_report(),
128 ) 128 )
129 .context("failed to get nsec input from interactor")?; 129 .context("failed to get nsec input from interactor")?;
@@ -509,6 +509,26 @@ async fn save_to_git_config(
509 if let Err(error) = 509 if let Err(error) =
510 silently_save_to_git_config(git_repo, signer_info, global).context(err_msg.clone()) 510 silently_save_to_git_config(git_repo, signer_info, global).context(err_msg.clone())
511 { 511 {
512 // Check if this is a read-only file system error
513 let is_readonly_error = error
514 .chain()
515 .any(|e| e.to_string().contains("Read-only file system"));
516
517 if is_readonly_error && global {
518 // In non-interactive mode, provide a clear error with --local suggestion
519 if crate::cli_interactor::Interactor::is_non_interactive() {
520 use crate::cli_interactor::cli_error;
521 return Err(cli_error(
522 "failed to create account",
523 &[("cause", "global git config is read-only")],
524 &[
525 "ngit account create --local --nsec <your-nsec>",
526 "ngit account login --local --nsec <your-nsec>",
527 ],
528 ));
529 }
530 }
531
512 eprintln!("Error: {error:?}"); 532 eprintln!("Error: {error:?}");
513 match signer_info { 533 match signer_info {
514 SignerInfo::Nsec { 534 SignerInfo::Nsec {
@@ -678,6 +698,119 @@ fn silently_save_to_git_config(
678 Ok(()) 698 Ok(())
679} 699}
680 700
701/// Non-interactive signup function for creating a new account
702///
703/// # Arguments
704/// * `name` - Display name for the new account
705/// * `client` - Optional client for publishing metadata to relays
706/// * `save_local` - If true, save credentials to local git config only
707/// * `publish` - If true, publish metadata and relay list to relays
708///
709/// # Returns
710/// Returns a tuple of (signer, public_key, signer_info, keys) where keys can be
711/// used to display the nsec
712pub async fn signup_non_interactive(
713 name: String,
714 #[cfg(test)] client: Option<&MockConnect>,
715 #[cfg(not(test))] client: Option<&Client>,
716 save_local: bool,
717 publish: bool,
718) -> Result<(Arc<dyn NostrSigner>, PublicKey, SignerInfo, Keys)> {
719 // Generate new keypair
720 let keys = nostr::Keys::generate();
721 let nsec = keys.secret_key().to_bech32()?;
722 let public_key = keys.public_key();
723
724 let signer_info = SignerInfo::Nsec {
725 nsec,
726 password: None,
727 npub: Some(public_key.to_bech32()?),
728 };
729
730 // Save to git config
731 let git_repo = Repo::discover().ok();
732 if let Err(error) = silently_save_to_git_config(&git_repo.as_ref(), &signer_info, !save_local) {
733 let is_readonly = error
734 .chain()
735 .any(|e| e.to_string().contains("Read-only file system"));
736
737 if is_readonly && !save_local {
738 use crate::cli_interactor::cli_error;
739
740 let mut cmds: Vec<String> = match &signer_info {
741 SignerInfo::Nsec { nsec, npub, .. } => {
742 let mut v = vec![format!("git config --global nostr.nsec {nsec}")];
743 if let Some(npub) = npub {
744 v.push(format!("git config --global nostr.npub {npub}"));
745 }
746 v
747 }
748 SignerInfo::Bunker {
749 bunker_uri,
750 bunker_app_key,
751 npub,
752 } => {
753 let mut v = vec![
754 format!("git config --global nostr.bunker-uri {bunker_uri}"),
755 format!("git config --global nostr.bunker-app-key {bunker_app_key}"),
756 ];
757 if let Some(npub) = npub {
758 v.push(format!("git config --global nostr.npub {npub}"));
759 }
760 v
761 }
762 };
763 cmds.push("ngit account create --local --name <your-name>".to_string());
764
765 let cmd_refs: Vec<&str> = cmds.iter().map(String::as_str).collect();
766 return Err(cli_error(
767 "global git config is read-only. login to local repo or save git config manually",
768 &[("--local", "login scoped to this repositoriy")],
769 &cmd_refs,
770 ));
771 }
772
773 return Err(error);
774 }
775
776 let git_repo_path = if let Some(ref git_repo) = git_repo {
777 Some(git_repo.get_path()?)
778 } else {
779 None
780 };
781
782 // Build events, save to cache, and optionally publish to relays
783 if let Some(client) = client {
784 let profile = EventBuilder::metadata(&Metadata::new().name(name)).sign_with_keys(&keys)?;
785 let relay_list = EventBuilder::relay_list(
786 client
787 .get_relay_default_set()
788 .iter()
789 .map(|s| (RelayUrl::parse(s).unwrap(), None)),
790 )
791 .sign_with_keys(&keys)?;
792
793 // Save to global cache so subsequent commands don't need to fetch
794 save_event_in_global_cache(git_repo_path, &profile).await?;
795 save_event_in_global_cache(git_repo_path, &relay_list).await?;
796
797 if publish {
798 send_events(
799 client,
800 git_repo_path,
801 vec![profile, relay_list],
802 client.get_relay_default_set().clone(),
803 vec![],
804 true,
805 false,
806 )
807 .await?;
808 }
809 }
810
811 Ok((Arc::new(keys.clone()), public_key, signer_info, keys))
812}
813
681async fn signup( 814async fn signup(
682 #[cfg(test)] client: Option<&MockConnect>, 815 #[cfg(test)] client: Option<&MockConnect>,
683 #[cfg(not(test))] client: Option<&Client>, 816 #[cfg(not(test))] client: Option<&Client>,
@@ -714,42 +847,22 @@ async fn signup(
714 _ => break Ok(None), 847 _ => break Ok(None),
715 } 848 }
716 } 849 }
717 let keys = nostr::Keys::generate(); 850
718 let nsec = keys.secret_key().to_bech32()?; 851 // Call the non-interactive function
852 let (signer, public_key, signer_info, _keys) = signup_non_interactive(
853 name.clone(),
854 client,
855 false, // save_local = false (will be saved globally by caller)
856 true, // publish = true (always publish in interactive mode)
857 )
858 .await?;
859
719 show_prompt_success("user display name", &name); 860 show_prompt_success("user display name", &name);
720 let signer_info = SignerInfo::Nsec {
721 nsec,
722 password: None,
723 npub: Some(keys.public_key().to_bech32()?),
724 };
725 let public_key = keys.public_key();
726 if let Some(client) = client {
727 let profile =
728 EventBuilder::metadata(&Metadata::new().name(name)).sign_with_keys(&keys)?;
729 let relay_list = EventBuilder::relay_list(
730 client
731 .get_relay_default_set()
732 .iter()
733 .map(|s| (RelayUrl::parse(s).unwrap(), None)),
734 )
735 .sign_with_keys(&keys)?;
736 eprintln!("publishing user profile to relays");
737 send_events(
738 client,
739 None,
740 vec![profile, relay_list],
741 client.get_relay_default_set().clone(),
742 vec![],
743 true,
744 false,
745 )
746 .await?;
747 }
748 eprintln!( 861 eprintln!(
749 "to login to other nostr clients eg. gitworkshop.dev with this account run `ngit export-keys` at any time to reveal your nostr account secret" 862 "to login to other nostr clients eg. gitworkshop.dev with this account run `ngit export-keys` at any time to reveal your nostr account secret"
750 ); 863 );
751 break Ok(Some(( 864 break Ok(Some((
752 Arc::new(keys), 865 signer,
753 public_key, 866 public_key,
754 signer_info, 867 signer_info,
755 // TODO factor in source 868 // TODO factor in source