From e4cfa53bcec6db72682904d09b269961fa21aa3f Mon Sep 17 00:00:00 2001 From: Joseph Montanaro Date: Sun, 22 Nov 2026 06:17:04 -0500 Subject: [PATCH] formatting pass --- src/app.rs | 13 ++-- src/assets.rs | 1 - src/components/colored_switch.rs | 7 +- src/components/error_alert.rs | 6 +- src/components/passphrase_input.rs | 19 +++-- src/config.rs | 25 +++--- src/credentials/aws.rs | 2 +- src/db/aws.rs | 41 ++++++---- src/db/config.rs | 9 +-- src/db/migrations.rs | 22 ++++-- src/db/mod.rs | 37 ++++----- src/error.rs | 1 - src/main.rs | 1 - src/screens/credentials.rs | 121 +++++++++++++++++++++-------- src/screens/home.rs | 50 +++++++++--- src/screens/mod.rs | 1 - src/screens/unlock.rs | 11 +-- src/screens/welcome.rs | 36 ++++----- src/session.rs | 4 +- src/srv/creddy_server.rs | 25 +++--- src/tests/mod.rs | 95 ++++++++++++++-------- 21 files changed, 333 insertions(+), 194 deletions(-) diff --git a/src/app.rs b/src/app.rs index 84f5943..840be3c 100644 --- a/src/app.rs +++ b/src/app.rs @@ -16,9 +16,7 @@ impl Render for CreddyApp { let session = cx.global::(); let screen = match session { AppSession::Empty => window - .use_keyed_state("welcome", cx, |window, cx| { - WelcomeScreen::new(window, cx) - }) + .use_keyed_state("welcome", cx, |window, cx| WelcomeScreen::new(window, cx)) .into_any_element(), AppSession::Locked => window .use_keyed_state("unlock", cx, |window, cx| UnlockScreen::new(window, cx)) @@ -56,9 +54,12 @@ pub fn launch(cx: &mut App, config: AppConfig, session: AppSession) -> WindowHan cx.set_global(Screen::Home); // refresh_windows() forces everything to re-render, which is kind of a nuclear solution, // but these values aren't expected to change very frequently, so it shouldn't be a problem - cx.observe_global::(|cx| cx.refresh_windows()).detach(); - cx.observe_global::(|cx| cx.refresh_windows()).detach(); - cx.observe_global::(|cx| cx.refresh_windows()).detach(); + cx.observe_global::(|cx| cx.refresh_windows()) + .detach(); + cx.observe_global::(|cx| cx.refresh_windows()) + .detach(); + cx.observe_global::(|cx| cx.refresh_windows()) + .detach(); cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| CreddyApp {})) .expect("open window") diff --git a/src/assets.rs b/src/assets.rs index 8b9ceed..e2ba750 100644 --- a/src/assets.rs +++ b/src/assets.rs @@ -3,7 +3,6 @@ use std::borrow::Cow; use gpui_kit::assets::{Assets, icon_assets}; use gpui_kit::{AssetSource, Result, SharedString}; - // gpui-kit only embeds the icons its own components use, so anything else has to be listed here icon_assets!(CreddyIcons, [Key, LogOut, Pencil, ShieldCheck, Trash]); diff --git a/src/components/colored_switch.rs b/src/components/colored_switch.rs index 4617b01..5b46b6e 100644 --- a/src/components/colored_switch.rs +++ b/src/components/colored_switch.rs @@ -5,7 +5,6 @@ use gpui_kit::{ }; use gpui_omarchy::ActiveTheme; - /// gpui-omarchy's switch hard-codes its track and knob colors, so this rebuilds it /// from the base parts in order to tint them with `color` when checked. pub fn colored_switch( @@ -41,7 +40,11 @@ pub fn colored_switch( .border_1() .border_color(if checked { color } else { t.control_border() }) .rounded_none() - .bg(if checked { color.opacity(0.18) } else { t.normal_fill() }) + .bg(if checked { + color.opacity(0.18) + } else { + t.normal_fill() + }) .child( SwitchThumb::new(checked) .size(rems(1.)) diff --git a/src/components/error_alert.rs b/src/components/error_alert.rs index eb9f53d..312b140 100644 --- a/src/components/error_alert.rs +++ b/src/components/error_alert.rs @@ -1,7 +1,9 @@ -use gpui_kit::{App, InteractiveElement, IntoElement, Role, SharedString, StatefulInteractiveElement, TestSupportExt}; +use gpui_kit::{ + App, InteractiveElement, IntoElement, Role, SharedString, StatefulInteractiveElement, + TestSupportExt, +}; use gpui_omarchy::{Status, alert}; - /// An error alert whose message is also its accessible label, /// so screen readers announce it and UI tests can find it by its "error" ID. pub fn error_alert(message: SharedString, cx: &App) -> impl IntoElement { diff --git a/src/components/passphrase_input.rs b/src/components/passphrase_input.rs index 2655f3e..1928c21 100644 --- a/src/components/passphrase_input.rs +++ b/src/components/passphrase_input.rs @@ -6,7 +6,6 @@ use gpui_kit::{ }; use gpui_omarchy::{ButtonVariant, icon_button, input}; - /// A masked passphrase field with a show/hide toggle. pub struct PassphraseInput { id: SharedString, @@ -62,11 +61,16 @@ impl PassphraseInputBuilder { }); // keep this field's masking in sync with the shared flag - let sync_mask = cx.observe_in(&show, window, |this: &mut PassphraseInput, show, window, cx| { - let masked = !*show.read(cx); - this.state.update(cx, |state, cx| state.set_masked(masked, window, cx)); - cx.notify(); - }); + let sync_mask = cx.observe_in( + &show, + window, + |this: &mut PassphraseInput, show, window, cx| { + let masked = !*show.read(cx); + this.state + .update(cx, |state, cx| state.set_masked(masked, window, cx)); + cx.notify(); + }, + ); // re-emit the subset of input events that consumers care about let forward = cx.subscribe(&state, |_, _, event: &InputEvent, cx| { @@ -119,8 +123,7 @@ impl Render for PassphraseInput { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { let (icon, label) = if *self.show.read(cx) { (IconName::EyeOff, "Hide passphrase") - } - else { + } else { (IconName::Eye, "Show passphrase") }; diff --git a/src/config.rs b/src/config.rs index 2245ba5..d4a1924 100644 --- a/src/config.rs +++ b/src/config.rs @@ -4,11 +4,10 @@ use std::fs::File; use std::path::{Path, PathBuf}; use gpui_kit::Global; -use serde::{Serialize, Deserialize}; +use serde::{Deserialize, Serialize}; use crate::error::CreddyError; - /// Config that doesn't need to or can't be stored in the encrypted db /// (such as settings that must be known at startup, before unlock). #[derive(Debug, Clone, Serialize, Deserialize)] @@ -29,8 +28,7 @@ impl PublicConfig { if path.exists() { let f = File::open(path)?; serde_json::from_reader(f).map_err(|e| CreddyError::InvalidJSON(e)) - } - else { + } else { Ok(PublicConfig::default()) } } @@ -51,9 +49,7 @@ pub struct PrivateConfig { impl Default for PrivateConfig { fn default() -> PrivateConfig { - PrivateConfig { - rehide_ms: 1000, - } + PrivateConfig { rehide_ms: 1000 } } } @@ -84,7 +80,12 @@ impl AppConfig { pub fn load_from(data_dir: PathBuf, runtime_dir: PathBuf) -> Result { let public_config = PublicConfig::load(&data_dir.join("public_config.json"))?; let private_config = PrivateConfig::default(); - Ok(AppConfig::from_parts(data_dir, runtime_dir, public_config, private_config)) + Ok(AppConfig::from_parts( + data_dir, + runtime_dir, + public_config, + private_config, + )) } /// Pull the appropriate fields from instances of PublicConfig and PrivateConfig (plus data_dir since that comes from neither) @@ -92,7 +93,7 @@ impl AppConfig { data_dir: PathBuf, runtime_dir: PathBuf, public: PublicConfig, - private: PrivateConfig + private: PrivateConfig, ) -> AppConfig { AppConfig { data_dir, @@ -147,7 +148,6 @@ impl Default for AppConfig { impl Global for AppConfig {} - #[cfg(test)] mod tests { use super::*; @@ -220,7 +220,10 @@ mod tests { let mut config = AppConfig::default(); config.runtime_dir = PathBuf::from("/tmp/creddy"); - assert_eq!(config.creddy_server_addr(), PathBuf::from("/tmp/creddy/creddy-server.sock")); + assert_eq!( + config.creddy_server_addr(), + PathBuf::from("/tmp/creddy/creddy-server.sock") + ); } #[test] diff --git a/src/credentials/aws.rs b/src/credentials/aws.rs index a4383a7..2aee5eb 100644 --- a/src/credentials/aws.rs +++ b/src/credentials/aws.rs @@ -1,5 +1,5 @@ use jiff::Timestamp; -use serde::{Serialize, Deserialize}; +use serde::{Deserialize, Serialize}; use uuid::Uuid; #[derive(Clone, Debug, Eq, PartialEq, Default, Serialize, Deserialize)] diff --git a/src/db/aws.rs b/src/db/aws.rs index aad5b48..5b1c8b5 100644 --- a/src/db/aws.rs +++ b/src/db/aws.rs @@ -1,7 +1,7 @@ +use super::Db; +use crate::credentials::AwsCredential; use duckdb::{Error, params}; use uuid::Uuid; -use crate::credentials::AwsCredential; -use super::Db; impl Db { pub fn load_aws_credential(&self, name: &str) -> Result { @@ -16,13 +16,15 @@ impl Db { FROM aws_credentials WHERE name = ?", params![name], - |row| Ok(AwsCredential { - id: row.get(0)?, - name: row.get(1)?, - access_key_id: row.get(2)?, - secret_access_key: row.get(3)?, - is_default: row.get(4)?, - }) + |row| { + Ok(AwsCredential { + id: row.get(0)?, + name: row.get(1)?, + access_key_id: row.get(2)?, + secret_access_key: row.get(3)?, + is_default: row.get(4)?, + }) + }, ) } @@ -53,7 +55,13 @@ impl Db { access_key_id = EXCLUDED.access_key_id, secret_access_key = EXCLUDED.secret_access_key, is_default = EXCLUDED.is_default", - params![cred.id, cred.name, cred.access_key_id, cred.secret_access_key, cred.is_default], + params![ + cred.id, + cred.name, + cred.access_key_id, + cred.secret_access_key, + cred.is_default + ], )?; tx.commit() } @@ -74,25 +82,26 @@ impl Db { secret_access_key, is_default FROM aws_credentials - ORDER BY created_at" + ORDER BY created_at", )?; stmt.query_map([], |row| { - Ok(AwsCredential{ + Ok(AwsCredential { id: row.get(0)?, name: row.get(1)?, access_key_id: row.get(2)?, secret_access_key: row.get(3)?, is_default: row.get(4)?, }) - })?.collect() + })? + .collect() } } #[cfg(test)] mod tests { - use testresult::TestResult; - use crate::tests::TestEnv; use super::*; + use crate::tests::TestEnv; + use testresult::TestResult; fn test_cred(name: &str, access_key_id: &str) -> AwsCredential { AwsCredential { @@ -150,7 +159,7 @@ mod tests { let (created_at, updated_at): (i64, i64) = conn.query_row( "SELECT created_at, updated_at FROM aws_credentials WHERE name = 'renamed'", [], - |row| Ok((row.get(0)?, row.get(1)?)) + |row| Ok((row.get(0)?, row.get(1)?)), )?; assert!(updated_at > created_at); diff --git a/src/db/config.rs b/src/db/config.rs index 6e0d9dc..3977bdf 100644 --- a/src/db/config.rs +++ b/src/db/config.rs @@ -1,6 +1,6 @@ +use super::Db; use crate::config::PrivateConfig; use crate::error::CreddyError; -use super::Db; impl Db { pub fn load_private_config(&self) -> Result { @@ -21,11 +21,10 @@ impl Db { #[cfg(test)] mod tests { - use testresult::TestResult; - use tempfile::TempDir; - use crate::config::AppConfig; use super::*; - + use crate::config::AppConfig; + use tempfile::TempDir; + use testresult::TestResult; fn test_db() -> Result<(Db, TempDir), CreddyError> { let data_dir = tempfile::tempdir()?; diff --git a/src/db/migrations.rs b/src/db/migrations.rs index 4916299..cd2b57a 100644 --- a/src/db/migrations.rs +++ b/src/db/migrations.rs @@ -3,16 +3,13 @@ use include_dir::{Dir, include_dir}; use crate::error::CreddyError; - static MIGRATIONS_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/migrations"); - struct Migration { id: &'static str, sql: &'static str, } - /// Run all unapplied database migrations. pub fn migrate(conn: &mut Connection) -> Result<(), CreddyError> { apply_migrations(conn, &embedded_migrations()) @@ -25,7 +22,11 @@ fn embedded_migrations() -> Vec { .filter(|f| f.path().extension().is_some_and(|ext| ext == "sql")) .map(|f| Migration { // these are baked in at compile time, so a bad file is a build problem, not a runtime one - id: f.path().file_name().and_then(|n| n.to_str()).expect("migration filename is not UTF-8"), + id: f + .path() + .file_name() + .and_then(|n| n.to_str()) + .expect("migration filename is not UTF-8"), sql: f.contents_utf8().expect("migration file is not UTF-8"), }) .collect(); @@ -81,11 +82,10 @@ fn list_applied_migrations(conn: &Connection) -> Result, CreddyError Ok(ids) } - #[cfg(test)] mod tests { - use testresult::TestResult; use super::*; + use testresult::TestResult; const FIRST: Migration = Migration { id: "0001_first.sql", @@ -110,7 +110,10 @@ mod tests { migrate(&mut conn)?; let applied = list_applied_migrations(&conn)?; - let expected: Vec<_> = embedded_migrations().iter().map(|m| m.id.to_string()).collect(); + let expected: Vec<_> = embedded_migrations() + .iter() + .map(|m| m.id.to_string()) + .collect(); assert_eq!(applied, expected); Ok(()) } @@ -123,7 +126,10 @@ mod tests { // already-applied migrations are skipped, so re-running FIRST would fail if it weren't apply_migrations(&mut conn, &[FIRST, SECOND])?; - assert_eq!(list_applied_migrations(&conn)?, ["0001_first.sql", "0002_second.sql"]); + assert_eq!( + list_applied_migrations(&conn)?, + ["0001_first.sql", "0002_second.sql"] + ); assert!(table_exists(&conn, "b")?); Ok(()) } diff --git a/src/db/mod.rs b/src/db/mod.rs index bb219ce..c76be55 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -1,14 +1,11 @@ +use argon2::{Algorithm, Argon2, Error as Argon2Error, ParamsBuilder, Version}; +use base64ct::{Base64, Encoding}; +use duckdb::{Connection, params}; use std::fs; use std::sync::Mutex; -use argon2::{Algorithm, Argon2, Version, Error as Argon2Error, ParamsBuilder}; -use base64ct::{Base64, Encoding}; -use duckdb::{ - Connection, - params, -}; -use crate::error::CreddyError; use crate::config::AppConfig; +use crate::error::CreddyError; mod aws; mod config; @@ -29,7 +26,6 @@ const TIME_COST: u32 = 1; #[cfg(debug_assertions)] const PARALLELISM_COST: u32 = 1; - #[derive(Debug)] pub struct Db { connection: Mutex, @@ -42,21 +38,21 @@ impl Db { // since we are about to make use of the salt stored in `config`, we need to save it now config.public_config().save(&config.public_config_path())?; - let path = config.db_path() + let path = config + .db_path() .into_os_string() .into_string() .map_err(|s| CreddyError::InvalidPath(s))?; let key = Db::derive_key(passphrase, &config.db_salt)?; let mut conn = Connection::open_in_memory()?; - conn.execute( - "ATTACH ? AS creddy (ENCRYPTION_KEY ?);", - params![path, key], - )?; + conn.execute("ATTACH ? AS creddy (ENCRYPTION_KEY ?);", params![path, key])?; // must come before migrating, or the tables end up in the in-memory db conn.execute("USE creddy;", [])?; migrations::migrate(&mut conn)?; - Ok(Self{ connection: Mutex::new(conn) }) + Ok(Self { + connection: Mutex::new(conn), + }) } /// Hash the given passphrase/salt with argon2, then encode to base64 for DuckDB @@ -77,12 +73,11 @@ impl Db { } } - #[cfg(test)] mod tests { - use testresult::TestResult; - use duckdb::Error; use super::*; + use duckdb::Error; + use testresult::TestResult; const TEST_PASSPHRASE: &'static str = "correct horse battery staple"; const TEST_SALT: [u8; 32] = [0; 32]; @@ -103,9 +98,11 @@ mod tests { Err(Error::DuckDBFailure(error, _desc)) => { assert!(error.code == duckdb::ErrorCode::Unknown); assert!(error.extended_code == 1); - }, + } Err(e) => panic!("Unexpected error type: {e:?}"), - Ok(_) => panic!("Should not be able to open newly-created database without encryption key"), + Ok(_) => { + panic!("Should not be able to open newly-created database without encryption key") + } }; // confirm that using a different passphrase won't work @@ -115,7 +112,7 @@ mod tests { assert!(error.code == duckdb::ErrorCode::Unknown); assert!(error.extended_code == 1); assert!(desc.contains("Wrong encryption key")); - }, + } Err(e) => panic!("Unexpected error type: {e:?}"), Ok(_) => panic!("Should not be able to open database with a different passphrase"), } diff --git a/src/error.rs b/src/error.rs index 56e4d5b..03fc6a2 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,7 +1,6 @@ use std::ffi::OsString; use thiserror::Error; - #[derive(Error, Debug)] pub enum CreddyError { #[error("Couldn't determine location for app state")] diff --git a/src/main.rs b/src/main.rs index 9411585..86c7911 100644 --- a/src/main.rs +++ b/src/main.rs @@ -15,7 +15,6 @@ mod tests; use config::AppConfig; use session::AppSession; - fn main() { // todo: replace this with proper error handling let app_config = AppConfig::load().expect("failed to load config"); diff --git a/src/screens/credentials.rs b/src/screens/credentials.rs index e3ba48f..36a1c55 100644 --- a/src/screens/credentials.rs +++ b/src/screens/credentials.rs @@ -8,13 +8,12 @@ use gpui_omarchy::{ focus_scope, icon_button, input, tab_list, }; +use super::Screen; use crate::components::{PassphraseInput, PassphraseInputEvent, colored_switch, error_alert}; use crate::credentials::AwsCredential; use crate::session::AppSession; -use super::Screen; use uuid::Uuid; - pub struct CredentialsScreen { tab: usize, aws: Vec, @@ -36,7 +35,13 @@ struct AwsForm { impl CredentialsScreen { pub fn new(cx: &mut Context) -> Self { - let mut this = Self { tab: 0, aws: Vec::new(), aws_form: None, aws_deleting: None, error: None }; + let mut this = Self { + tab: 0, + aws: Vec::new(), + aws_form: None, + aws_deleting: None, + error: None, + }; this.load_aws(cx); this } @@ -50,20 +55,27 @@ impl CredentialsScreen { Ok(creds) => { self.aws = creds; self.error = None; - }, + } Err(e) => self.error = Some(format!("Failed to load credentials: {e}").into()), } } - fn open_aws_form(&mut self, editing: Option, window: &mut Window, cx: &mut Context) { - let existing = self.aws + fn open_aws_form( + &mut self, + editing: Option, + window: &mut Window, + cx: &mut Context, + ) { + let existing = self + .aws .iter() .find(|cred| Some(cred.id) == editing) .cloned() .unwrap_or_default(); let name = cx.new(|cx| InputState::new(window, cx).default_value(existing.name)); - let access_key_id = cx.new(|cx| InputState::new(window, cx).default_value(existing.access_key_id)); + let access_key_id = + cx.new(|cx| InputState::new(window, cx).default_value(existing.access_key_id)); let secret_access_key = PassphraseInput::builder("aws-secret") .value(existing.secret_access_key) .build(window, cx); @@ -106,13 +118,21 @@ impl CredentialsScreen { is_default: form.is_default, }; - if cred.name.is_empty() || cred.access_key_id.is_empty() || cred.secret_access_key.is_empty() { + if cred.name.is_empty() + || cred.access_key_id.is_empty() + || cred.secret_access_key.is_empty() + { self.error = Some("All fields are required.".into()); cx.notify(); return; } - if self.aws.iter().any(|existing| existing.name == cred.name && existing.id != cred.id) { - self.error = Some(format!("An AWS credential named \"{}\" already exists.", cred.name).into()); + if self + .aws + .iter() + .any(|existing| existing.name == cred.name && existing.id != cred.id) + { + self.error = + Some(format!("An AWS credential named \"{}\" already exists.", cred.name).into()); cx.notify(); return; } @@ -124,7 +144,7 @@ impl CredentialsScreen { Ok(()) => { self.aws_form = None; self.load_aws(cx); - }, + } Err(e) => self.error = Some(format!("Failed to save credential: {e}").into()), } cx.notify(); @@ -138,7 +158,7 @@ impl CredentialsScreen { Ok(()) => { self.aws_deleting = None; self.load_aws(cx); - }, + } Err(e) => self.error = Some(format!("Failed to delete credential: {e}").into()), } cx.notify(); @@ -149,7 +169,11 @@ impl CredentialsScreen { let mut panel = div().flex().flex_col().gap(rems(0.5)); if self.aws.is_empty() { - panel = panel.child(empty_state("AWS access keys", "You have no saved AWS credentials.", cx)); + panel = panel.child(empty_state( + "AWS access keys", + "You have no saved AWS credentials.", + cx, + )); } for cred in &self.aws { if let Some(form) = &self.aws_form @@ -180,7 +204,9 @@ impl CredentialsScreen { ) .child( button("aws-delete-confirm", "Delete", ButtonVariant::Danger, cx) - .on_click(cx.listener(move |this, _, _, cx| this.delete_aws(id, cx))), + .on_click( + cx.listener(move |this, _, _, cx| this.delete_aws(id, cx)), + ), ), ); continue; @@ -197,7 +223,10 @@ impl CredentialsScreen { .border_1() .border_color(if cred.is_default { t.accent } else { t.border }) .child(div().font_weight(FontWeight::BOLD).child(cred.name.clone())) - .children(cred.is_default.then(|| badge("Default", Status::Success, cx))) + .children( + cred.is_default + .then(|| badge("Default", Status::Success, cx)), + ) .child( div() .ml_auto() @@ -213,9 +242,9 @@ impl CredentialsScreen { ButtonVariant::Outline, cx, ) - .on_click(cx.listener(move |this, _, window, cx| { - this.open_aws_form(Some(id), window, cx) - })), + .on_click(cx.listener( + move |this, _, window, cx| this.open_aws_form(Some(id), window, cx), + )), ) .child( icon_button( @@ -238,9 +267,13 @@ impl CredentialsScreen { button("aws-add", "Add", ButtonVariant::Primary, cx) .self_center() .mt(rems(0.5)) - .on_click(cx.listener(|this, _, window, cx| this.open_aws_form(None, window, cx))), + .on_click( + cx.listener(|this, _, window, cx| this.open_aws_form(None, window, cx)), + ), ), - Some(form) if form.editing.is_none() => panel.child(self.render_aws_form(form, window, cx)), + Some(form) if form.editing.is_none() => { + panel.child(self.render_aws_form(form, window, cx)) + } Some(_) => panel, } } @@ -264,27 +297,41 @@ impl CredentialsScreen { .p(rems(1.)) .border_1() .border_color(t.border) - .child(field("Name", input("aws-name", &form.name, window, cx).into_any_element())) + .child(field( + "Name", + input("aws-name", &form.name, window, cx).into_any_element(), + )) .child(field( "Key ID", input("aws-key-id", &form.access_key_id, window, cx) .font_family(t.mono_font.clone()) .into_any_element(), )) - .child(field("Secret key", form.secret_access_key.clone().into_any_element())) + .child(field( + "Secret key", + form.secret_access_key.clone().into_any_element(), + )) .child( div() .flex() .items_center() .gap(rems(0.5)) .child( - colored_switch("aws-default", "Default AWS access key", form.is_default, t.success, cx) - .on_change(move |value, _, _, cx| this.update(cx, |this, cx| { + colored_switch( + "aws-default", + "Default AWS access key", + form.is_default, + t.success, + cx, + ) + .on_change(move |value, _, _, cx| { + this.update(cx, |this, cx| { if let Some(form) = &mut this.aws_form { form.is_default = value; } cx.notify(); - })), + }) + }), ) .child( button("aws-cancel", "Cancel", ButtonVariant::Outline, cx) @@ -315,10 +362,12 @@ impl Render for CredentialsScreen { ], Some(self.tab), false, - move |index, _, cx| this.update(cx, |this, cx| { - this.tab = index; - cx.notify(); - }), + move |index, _, cx| { + this.update(cx, |this, cx| { + this.tab = index; + cx.notify(); + }) + }, window, cx, ); @@ -343,10 +392,16 @@ impl Render for CredentialsScreen { .flex() .justify_center() .child( - icon_button("back", IconName::ChevronLeft, "Back", ButtonVariant::Secondary, cx) - .absolute() - .left_0() - .on_click(|_, _, cx| cx.set_global(Screen::Home)), + icon_button( + "back", + IconName::ChevronLeft, + "Back", + ButtonVariant::Secondary, + cx, + ) + .absolute() + .left_0() + .on_click(|_, _, cx| cx.set_global(Screen::Home)), ) .child( div() diff --git a/src/screens/home.rs b/src/screens/home.rs index c870c0c..bd61abe 100644 --- a/src/screens/home.rs +++ b/src/screens/home.rs @@ -5,21 +5,41 @@ use gpui_kit::{ }; use gpui_omarchy::{ActiveTheme, IconName, focus_scope, icon}; -use crate::session::AppSession; use super::Screen; - +use crate::session::AppSession; pub struct HomeScreen {} impl Render for HomeScreen { fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { let t = cx.omarchy(); - let credentials = nav_tile("credentials", IconName::Key, "Credentials", "Add, remove, and change credentials.", t.success, cx) - .on_click(|_, _, cx| cx.set_global(Screen::Credentials)); - let lock = nav_tile("lock", IconName::ShieldCheck, "Lock", "Lock Creddy.", t.warning, cx) - .on_click(|_, _, cx| cx.set_global(AppSession::Locked)); - let exit = nav_tile("exit", IconName::LogOut, "Exit", "Close Creddy.", t.accent, cx) - .on_click(|_, _, cx| cx.quit()); + let credentials = nav_tile( + "credentials", + IconName::Key, + "Credentials", + "Add, remove, and change credentials.", + t.success, + cx, + ) + .on_click(|_, _, cx| cx.set_global(Screen::Credentials)); + let lock = nav_tile( + "lock", + IconName::ShieldCheck, + "Lock", + "Lock Creddy.", + t.warning, + cx, + ) + .on_click(|_, _, cx| cx.set_global(AppSession::Locked)); + let exit = nav_tile( + "exit", + IconName::LogOut, + "Exit", + "Close Creddy.", + t.accent, + cx, + ) + .on_click(|_, _, cx| cx.quit()); focus_scope("home") .size_full() @@ -70,6 +90,16 @@ fn nav_tile( .focus_visible(|s| s.bg(t.hover_fill())) .active(|s| s.bg(t.pressed_fill())) .child(icon(icon_name).size(rems(3.)).text_color(color)) - .child(div().text_size(rems(1.125)).font_weight(FontWeight::BOLD).child(title)) - .child(div().text_size(rems(0.875)).text_center().child(description)) + .child( + div() + .text_size(rems(1.125)) + .font_weight(FontWeight::BOLD) + .child(title), + ) + .child( + div() + .text_size(rems(0.875)) + .text_center() + .child(description), + ) } diff --git a/src/screens/mod.rs b/src/screens/mod.rs index c5ef35a..a697a82 100644 --- a/src/screens/mod.rs +++ b/src/screens/mod.rs @@ -10,7 +10,6 @@ pub use home::HomeScreen; pub use unlock::UnlockScreen; pub use welcome::WelcomeScreen; - /// Which screen to show while the app is unlocked. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Screen { diff --git a/src/screens/unlock.rs b/src/screens/unlock.rs index 6b611c2..eabedb9 100644 --- a/src/screens/unlock.rs +++ b/src/screens/unlock.rs @@ -1,6 +1,6 @@ use gpui_kit::{ - AppContext, BorrowAppContext, Context, Entity, FontWeight, IntoElement, ParentElement, Render, SharedString, - Styled, Subscription, Task, Window, div, rems, + AppContext, BorrowAppContext, Context, Entity, FontWeight, IntoElement, ParentElement, Render, + SharedString, Styled, Subscription, Task, Window, div, rems, }; use gpui_omarchy::{ButtonVariant, button, focus_scope}; @@ -10,7 +10,6 @@ use crate::db::Db; use crate::error::CreddyError; use crate::session::AppSession; - /// Shown at startup when a database exists: enter the passphrase to open it. pub struct UnlockScreen { passphrase: Entity, @@ -71,9 +70,11 @@ impl UnlockScreen { this.pending = None; match result { Ok((db, private_config)) => { - cx.update_global::(|config, _cx| config.merge_private(private_config)); + cx.update_global::(|config, _cx| { + config.merge_private(private_config) + }); cx.set_global(AppSession::Unlocked(db)); - }, + } Err(e) => this.error = Some(error_message(&e)), } cx.notify(); diff --git a/src/screens/welcome.rs b/src/screens/welcome.rs index e017894..d2a96df 100644 --- a/src/screens/welcome.rs +++ b/src/screens/welcome.rs @@ -1,6 +1,6 @@ use gpui_kit::{ AppContext, Context, Entity, FontWeight, IntoElement, ParentElement, Render, SharedString, - Styled, Subscription, Task,Window, div, rems, + Styled, Subscription, Task, Window, div, rems, }; use gpui_omarchy::{ActiveTheme, ButtonVariant, button, focus_scope}; @@ -9,10 +9,8 @@ use crate::config::AppConfig; use crate::db::Db; use crate::session::AppSession; - const MISMATCH: &str = "Passphrases do not match."; - /// First-run screen: choose a passphrase, derive the key, and unlock the session. pub struct WelcomeScreen { passphrase: Entity, @@ -38,17 +36,19 @@ impl WelcomeScreen { let mut _subscriptions = Vec::new(); for input in [&passphrase, &confirm] { - _subscriptions.push(cx.subscribe_in(input, window, |this, _, event, window, cx| { - match event { - PassphraseInputEvent::Submit => this.submit(window, cx), - // typing only dismisses the mismatch error, never raises it - PassphraseInputEvent::Change if this.passphrases_match(cx) => { - this.error = None; - cx.notify(); + _subscriptions.push( + cx.subscribe_in(input, window, |this, _, event, window, cx| { + match event { + PassphraseInputEvent::Submit => this.submit(window, cx), + // typing only dismisses the mismatch error, never raises it + PassphraseInputEvent::Change if this.passphrases_match(cx) => { + this.error = None; + cx.notify(); + } + _ => (), } - _ => (), - } - })); + }), + ); } // leaving the confirm field is what raises the mismatch error _subscriptions.push(cx.subscribe_in(&confirm, window, |this, _, event, _, cx| { @@ -96,9 +96,7 @@ impl WelcomeScreen { self.pending = Some(cx.spawn(async move |this, cx| { // argon2 is deliberately slow, so keep it off the UI thread let result = cx - .background_spawn(async move { - Db::connect(&config, passphrase.as_str()) - }) + .background_spawn(async move { Db::connect(&config, passphrase.as_str()) }) .await; let _ = this.update(cx, |this, cx| { @@ -174,9 +172,9 @@ impl Render for WelcomeScreen { .child( button("submit", "Submit", ButtonVariant::Primary, cx) .disabled(self.pending.is_some()) - .on_click(cx.listener(|this, _, window, cx| { - this.submit(window, cx) - })), + .on_click( + cx.listener(|this, _, window, cx| this.submit(window, cx)), + ), ), ), ) diff --git a/src/session.rs b/src/session.rs index faf000b..c8387d3 100644 --- a/src/session.rs +++ b/src/session.rs @@ -1,6 +1,6 @@ -use gpui_kit::Global; use crate::config::AppConfig; use crate::db::Db; +use gpui_kit::Global; #[derive(Debug)] pub enum AppSession { @@ -24,9 +24,9 @@ impl Global for AppSession {} #[cfg(test)] mod tests { use super::*; + use crate::tests::TestEnv; use std::assert_matches; use testresult::TestResult; - use crate::tests::TestEnv; #[test] fn test_load_empty() -> TestResult { diff --git a/src/srv/creddy_server.rs b/src/srv/creddy_server.rs index e02c940..b3ad366 100644 --- a/src/srv/creddy_server.rs +++ b/src/srv/creddy_server.rs @@ -1,22 +1,21 @@ use crate::error::CreddyError; use gpui_kit::AsyncApp; use http_body_util::Full; -use hyper::{Request, Response, StatusCode}; -use hyper::body::{Incoming, Bytes}; -use hyper::service::service_fn; +use hyper::body::{Bytes, Incoming}; use hyper::server::conn::http1; +use hyper::service::service_fn; +use hyper::{Request, Response, StatusCode}; +use rustix::net::sockopt::socket_peercred; +use rustix::process::Pid; use smol::Timer; use smol::net::unix::{UnixListener, UnixStream}; use smol_hyper::rt::FuturesIo; -use rustix::net::sockopt::socket_peercred; -use rustix::process::Pid; use std::convert::Infallible; use std::fs; use std::io; use std::path::Path; use std::time::Duration; - pub fn start_creddy_server(path: &Path, app: AsyncApp) -> Result<(), CreddyError> { if path.exists() { fs::remove_file(path)?; @@ -42,14 +41,15 @@ pub fn start_creddy_server(path: &Path, app: AsyncApp) -> Result<(), CreddyError if let Err(e) = conn.await { eprintln!("Error serving connection: {e}") } - }).detach(); + }) + .detach(); } - }).detach(); + }) + .detach(); Ok(()) } - async fn accept(listener: &UnixListener) -> io::Result<(UnixStream, Pid)> { let (stream, _) = listener.accept().await?; // pid() never returns None on Linux @@ -57,8 +57,11 @@ async fn accept(listener: &UnixListener) -> io::Result<(UnixStream, Pid)> { Ok((stream, pid)) } - -async fn handle(req: Request, pid: Pid, app: AsyncApp) -> Result>, Infallible> { +async fn handle( + req: Request, + pid: Pid, + app: AsyncApp, +) -> Result>, Infallible> { Ok(Response::new(Full::new(Bytes::from("hello world")))) } diff --git a/src/tests/mod.rs b/src/tests/mod.rs index 1acab24..b6124c0 100644 --- a/src/tests/mod.rs +++ b/src/tests/mod.rs @@ -1,7 +1,3 @@ -use gpui_kit::{AnyWindowHandle, App, AppContext, TestAppContext, Window}; -use gpui_kit::test::TestWindowExt; -use tempfile::TempDir; -use uuid::Uuid; use crate::app::launch; use crate::config::AppConfig; use crate::credentials::AwsCredential; @@ -9,7 +5,10 @@ use crate::db::Db; use crate::error::CreddyError; use crate::screens::Screen; use crate::session::AppSession; - +use gpui_kit::test::TestWindowExt; +use gpui_kit::{AnyWindowHandle, App, AppContext, TestAppContext, Window}; +use tempfile::TempDir; +use uuid::Uuid; pub const TEST_PASSPHRASE: &'static str = "correct horse battery staple"; @@ -34,23 +33,20 @@ impl TestEnv { /// Start the app against the test environment, as `main` would. fn open_app(env: &TestEnv, cx: &mut TestAppContext) -> AnyWindowHandle { - let window = cx.update(|cx| { - launch( - cx, - env.config.clone(), - AppSession::load(&env.config), - ) - }); + let window = cx.update(|cx| launch(cx, env.config.clone(), AppSession::load(&env.config))); // first frame, so that elements exist to be found - cx.update_window(window.into(), |_, window, cx| window.render_frame(cx)).unwrap(); + cx.update_window(window.into(), |_, window, cx| window.render_frame(cx)) + .unwrap(); window.into() } /// Do something in the window, then let any resulting tasks (e.g. the KDF) finish. fn act(window: AnyWindowHandle, cx: &mut TestAppContext, f: impl FnOnce(&mut Window, &mut App)) { - cx.update_window(window, |_, window, cx| f(window, cx)).unwrap(); + cx.update_window(window, |_, window, cx| f(window, cx)) + .unwrap(); cx.run_until_parked(); - cx.update_window(window, |_, window, cx| window.render_frame(cx)).unwrap(); + cx.update_window(window, |_, window, cx| window.render_frame(cx)) + .unwrap(); } /// Click into a field and type. @@ -68,8 +64,11 @@ fn click(window: AnyWindowHandle, id: &'static str, cx: &mut TestAppContext) { /// The message in the error alert, if one is showing. fn error_message(window: AnyWindowHandle, cx: &mut TestAppContext) -> Option { cx.update_window(window, |_, window, _| { - window.try_find("error").and_then(|e| e.label().map(String::from)) - }).unwrap() + window + .try_find("error") + .and_then(|e| e.label().map(String::from)) + }) + .unwrap() } fn is_unlocked(cx: &TestAppContext) -> bool { @@ -99,7 +98,10 @@ fn test_welcome_mismatch(cx: &mut TestAppContext) { fill(window, "confirm", "something else", cx); click(window, "submit", cx); - assert_eq!(error_message(window, cx).as_deref(), Some("Passphrases do not match.")); + assert_eq!( + error_message(window, cx).as_deref(), + Some("Passphrases do not match.") + ); assert!(!is_unlocked(cx)); assert!(!env.config.db_path().exists()); } @@ -111,7 +113,10 @@ fn test_welcome_empty(cx: &mut TestAppContext) { click(window, "submit", cx); - assert_eq!(error_message(window, cx).as_deref(), Some("Passphrase is empty.")); + assert_eq!( + error_message(window, cx).as_deref(), + Some("Passphrase is empty.") + ); assert!(!is_unlocked(cx)); assert!(!env.config.db_path().exists()); } @@ -138,7 +143,10 @@ fn test_unlock_wrong_passphrase(cx: &mut TestAppContext) { fill(window, "passphrase", "not the passphrase", cx); click(window, "submit", cx); - assert_eq!(error_message(window, cx).as_deref(), Some("Incorrect passphrase.")); + assert_eq!( + error_message(window, cx).as_deref(), + Some("Incorrect passphrase.") + ); assert!(!is_unlocked(cx)); } @@ -147,11 +155,17 @@ fn test_unlock_restores_private_config(cx: &mut TestAppContext) { let env = TestEnv::new().unwrap(); let mut saved = env.config.clone(); saved.rehide_ms = 5000; - env.db().unwrap().save_private_config(&saved.private_config()).unwrap(); + env.db() + .unwrap() + .save_private_config(&saved.private_config()) + .unwrap(); let window = open_app(&env, cx); // before unlocking, only the defaults are available - assert_eq!(cx.read(|cx| cx.global::().rehide_ms), env.config.rehide_ms); + assert_eq!( + cx.read(|cx| cx.global::().rehide_ms), + env.config.rehide_ms + ); fill(window, "passphrase", TEST_PASSPHRASE, cx); click(window, "submit", cx); @@ -175,12 +189,16 @@ fn test_lock(cx: &mut TestAppContext) { // The unlock screen should be a new one, not the old one with the passphrase still in it. // The masked input doesn't expose its value, so check by submitting it as-is. click(window, "submit", cx); - assert_eq!(error_message(window, cx).as_deref(), Some("Passphrase is empty.")); + assert_eq!( + error_message(window, cx).as_deref(), + Some("Passphrase is empty.") + ); assert!(!is_unlocked(cx)); } fn is_visible(window: AnyWindowHandle, id: &'static str, cx: &mut TestAppContext) -> bool { - cx.update_window(window, |_, window, _| window.try_find(id).is_some()).unwrap() + cx.update_window(window, |_, window, _| window.try_find(id).is_some()) + .unwrap() } #[gpui_kit::test] @@ -218,10 +236,14 @@ fn test_credentials_tabs(cx: &mut TestAppContext) { assert!(is_visible(window, "work", cx)); - act(window, cx, |window, cx| window.within("credential-tabs").click(1usize, cx)); + act(window, cx, |window, cx| { + window.within("credential-tabs").click(1usize, cx) + }); assert!(!is_visible(window, "work", cx)); - act(window, cx, |window, cx| window.within("credential-tabs").click(0usize, cx)); + act(window, cx, |window, cx| { + window.within("credential-tabs").click(0usize, cx) + }); assert!(is_visible(window, "work", cx)); } @@ -246,7 +268,9 @@ fn test_add_aws_credential(cx: &mut TestAppContext) { assert!(!is_visible(window, "aws-save", cx)); let saved = cx.read(|cx| { - let AppSession::Unlocked(db) = cx.global::() else { panic!("locked") }; + let AppSession::Unlocked(db) = cx.global::() else { + panic!("locked") + }; db.load_aws_credential("work").unwrap() }); assert_eq!(saved.access_key_id, "AKIAEXAMPLE"); @@ -267,7 +291,10 @@ fn test_add_aws_credential_missing_fields(cx: &mut TestAppContext) { fill(window, "aws-name", "work", cx); click(window, "aws-save", cx); - assert_eq!(error_message(window, cx).as_deref(), Some("All fields are required.")); + assert_eq!( + error_message(window, cx).as_deref(), + Some("All fields are required.") + ); assert!(!is_visible(window, "work", cx)); } @@ -298,7 +325,9 @@ fn test_add_aws_credential_duplicate_name(cx: &mut TestAppContext) { Some("An AWS credential named \"work\" already exists."), ); let saved = cx.read(|cx| { - let AppSession::Unlocked(db) = cx.global::() else { panic!("locked") }; + let AppSession::Unlocked(db) = cx.global::() else { + panic!("locked") + }; db.load_aws_credential("work").unwrap() }); assert_eq!(saved.access_key_id, "AKIAEXAMPLE"); @@ -334,7 +363,9 @@ fn test_edit_aws_credential(cx: &mut TestAppContext) { assert!(!is_visible(window, "work", cx)); let creds = cx.read(|cx| { - let AppSession::Unlocked(db) = cx.global::() else { panic!("locked") }; + let AppSession::Unlocked(db) = cx.global::() else { + panic!("locked") + }; db.list_aws_credentials().unwrap() }); assert_eq!(creds.len(), 1); @@ -372,7 +403,9 @@ fn test_delete_aws_credential(cx: &mut TestAppContext) { assert!(!is_visible(window, "work", cx)); let creds = cx.read(|cx| { - let AppSession::Unlocked(db) = cx.global::() else { panic!("locked") }; + let AppSession::Unlocked(db) = cx.global::() else { + panic!("locked") + }; db.list_aws_credentials().unwrap() }); assert!(creds.is_empty());