formatting pass

This commit is contained in:
jfmonty2 committed 2026-11-22 06:17:04 -05:00
1 parent d976eebbbc
commit e4cfa53bce
21 files changed
+333 -194

No files matched your search

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