diff options
| author | Benedikt Peetz <benedikt.peetz@b-peetz.de> | 2026-06-12 17:16:19 +0200 |
|---|---|---|
| committer | Benedikt Peetz <benedikt.peetz@b-peetz.de> | 2026-06-12 17:16:19 +0200 |
| commit | 2ca7dd57b12861e8c9bbc9238cda612e0ff22ff3 (patch) | |
| tree | 302a644f6a50d60cc8304c4498fe6bbb72ddaaa9 /crates/turtle/src/atuin_client | |
| parent | feat(server): Really make users stateless (with tests) (diff) | |
| download | atuin-2ca7dd57b12861e8c9bbc9238cda612e0ff22ff3.zip | |
chore(treewide): Cleanup themes
Diffstat (limited to 'crates/turtle/src/atuin_client')
| -rw-r--r-- | crates/turtle/src/atuin_client/database.rs | 99 | ||||
| -rw-r--r-- | crates/turtle/src/atuin_client/history.rs | 61 | ||||
| -rw-r--r-- | crates/turtle/src/atuin_client/history/store.rs | 2 | ||||
| -rw-r--r-- | crates/turtle/src/atuin_client/mod.rs | 2 | ||||
| -rw-r--r-- | crates/turtle/src/atuin_client/record/mod.rs | 3 | ||||
| -rw-r--r-- | crates/turtle/src/atuin_client/record/sqlite_store.rs | 94 | ||||
| -rw-r--r-- | crates/turtle/src/atuin_client/record/store.rs | 60 | ||||
| -rw-r--r-- | crates/turtle/src/atuin_client/record/sync.rs | 28 | ||||
| -rw-r--r-- | crates/turtle/src/atuin_client/settings.rs | 91 | ||||
| -rw-r--r-- | crates/turtle/src/atuin_client/settings/watcher.rs | 70 | ||||
| -rw-r--r-- | crates/turtle/src/atuin_client/theme.rs | 846 | ||||
| -rw-r--r-- | crates/turtle/src/atuin_client/utils.rs | 1 |
12 files changed, 150 insertions, 1207 deletions
diff --git a/crates/turtle/src/atuin_client/database.rs b/crates/turtle/src/atuin_client/database.rs index f8b73809..6a2d5887 100644 --- a/crates/turtle/src/atuin_client/database.rs +++ b/crates/turtle/src/atuin_client/database.rs @@ -8,7 +8,6 @@ use std::{ use crate::atuin_common::utils; use fs_err as fs; use itertools::Itertools; -use rand::{Rng, distributions::Alphanumeric}; use sql_builder::{SqlBuilder, SqlName, bind::Bind, esc, quote}; use sqlx::{ Result, Row, @@ -192,8 +191,10 @@ impl ClientSqlite { History::from_db() .id(row.get("id")) .timestamp( - OffsetDateTime::from_unix_timestamp_nanos(row.get::<i64, _>("timestamp") as i128) - .unwrap(), + OffsetDateTime::from_unix_timestamp_nanos(i128::from( + row.get::<i64, _>("timestamp"), + )) + .unwrap(), ) .duration(row.get("duration")) .exit(row.get("exit")) @@ -247,31 +248,6 @@ impl ClientSqlite { Ok(res) } - pub(crate) async fn update(&self, h: &History) -> Result<()> { - debug!("updating sqlite history"); - - sqlx::query( - "update history - set timestamp = ?2, duration = ?3, exit = ?4, command = ?5, cwd = ?6, session = ?7, hostname = ?8, author = ?9, intent = ?10, deleted_at = ?11 - where id = ?1", - ) - .bind(h.id.0.as_str()) - .bind(h.timestamp.unix_timestamp_nanos() as i64) - .bind(h.duration) - .bind(h.exit) - .bind(h.command.as_str()) - .bind(h.cwd.as_str()) - .bind(h.session.as_str()) - .bind(h.hostname.as_str()) - .bind(h.author.as_str()) - .bind(h.intent.as_deref()) - .bind(h.deleted_at.map(|t|t.unix_timestamp_nanos() as i64)) - .execute(&self.pool) - .await?; - - Ok(()) - } - // make a unique list, that only shows the *newest* version of things pub(crate) async fn list( &self, @@ -452,9 +428,9 @@ impl ClientSqlite { if !is_or { is_or = true; continue; - } else { - format!("{glob}|{glob}") } + + format!("{glob}|{glob}") } QueryToken::MatchStart(term, _) => { format!("{term}{glob}") @@ -584,22 +560,6 @@ impl ClientSqlite { Paged::new(self.clone(), page_size, include_deleted, unique) } - // deleted_at doesn't mean the actual time that the user deleted it, - // but the time that the system marks it as deleted - pub(crate) async fn delete(&self, mut h: History) -> Result<()> { - let now = OffsetDateTime::now_utc(); - h.command = rand::thread_rng() - .sample_iter(&Alphanumeric) - .take(32) - .map(char::from) - .collect(); // overwrite with random string - h.deleted_at = Some(now); // delete it - - self.update(&h).await?; // save it - - Ok(()) - } - pub(crate) async fn delete_rows(&self, ids: &[HistoryId]) -> Result<()> { let mut tx = self.pool.begin().await?; @@ -1233,53 +1193,6 @@ mod test { } #[tokio::test(flavor = "multi_thread")] - async fn test_paged_include_deleted() { - let mut db = ClientSqlite::new("sqlite::memory:", test_local_timeout()) - .await - .unwrap(); - - // Add items - new_history_item(&mut db, "keep1").await.unwrap(); - new_history_item(&mut db, "keep2").await.unwrap(); - new_history_item(&mut db, "delete_me").await.unwrap(); - - // Delete one item - let all = db - .list( - &[], - &Context { - hostname: "".to_string(), - session: "".to_string(), - cwd: "".to_string(), - host_id: "".to_string(), - git_root: None, - }, - None, - false, - false, - ) - .await - .unwrap(); - - let to_delete = all - .iter() - .find(|h| h.command == "delete_me") - .unwrap() - .clone(); - db.delete(to_delete).await.unwrap(); - - // Without include_deleted - should get 2 - let mut paged = db.all_paged(10, false, false); - let page = paged.next().await.unwrap().unwrap(); - assert_eq!(page.len(), 2); - - // With include_deleted - should get 3 - let mut paged_deleted = db.all_paged(10, true, false); - let page_deleted = paged_deleted.next().await.unwrap().unwrap(); - assert_eq!(page_deleted.len(), 3); - } - - #[tokio::test(flavor = "multi_thread")] async fn test_search_bench_dupes() { let context = Context { hostname: "test:host".to_string(), diff --git a/crates/turtle/src/atuin_client/history.rs b/crates/turtle/src/atuin_client/history.rs index 5e2f89f2..1f89cd71 100644 --- a/crates/turtle/src/atuin_client/history.rs +++ b/crates/turtle/src/atuin_client/history.rs @@ -61,24 +61,34 @@ pub(crate) struct History { /// /// Stored as `client_id` in the database. pub(crate) id: HistoryId, + /// When the command was run. pub(crate) timestamp: OffsetDateTime, + /// How long the command took to run. pub(crate) duration: i64, + /// The exit code of the command. pub(crate) exit: i64, + /// The command that was run. pub(crate) command: String, + /// The current working directory when the command was run. pub(crate) cwd: String, + /// The session ID, associated with a terminal session. pub(crate) session: String, + /// The hostname of the machine the command was run on. pub(crate) hostname: String, + /// Who wrote this command (human user or automation/agent identity). pub(crate) author: String, + /// Optional rationale for why the command was executed. pub(crate) intent: Option<String>, + /// Timestamp, which is set when the entry is deleted, allowing a soft delete. pub(crate) deleted_at: Option<OffsetDateTime>, } @@ -87,7 +97,7 @@ pub(crate) struct History { pub(crate) struct HistoryStats { /// The command that was ran after this one in the session pub(crate) next: Option<History>, - /// + /// The command that was ran before this one in the session pub(crate) previous: Option<History>, @@ -333,7 +343,7 @@ impl History { Ok(History { id: id.to_owned().into(), - timestamp: OffsetDateTime::from_unix_timestamp_nanos(timestamp as i128)?, + timestamp: OffsetDateTime::from_unix_timestamp_nanos(i128::from(timestamp))?, duration, exit, command: command.to_owned(), @@ -343,7 +353,7 @@ impl History { author: author.unwrap_or_else(|| Self::author_from_hostname(hostname)), intent, deleted_at: deleted_at - .map(|t| OffsetDateTime::from_unix_timestamp_nanos(t as i128)) + .map(|t| OffsetDateTime::from_unix_timestamp_nanos(i128::from(t))) .transpose()?, }) } @@ -357,51 +367,6 @@ impl History { } } - /// Builder for a history entry that is imported from shell history. - /// - /// The only two required fields are `timestamp` and `command`. - /// - /// ## Examples - /// ``` - /// use crate::atuin_client::history::History; - /// - /// let history: History = History::import() - /// .timestamp(time::OffsetDateTime::now_utc()) - /// .command("ls -la") - /// .build() - /// .into(); - /// ``` - /// - /// If shell history contains more information, it can be added to the builder: - /// ``` - /// use crate::atuin_client::history::History; - /// - /// let history: History = History::import() - /// .timestamp(time::OffsetDateTime::now_utc()) - /// .command("ls -la") - /// .cwd("/home/user") - /// .exit(0) - /// .duration(100) - /// .build() - /// .into(); - /// ``` - /// - /// Unknown command or command without timestamp cannot be imported, which - /// is forced at compile time: - /// - /// ```compile_fail - /// use crate::atuin_client::history::History; - /// - /// // this will not compile because timestamp is missing - /// let history: History = History::import() - /// .command("ls -la") - /// .build() - /// .into(); - /// ``` - pub(crate) fn import() -> builder::HistoryImportedBuilder { - builder::HistoryImported::builder() - } - /// Builder for a history entry that is captured via hook. /// /// This builder is used only at the `start` step of the hook, diff --git a/crates/turtle/src/atuin_client/history/store.rs b/crates/turtle/src/atuin_client/history/store.rs index a8162e21..c6e079f3 100644 --- a/crates/turtle/src/atuin_client/history/store.rs +++ b/crates/turtle/src/atuin_client/history/store.rs @@ -7,7 +7,7 @@ use tracing::debug; use crate::atuin_client::{ database::{ClientSqlite, current_context}, - record::{encryption::PASETO_V4, sqlite_store::SqliteStore, store::Store}, + record::{encryption::PASETO_V4, sqlite_store::SqliteStore}, }; use crate::atuin_common::record::{DecryptedData, Host, HostId, Record, RecordId, RecordIdx}; diff --git a/crates/turtle/src/atuin_client/mod.rs b/crates/turtle/src/atuin_client/mod.rs index 530b7d81..851dfbdb 100644 --- a/crates/turtle/src/atuin_client/mod.rs +++ b/crates/turtle/src/atuin_client/mod.rs @@ -1,6 +1,4 @@ -#[cfg(feature = "sync")] pub(crate) mod api_client; - pub(crate) mod database; pub(crate) mod encryption; pub(crate) mod history; diff --git a/crates/turtle/src/atuin_client/record/mod.rs b/crates/turtle/src/atuin_client/record/mod.rs index 175c7a9d..4e5774ea 100644 --- a/crates/turtle/src/atuin_client/record/mod.rs +++ b/crates/turtle/src/atuin_client/record/mod.rs @@ -1,6 +1,3 @@ pub(crate) mod encryption; pub(crate) mod sqlite_store; -pub(crate) mod store; - -#[cfg(feature = "sync")] pub(crate) mod sync; diff --git a/crates/turtle/src/atuin_client/record/sqlite_store.rs b/crates/turtle/src/atuin_client/record/sqlite_store.rs index f8eab076..24188443 100644 --- a/crates/turtle/src/atuin_client/record/sqlite_store.rs +++ b/crates/turtle/src/atuin_client/record/sqlite_store.rs @@ -5,7 +5,6 @@ use std::str::FromStr; use std::{path::Path, time::Duration}; -use async_trait::async_trait; use eyre::{Result, eyre}; use fs_err as fs; @@ -22,7 +21,6 @@ use crate::atuin_common::utils; use uuid::Uuid; use super::encryption::PASETO_V4; -use super::store::Store; #[derive(Debug, Clone)] pub(crate) struct SqliteStore { @@ -37,7 +35,8 @@ impl SqliteStore { if utils::broken_symlink(path) { eprintln!( - "Atuin: Sqlite db path ({path:?}) is a broken symlink. Unable to read or create replacement." + "Atuin: Sqlite db path ({}) is a broken symlink. Unable to read or create replacement.", + path.display() ); std::process::exit(1); } @@ -128,9 +127,18 @@ impl SqliteStore { } } -#[async_trait] -impl Store for SqliteStore { - async fn push_batch( +/// A record store stores records +/// In more detail - we tend to need to process this into _another_ format to actually query it. +/// As is, the record store is intended as the source of truth for arbitrary data, which could +/// be shell history, kvs, etc. +impl SqliteStore { + /// Push a record + pub(crate) async fn push(&self, record: &Record<EncryptedData>) -> Result<()> { + self.push_batch(std::iter::once(record)).await + } + + /// Push a batch of records, all in one transaction + pub(crate) async fn push_batch( &self, records: impl Iterator<Item = &Record<EncryptedData>> + Send + Sync, ) -> Result<()> { @@ -145,7 +153,7 @@ impl Store for SqliteStore { Ok(()) } - async fn get(&self, id: RecordId) -> Result<Record<EncryptedData>> { + pub(crate) async fn get(&self, id: RecordId) -> Result<Record<EncryptedData>> { let res = sqlx::query("select * from store where store.id = ?1") .bind(id.0.as_hyphenated().to_string()) .map(Self::query_row) @@ -155,7 +163,7 @@ impl Store for SqliteStore { Ok(res) } - async fn delete(&self, id: RecordId) -> Result<()> { + pub(crate) async fn delete(&self, id: RecordId) -> Result<()> { sqlx::query("delete from store where id = ?1") .bind(id.0.as_hyphenated().to_string()) .execute(&self.pool) @@ -164,13 +172,17 @@ impl Store for SqliteStore { Ok(()) } - async fn delete_all(&self) -> Result<()> { + pub(crate) async fn delete_all(&self) -> Result<()> { sqlx::query("delete from store").execute(&self.pool).await?; Ok(()) } - async fn last(&self, host: HostId, tag: &str) -> Result<Option<Record<EncryptedData>>> { + pub(crate) async fn last( + &self, + host: HostId, + tag: &str, + ) -> Result<Option<Record<EncryptedData>>> { let res = sqlx::query("select * from store where host=?1 and tag=?2 order by idx desc limit 1") .bind(host.0.as_hyphenated().to_string()) @@ -186,21 +198,15 @@ impl Store for SqliteStore { } } - async fn first(&self, host: HostId, tag: &str) -> Result<Option<Record<EncryptedData>>> { + pub(crate) async fn first( + &self, + host: HostId, + tag: &str, + ) -> Result<Option<Record<EncryptedData>>> { self.idx(host, tag, 0).await } - async fn len_all(&self) -> Result<u64> { - let res: Result<(i64,), sqlx::Error> = sqlx::query_as("select count(*) from store") - .fetch_one(&self.pool) - .await; - match res { - Err(e) => Err(eyre!("failed to fetch local store len: {}", e)), - Ok(v) => Ok(v.0 as u64), - } - } - - async fn len_tag(&self, tag: &str) -> Result<u64> { + pub(crate) async fn len_tag(&self, tag: &str) -> Result<u64> { let res: Result<(i64,), sqlx::Error> = sqlx::query_as("select count(*) from store where tag=?1") .bind(tag) @@ -212,17 +218,8 @@ impl Store for SqliteStore { } } - async fn len(&self, host: HostId, tag: &str) -> Result<u64> { - let last = self.last(host, tag).await?; - - if let Some(last) = last { - return Ok(last.idx + 1); - } - - return Ok(0); - } - - async fn next( + /// Get the next `limit` records, after and including the given index + pub(crate) async fn next( &self, host: HostId, tag: &str, @@ -243,7 +240,8 @@ impl Store for SqliteStore { Ok(res) } - async fn idx( + /// Get the first record for a given host and tag + pub(crate) async fn idx( &self, host: HostId, tag: &str, @@ -264,7 +262,7 @@ impl Store for SqliteStore { } } - async fn status(&self) -> Result<RecordStatus> { + pub(crate) async fn status(&self) -> Result<RecordStatus> { let mut status = RecordStatus::new(); let res: Result<Vec<(String, String, i64)>, sqlx::Error> = @@ -288,7 +286,8 @@ impl Store for SqliteStore { Ok(status) } - async fn all_tagged(&self, tag: &str) -> Result<Vec<Record<EncryptedData>>> { + /// Get all records for a given tag + pub(crate) async fn all_tagged(&self, tag: &str) -> Result<Vec<Record<EncryptedData>>> { let res = sqlx::query("select * from store where tag = ?1 order by timestamp asc") .bind(tag) .map(Self::query_row) @@ -300,7 +299,7 @@ impl Store for SqliteStore { /// Reencrypt every single item in this store with a new key /// Be careful - this may mess with sync. - async fn re_encrypt(&self, old_key: &[u8; 32], new_key: &[u8; 32]) -> Result<()> { + pub(crate) async fn re_encrypt(&self, old_key: &[u8; 32], new_key: &[u8; 32]) -> Result<()> { // Load all the records // In memory like some of the other code here // This will never be called in a hot loop, and only under the following circumstances @@ -339,7 +338,7 @@ impl Store for SqliteStore { /// Verify that every record in this store can be decrypted with the current key /// Someday maybe also check each tag/record can be deserialized, but not for now. - async fn verify(&self, key: &[u8; 32]) -> Result<()> { + pub(crate) async fn verify(&self, key: &[u8; 32]) -> Result<()> { let all = self.load_all().await?; all.into_iter() @@ -351,7 +350,7 @@ impl Store for SqliteStore { /// Verify that every record in this store can be decrypted with the current key /// Someday maybe also check each tag/record can be deserialized, but not for now. - async fn purge(&self, key: &[u8; 32]) -> Result<()> { + pub(crate) async fn purge(&self, key: &[u8; 32]) -> Result<()> { let all = self.load_all().await?; for record in all.iter() { @@ -374,15 +373,16 @@ impl Store for SqliteStore { #[cfg(test)] mod tests { - use crate::atuin_common::{ - record::{DecryptedData, EncryptedData, Host, HostId, Record}, - utils::uuid_v7, - }; - use crate::{ - encryption::generate_encoded_key, - record::{encryption::PASETO_V4, store::Store}, - settings::test_local_timeout, + atuin_client::{ + encryption::generate_encoded_key, record::encryption::PASETO_V4, + settings::test_local_timeout, + }, + atuin_common::{ + self, + record::{DecryptedData, EncryptedData, Host, HostId, Record}, + utils::uuid_v7, + }, }; use super::SqliteStore; diff --git a/crates/turtle/src/atuin_client/record/store.rs b/crates/turtle/src/atuin_client/record/store.rs deleted file mode 100644 index db832a0d..00000000 --- a/crates/turtle/src/atuin_client/record/store.rs +++ /dev/null @@ -1,60 +0,0 @@ -use async_trait::async_trait; -use eyre::Result; - -use crate::atuin_common::record::{EncryptedData, HostId, Record, RecordId, RecordIdx, RecordStatus}; - -/// A record store stores records -/// In more detail - we tend to need to process this into _another_ format to actually query it. -/// As is, the record store is intended as the source of truth for arbitrary data, which could -/// be shell history, kvs, etc. -#[async_trait] -pub(crate) trait Store { - // Push a record - async fn push(&self, record: &Record<EncryptedData>) -> Result<()> { - self.push_batch(std::iter::once(record)).await - } - - // Push a batch of records, all in one transaction - async fn push_batch( - &self, - records: impl Iterator<Item = &Record<EncryptedData>> + Send + Sync, - ) -> Result<()>; - - async fn get(&self, id: RecordId) -> Result<Record<EncryptedData>>; - - async fn delete(&self, id: RecordId) -> Result<()>; - async fn delete_all(&self) -> Result<()>; - - async fn len_all(&self) -> Result<u64>; - async fn len(&self, host: HostId, tag: &str) -> Result<u64>; - async fn len_tag(&self, tag: &str) -> Result<u64>; - - async fn last(&self, host: HostId, tag: &str) -> Result<Option<Record<EncryptedData>>>; - async fn first(&self, host: HostId, tag: &str) -> Result<Option<Record<EncryptedData>>>; - - async fn re_encrypt(&self, old_key: &[u8; 32], new_key: &[u8; 32]) -> Result<()>; - async fn verify(&self, key: &[u8; 32]) -> Result<()>; - async fn purge(&self, key: &[u8; 32]) -> Result<()>; - - /// Get the next `limit` records, after and including the given index - async fn next( - &self, - host: HostId, - tag: &str, - idx: RecordIdx, - limit: u64, - ) -> Result<Vec<Record<EncryptedData>>>; - - /// Get the first record for a given host and tag - async fn idx( - &self, - host: HostId, - tag: &str, - idx: RecordIdx, - ) -> Result<Option<Record<EncryptedData>>>; - - async fn status(&self) -> Result<RecordStatus>; - - /// Get all records for a given tag - async fn all_tagged(&self, tag: &str) -> Result<Vec<Record<EncryptedData>>>; -} diff --git a/crates/turtle/src/atuin_client/record/sync.rs b/crates/turtle/src/atuin_client/record/sync.rs index 9a7abfba..a86fc7a9 100644 --- a/crates/turtle/src/atuin_client/record/sync.rs +++ b/crates/turtle/src/atuin_client/record/sync.rs @@ -5,7 +5,8 @@ use eyre::{OptionExt, Result}; use thiserror::Error; use tracing::error; -use super::{encryption::PASETO_V4, store::Store}; +use super::encryption::PASETO_V4; +use crate::atuin_client::record::sqlite_store::SqliteStore; use crate::atuin_client::{api_client::Client, settings::Settings}; use crate::atuin_common::record::{Diff, HostId, RecordId, RecordIdx, RecordStatus}; @@ -58,7 +59,7 @@ pub(crate) enum Operation { }, } -pub(crate) async fn build_client(settings: &Settings) -> Result<Client<'_>, SyncError> { +pub(crate) fn build_client(settings: &Settings) -> Result<Client<'_>, SyncError> { Client::new( &settings.sync.address, settings.network_connect_timeout, @@ -75,7 +76,7 @@ pub(crate) async fn build_client(settings: &Settings) -> Result<Client<'_>, Sync pub(crate) async fn diff( client: &Client<'_>, - store: &impl Store, + store: &SqliteStore, ) -> Result<(Vec<Diff>, RecordStatus), SyncError> { let local_index = store .status() @@ -96,9 +97,9 @@ pub(crate) async fn diff( // With the store as context, we can determine if a tail exists locally or not and therefore if it needs uploading or download. // In theory this could be done as a part of the diffing stage, but it's easier to reason // about and test this way -pub(crate) async fn operations( +pub(crate) fn operations( diffs: Vec<Diff>, - _store: &impl Store, + _store: &SqliteStore, ) -> Result<Vec<Operation>, SyncError> { let mut operations = Vec::with_capacity(diffs.len()); @@ -170,7 +171,7 @@ pub(crate) async fn operations( } async fn sync_upload( - store: &impl Store, + store: &SqliteStore, client: &Client<'_>, host: HostId, tag: String, @@ -229,7 +230,7 @@ async fn sync_upload( } async fn sync_download( - store: &impl Store, + store: &SqliteStore, client: &Client<'_>, host: HostId, tag: String, @@ -288,7 +289,7 @@ async fn sync_download( pub(crate) async fn sync_remote( client: &Client<'_>, operations: Vec<Operation>, - local_store: &impl Store, + local_store: &SqliteStore, page_size: u64, ) -> Result<(i64, Vec<RecordId>), SyncError> { let mut uploaded = 0; @@ -304,7 +305,7 @@ pub(crate) async fn sync_remote( remote, } => { uploaded += - sync_upload(local_store, client, host, tag, local, remote, page_size).await? + sync_upload(local_store, client, host, tag, local, remote, page_size).await?; } Operation::Download { @@ -315,7 +316,7 @@ pub(crate) async fn sync_remote( } => { let mut d = sync_download(local_store, client, host, tag, local, remote, page_size).await?; - downloaded.append(&mut d) + downloaded.append(&mut d); } Operation::Noop { .. } => continue, @@ -358,16 +359,16 @@ pub(crate) async fn check_encryption_key( pub(crate) async fn sync( settings: &Settings, - store: &impl Store, + store: &SqliteStore, encryption_key: &[u8; 32], ) -> Result<(i64, Vec<RecordId>), SyncError> { - let client = build_client(settings).await?; + let client = build_client(settings)?; let (diff, remote_index) = diff(&client, store).await?; // Bail before mutating either side if the local key can't read the remote. check_encryption_key(&client, &remote_index, encryption_key).await?; - let operations = operations(diff, store).await?; + let operations = operations(diff, store)?; let (uploaded, downloaded) = sync_remote(&client, operations, store, 100).await?; Ok((uploaded, downloaded)) @@ -382,7 +383,6 @@ mod tests { record::{ encryption::PASETO_V4, sqlite_store::SqliteStore, - store::Store, sync::{self, Operation}, }, settings::test_local_timeout, diff --git a/crates/turtle/src/atuin_client/settings.rs b/crates/turtle/src/atuin_client/settings.rs index d84e2eb0..c966ba67 100644 --- a/crates/turtle/src/atuin_client/settings.rs +++ b/crates/turtle/src/atuin_client/settings.rs @@ -14,7 +14,6 @@ use config::{ }; use eyre::{Context, Error, Result, bail, eyre}; use fs_err::{File, create_dir_all}; -use humantime::parse_duration; use regex::RegexSet; use serde::{Deserialize, Serialize}; use serde_with::DeserializeFromStr; @@ -222,7 +221,6 @@ pub(crate) enum KeymapMode { Auto, } - // We want to translate the config to crossterm::cursor::SetCursorStyle, but // the original type does not implement trait serde::Deserialize unfortunately. // It seems impossible to implement Deserialize for external types when it is @@ -252,7 +250,6 @@ pub(crate) enum CursorStyle { SteadyBar, } - #[derive(Clone, Debug, Deserialize, Serialize)] pub(crate) struct Stats { #[serde(default = "Stats::common_prefix_default")] @@ -336,17 +333,6 @@ impl Keys { prefix: "a".to_string(), } } - - /// Returns true if any value differs from the standard defaults. - pub(crate) fn has_non_default_values(&self) -> bool { - let d = Self::standard_defaults(); - self.scroll_exits != d.scroll_exits - || self.exit_past_line_start != d.exit_past_line_start - || self.accept_past_line_end != d.accept_past_line_end - || self.accept_past_line_start != d.accept_past_line_start - || self.accept_with_backspace != d.accept_with_backspace - || self.prefix != d.prefix - } } /// A single rule within a conditional keybinding config. @@ -403,24 +389,7 @@ pub(crate) struct Preview { } #[derive(Clone, Debug, Deserialize, Serialize)] -pub(crate) struct Theme { - /// Name of desired theme ("default" for base) - pub(crate) name: String, - - /// Whether any available additional theme debug should be shown - pub(crate) debug: Option<bool>, - - /// How many levels of parenthood will be traversed if needed - pub(crate) max_depth: Option<u8>, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] pub(crate) struct Daemon { - /// Use the daemon to sync - /// If enabled, history hooks are routed through the daemon. - #[serde(alias = "enable")] - pub(crate) enabled: bool, - /// Automatically start and manage a local daemon when needed. pub(crate) autostart: bool, @@ -534,24 +503,13 @@ impl Default for Preview { } } -impl Default for Theme { - fn default() -> Self { - Self { - name: "".to_string(), - debug: None::<bool>, - max_depth: Some(10), - } - } -} - impl Default for Daemon { fn default() -> Self { Self { - enabled: false, autostart: false, sync_frequency: 300, - socket_path: "".to_string(), - pidfile_path: "".to_string(), + socket_path: String::new(), + pidfile_path: String::new(), systemd_socket: false, tcp_port: 8889, } @@ -562,7 +520,7 @@ impl Default for Logs { fn default() -> Self { Self { enabled: true, - dir: "".to_string(), + dir: String::new(), level: LogLevel::default(), retention: Self::default_retention(), search: LogConfig { @@ -621,18 +579,6 @@ impl Logs { pub(crate) fn daemon_retention(&self) -> u64 { self.daemon.retention.unwrap_or(self.retention) } - - /// Returns the full path for the search log file. - pub(crate) fn search_path(&self) -> PathBuf { - let path = PathBuf::from(&self.search.file); - PathBuf::from(&self.dir).join(path) - } - - /// Returns the full path for the daemon log file. - pub(crate) fn daemon_path(&self) -> PathBuf { - let path = PathBuf::from(&self.daemon.file); - PathBuf::from(&self.dir).join(path) - } } impl Default for Search { @@ -902,24 +848,6 @@ impl Sync { .map(decode_key) .transpose() } - - pub(crate) async fn should_sync(&self) -> Result<bool> { - if !self.auto || !self.have_sync_user()? { - return Ok(false); - } - - if self.frequency == "0" || self.frequency.is_empty() { - return Ok(true); - } - - match parse_duration(self.frequency.as_str()) { - Ok(d) => { - let d = time::Duration::try_from(d)?; - Ok(OffsetDateTime::now_utc() - Settings::last_sync().await? >= d) - } - Err(e) => Err(eyre!("failed to check sync: {}", e)), - } - } } #[derive(Clone, Debug, Deserialize, Serialize)] @@ -998,9 +926,6 @@ pub(crate) struct Settings { pub(crate) search: Search, #[serde(default)] - pub(crate) theme: Theme, - - #[serde(default)] pub(crate) ui: Ui, #[serde(default)] @@ -1126,7 +1051,6 @@ impl Settings { .set_default("command_chaining", false)? .set_default("store_failed", true)? .set_default("daemon.sync_frequency", 300)? - .set_default("daemon.enabled", false)? .set_default("daemon.autostart", false)? .set_default("daemon.socket_path", socket_path.to_str())? .set_default("daemon.pidfile_path", pidfile_path.to_str())? @@ -1553,15 +1477,6 @@ mod tests { } #[test] - fn effective_data_dir_returns_default_when_not_set() { - let effective = super::Settings::effective_data_dir(); - let default = crate::atuin_common::utils::data_dir(); - - assert!(effective.to_str().is_some()); - assert!(effective.ends_with("atuin") || effective == default); - } - - #[test] fn keymap_config_deserializes_simple_binding() { let json = r#"{"emacs": {"ctrl-c": "exit"}}"#; let config: super::KeymapConfig = serde_json::from_str(json).unwrap(); diff --git a/crates/turtle/src/atuin_client/settings/watcher.rs b/crates/turtle/src/atuin_client/settings/watcher.rs index 20082639..e280480c 100644 --- a/crates/turtle/src/atuin_client/settings/watcher.rs +++ b/crates/turtle/src/atuin_client/settings/watcher.rs @@ -22,7 +22,7 @@ //! ``` use std::{ - path::PathBuf, + path::{Path, PathBuf}, sync::{Arc, OnceLock}, time::Duration, }; @@ -74,9 +74,9 @@ impl SettingsWatcher { let (tx, rx) = watch::channel(initial_settings); let config_path = Self::config_path(); - info!("starting config file watcher: {:?}", config_path); + info!("starting config file watcher: {}", config_path.display()); - let watcher = Self::create_watcher(tx, config_path)?; + let watcher = Self::create_watcher(tx, &config_path)?; Ok(Self { rx, @@ -93,37 +93,29 @@ impl SettingsWatcher { self.rx.clone() } - /// Get the current settings without subscribing to updates. - pub(crate) fn current(&self) -> Arc<Settings> { - self.rx.borrow().clone() - } - /// Get the config file path. fn config_path() -> PathBuf { - let config_dir = if let Ok(p) = std::env::var("ATUIN_CONFIG_DIR") { - PathBuf::from(p) - } else { - crate::atuin_common::utils::config_dir() - }; + let config_dir = std::env::var("ATUIN_CONFIG_DIR") + .map_or_else(|_| crate::atuin_common::utils::config_dir(), PathBuf::from); config_dir.join("config.toml") } /// Create the file watcher with debouncing. fn create_watcher( tx: watch::Sender<Arc<Settings>>, - config_path: PathBuf, + config_path: &Path, ) -> Result<RecommendedWatcher> { // Channel for debouncing file events let (debounce_tx, debounce_rx) = std::sync::mpsc::channel::<()>(); // Spawn debounce thread - let config_path_clone = config_path.clone(); + let config_path_clone = config_path.to_owned(); std::thread::spawn(move || { - Self::debounce_loop(debounce_rx, tx, config_path_clone); + Self::debounce_loop(&debounce_rx, &tx, &config_path_clone); }); // Clone config_path for use in the watcher callback - let config_path_for_watcher = config_path.clone(); + let config_path_for_watcher = config_path.to_owned(); // Canonicalize config path for reliable comparison on macOS // (handles symlinks like /var -> /private/var) @@ -169,13 +161,13 @@ impl SettingsWatcher { EventKind::Modify(ModifyKind::Data(_) | ModifyKind::Any) | EventKind::Create(_) ) { - debug!("config file event detected: {:?}", event); + debug!("config file event detected: {event:?}"); // Send to debounce channel (ignore send errors - receiver might be gone) let _ = debounce_tx.send(()); } } Err(e) => { - error!("file watcher error: {}", e); + error!("file watcher error: {e}"); } } }, @@ -184,31 +176,40 @@ impl SettingsWatcher { .wrap_err("failed to create file watcher")?; // Watch the config file's parent directory (some editors create new files) - let watch_path = config_path.parent().unwrap_or(&config_path); + let watch_path = config_path.parent().unwrap_or(config_path); // Defensive: ensure watch path exists before trying to watch if !watch_path.exists() { warn!( - "config directory does not exist, creating it: {:?}", - watch_path + "config directory does not exist, creating it: {}", + watch_path.display() ); - std::fs::create_dir_all(watch_path) - .wrap_err_with(|| format!("failed to create config directory: {:?}", watch_path))?; + std::fs::create_dir_all(watch_path).wrap_err_with(|| { + format!( + "failed to create config directory: {}", + watch_path.display() + ) + })?; } watcher .watch(watch_path, RecursiveMode::NonRecursive) - .wrap_err_with(|| format!("failed to watch config directory: {:?}", watch_path))?; + .wrap_err_with(|| { + format!("failed to watch config directory: {}", watch_path.display()) + })?; - info!("config file watcher initialized for: {:?}", watch_path); + info!( + "config file watcher initialized for: {}", + watch_path.display() + ); Ok(watcher) } /// Debounce loop that batches file events and reloads settings. fn debounce_loop( - rx: std::sync::mpsc::Receiver<()>, - tx: watch::Sender<Arc<Settings>>, - config_path: PathBuf, + rx: &std::sync::mpsc::Receiver<()>, + tx: &watch::Sender<Arc<Settings>>, + config_path: &Path, ) { const DEBOUNCE_DURATION: Duration = Duration::from_millis(500); @@ -229,14 +230,17 @@ impl SettingsWatcher { // (handles case where file was deleted - we'll get notified when it's recreated) if !config_path.exists() { debug!( - "config file does not exist, skipping reload: {:?}", - config_path + "config file does not exist, skipping reload: {}", + config_path.display() ); continue; } // Now reload settings - info!("config file changed, reloading settings: {:?}", config_path); + info!( + "config file changed, reloading settings: {}", + config_path.display() + ); match Settings::new() { Ok(settings) => { if tx.send(Arc::new(settings)).is_err() { @@ -247,7 +251,7 @@ impl SettingsWatcher { info!("settings reloaded successfully"); } Err(e) => { - warn!("failed to reload settings: {}", e); + warn!("failed to reload settings: {e}"); // Keep the old settings, don't broadcast the error } } diff --git a/crates/turtle/src/atuin_client/theme.rs b/crates/turtle/src/atuin_client/theme.rs index 21bbe07c..ec0538e9 100644 --- a/crates/turtle/src/atuin_client/theme.rs +++ b/crates/turtle/src/atuin_client/theme.rs @@ -1,831 +1,41 @@ -use config::{Config, File as ConfigFile, FileFormat}; -use log; -use palette::named; -use serde::{Deserialize, Serialize}; -use serde_json; -use std::collections::HashMap; -use std::error; -use std::io::{Error, ErrorKind}; -use std::path::PathBuf; -use std::sync::LazyLock; -use strum_macros; - -static DEFAULT_MAX_DEPTH: u8 = 10; - -// Collection of settable "meanings" that can have colors set. -// NOTE: You can add a new meaning here without breaking backwards compatibility but please: -// - update the atuin/docs repository, which has a list of available meanings -// - add a fallback in the MEANING_FALLBACKS below, so that themes which do not have it -// get a sensible fallback (see Title as an example) -#[derive( - Serialize, Deserialize, Copy, Clone, Hash, Debug, Eq, PartialEq, strum_macros::Display, -)] -#[strum(serialize_all = "camel_case")] -pub(crate) enum Meaning { - AlertInfo, - AlertWarn, - AlertError, - Annotation, - Base, - Guidance, - Important, - Title, - Muted, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub(crate) struct ThemeConfig { - // Definition of the theme - pub(crate) theme: ThemeDefinitionConfigBlock, - - // Colors - pub(crate) colors: HashMap<Meaning, String>, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub(crate) struct ThemeDefinitionConfigBlock { - /// Name of theme ("default" for base) - pub(crate) name: String, - - /// Whether any theme should be treated as a parent _if available_ - pub(crate) parent: Option<String>, -} - use crossterm::style::{Attribute, Attributes, Color, ContentStyle}; - -// For now, a theme is loaded as a mapping of meanings to colors, but it may be desirable to -// expand that in the future to general styles, so we populate a Meaning->ContentStyle hashmap. -pub(crate) struct Theme { - pub(crate) name: String, - pub(crate) parent: Option<String>, - pub(crate) styles: HashMap<Meaning, ContentStyle>, +pub(crate) fn style_base() -> ContentStyle { + ContentStyle::default() } - -// Themes have a number of convenience functions for the most commonly used meanings. -// The general purpose `as_style` routine gives back a style, but for ease-of-use and to keep -// theme-related boilerplate minimal, the convenience functions give a color. -impl Theme { - // This is the base "default" color, for general text - pub(crate) fn get_base(&self) -> ContentStyle { - self.styles[&Meaning::Base] - } - - pub(crate) fn get_info(&self) -> ContentStyle { - self.get_alert(log::Level::Info) - } - - pub(crate) fn get_warning(&self) -> ContentStyle { - self.get_alert(log::Level::Warn) - } - - pub(crate) fn get_error(&self) -> ContentStyle { - self.get_alert(log::Level::Error) - } - - // The alert meanings may be chosen by the Level enum, rather than the methods above - // or the full Meaning enum, to simplify programmatic selection of a log-level. - pub(crate) fn get_alert(&self, severity: log::Level) -> ContentStyle { - self.styles[ALERT_TYPES.get(&severity).unwrap()] - } - - pub(crate) fn new( - name: String, - parent: Option<String>, - styles: HashMap<Meaning, ContentStyle>, - ) -> Theme { - Theme { - name, - parent, - styles, - } - } - - pub(crate) fn closest_meaning<'a>(&self, meaning: &'a Meaning) -> &'a Meaning { - if self.styles.contains_key(meaning) { - meaning - } else if MEANING_FALLBACKS.contains_key(meaning) { - self.closest_meaning(&MEANING_FALLBACKS[meaning]) - } else { - &Meaning::Base - } - } - - // General access - if you have a meaning, this will give you a (crossterm) style - pub(crate) fn as_style(&self, meaning: Meaning) -> ContentStyle { - self.styles[self.closest_meaning(&meaning)] - } - - // Turns a map of meanings to colornames into a theme - // If theme-debug is on, then we will print any colornames that we cannot load, - // but we do not have this on in general, as it could print unfiltered text to the terminal - // from a theme TOML file. However, it will always return a theme, falling back to - // defaults on error, so that a TOML file does not break loading - pub(crate) fn from_foreground_colors( - name: String, - parent: Option<&Theme>, - foreground_colors: HashMap<Meaning, String>, - debug: bool, - ) -> Theme { - let styles: HashMap<Meaning, ContentStyle> = foreground_colors - .iter() - .map(|(name, color)| { - ( - *name, - StyleFactory::from_fg_string(color).unwrap_or_else(|err| { - if debug { - log::warn!("Tried to load string as a color unsuccessfully: ({name}={color}) {err}"); - } - ContentStyle::default() - }), - ) - }) - .collect(); - Theme::from_map(name, parent, &styles) - } - - // Boil down a meaning-color hashmap into a theme, by taking the defaults - // for any unknown colors - fn from_map( - name: String, - parent: Option<&Theme>, - overrides: &HashMap<Meaning, ContentStyle>, - ) -> Theme { - let styles = match parent { - Some(theme) => Box::new(theme.styles.clone()), - None => Box::new(DEFAULT_THEME.styles.clone()), - } - .iter() - .map(|(name, color)| match overrides.get(name) { - Some(value) => (*name, *value), - None => (*name, *color), - }) - .collect(); - Theme::new(name, parent.map(|p| p.name.clone()), styles) +pub(crate) fn style_annotation() -> ContentStyle { + ContentStyle { + foreground_color: Some(Color::DarkGrey), + ..ContentStyle::default() } } - -// Use palette to get a color from a string name, if possible -fn from_string(name: &str) -> Result<Color, String> { - if name.is_empty() { - return Err("Empty string".into()); - } - let first_char = name.chars().next().unwrap(); - match first_char { - '#' => { - let hexcode = &name[1..]; - let vec: Vec<u8> = hexcode - .chars() - .collect::<Vec<char>>() - .chunks(2) - .map(|pair| u8::from_str_radix(pair.iter().collect::<String>().as_str(), 16)) - .filter_map(|n| n.ok()) - .collect(); - if vec.len() != 3 { - return Err("Could not parse 3 hex values from string".into()); - } - Ok(Color::Rgb { - r: vec[0], - g: vec[1], - b: vec[2], - }) - } - '@' => { - // For full flexibility, we need to use serde_json, given - // crossterm's approach. - serde_json::from_str::<Color>(format!("\"{}\"", &name[1..]).as_str()) - .map_err(|_| format!("Could not convert color name {name} to Crossterm color")) - } - _ => { - let srgb = named::from_str(name).ok_or("No such color in palette")?; - Ok(Color::Rgb { - r: srgb.red, - g: srgb.green, - b: srgb.blue, - }) - } +pub(crate) fn style_important() -> ContentStyle { + ContentStyle { + foreground_color: Some(Color::White), + attributes: Attributes::from(Attribute::Bold), + ..ContentStyle::default() } } - -pub(crate) struct StyleFactory {} - -impl StyleFactory { - fn from_fg_string(name: &str) -> Result<ContentStyle, String> { - match from_string(name) { - Ok(color) => Ok(Self::from_fg_color(color)), - Err(err) => Err(err), - } - } - - // For succinctness, if we are confident that the name will be known, - // this routine is available to keep the code readable - fn known_fg_string(name: &str) -> ContentStyle { - Self::from_fg_string(name).unwrap() - } - - fn from_fg_color(color: Color) -> ContentStyle { - ContentStyle { - foreground_color: Some(color), - ..ContentStyle::default() - } - } - - fn from_fg_color_and_attributes(color: Color, attributes: Attributes) -> ContentStyle { - ContentStyle { - foreground_color: Some(color), - attributes, - ..ContentStyle::default() - } +pub(crate) fn style_guidance() -> ContentStyle { + ContentStyle { + foreground_color: Some(Color::DarkBlue), + ..ContentStyle::default() } } - -// Built-in themes. Rather than having extra files added before any theming -// is available, this gives a couple of basic options, demonstrating the use -// of themes: autumn and marine -static ALERT_TYPES: LazyLock<HashMap<log::Level, Meaning>> = LazyLock::new(|| { - HashMap::from([ - (log::Level::Info, Meaning::AlertInfo), - (log::Level::Warn, Meaning::AlertWarn), - (log::Level::Error, Meaning::AlertError), - ]) -}); - -static MEANING_FALLBACKS: LazyLock<HashMap<Meaning, Meaning>> = LazyLock::new(|| { - HashMap::from([ - (Meaning::Guidance, Meaning::AlertInfo), - (Meaning::Annotation, Meaning::AlertInfo), - (Meaning::Title, Meaning::Important), - ]) -}); - -static DEFAULT_THEME: LazyLock<Theme> = LazyLock::new(|| { - Theme::new( - "default".to_string(), - None, - HashMap::from([ - ( - Meaning::AlertError, - StyleFactory::from_fg_color(Color::DarkRed), - ), - ( - Meaning::AlertWarn, - StyleFactory::from_fg_color(Color::DarkYellow), - ), - ( - Meaning::AlertInfo, - StyleFactory::from_fg_color(Color::DarkGreen), - ), - ( - Meaning::Annotation, - StyleFactory::from_fg_color(Color::DarkGrey), - ), - ( - Meaning::Guidance, - StyleFactory::from_fg_color(Color::DarkBlue), - ), - ( - Meaning::Important, - StyleFactory::from_fg_color_and_attributes( - Color::White, - Attributes::from(Attribute::Bold), - ), - ), - (Meaning::Muted, StyleFactory::from_fg_color(Color::Grey)), - (Meaning::Base, ContentStyle::default()), - ]), - ) -}); - -static BUILTIN_THEMES: LazyLock<HashMap<&'static str, Theme>> = LazyLock::new(|| { - HashMap::from([ - ("default", HashMap::new()), - ( - "(none)", - HashMap::from([ - (Meaning::AlertError, ContentStyle::default()), - (Meaning::AlertWarn, ContentStyle::default()), - (Meaning::AlertInfo, ContentStyle::default()), - (Meaning::Annotation, ContentStyle::default()), - (Meaning::Guidance, ContentStyle::default()), - (Meaning::Important, ContentStyle::default()), - (Meaning::Muted, ContentStyle::default()), - (Meaning::Base, ContentStyle::default()), - ]), - ), - ( - "autumn", - HashMap::from([ - ( - Meaning::AlertError, - StyleFactory::known_fg_string("saddlebrown"), - ), - ( - Meaning::AlertWarn, - StyleFactory::known_fg_string("darkorange"), - ), - (Meaning::AlertInfo, StyleFactory::known_fg_string("gold")), - ( - Meaning::Annotation, - StyleFactory::from_fg_color(Color::DarkGrey), - ), - (Meaning::Guidance, StyleFactory::known_fg_string("brown")), - ]), - ), - ( - "marine", - HashMap::from([ - ( - Meaning::AlertError, - StyleFactory::known_fg_string("yellowgreen"), - ), - (Meaning::AlertWarn, StyleFactory::known_fg_string("cyan")), - ( - Meaning::AlertInfo, - StyleFactory::known_fg_string("turquoise"), - ), - ( - Meaning::Annotation, - StyleFactory::known_fg_string("steelblue"), - ), - ( - Meaning::Base, - StyleFactory::known_fg_string("lightsteelblue"), - ), - (Meaning::Guidance, StyleFactory::known_fg_string("teal")), - ]), - ), - ]) - .iter() - .map(|(name, theme)| (*name, Theme::from_map(name.to_string(), None, theme))) - .collect() -}); - -// To avoid themes being repeatedly loaded, we store them in a theme manager -pub(crate) struct ThemeManager { - loaded_themes: HashMap<String, Theme>, - debug: bool, - override_theme_dir: Option<String>, -} - -// Theme-loading logic -impl ThemeManager { - pub(crate) fn new(debug: Option<bool>, theme_dir: Option<String>) -> Self { - Self { - loaded_themes: HashMap::new(), - debug: debug.unwrap_or(false), - override_theme_dir: match theme_dir { - Some(theme_dir) => Some(theme_dir), - None => std::env::var("ATUIN_THEME_DIR").ok(), - }, - } - } - - // Try to load a theme from a `{name}.toml` file in the theme directory. If an override is set - // for the theme dir (via ATUIN_THEME_DIR env) we should load the theme from there - pub(crate) fn load_theme_from_file( - &mut self, - name: &str, - max_depth: u8, - ) -> Result<&Theme, Box<dyn error::Error>> { - let mut theme_file = if let Some(p) = &self.override_theme_dir { - if p.is_empty() { - return Err(Box::new(Error::new( - ErrorKind::NotFound, - "Empty theme directory override and could not find theme elsewhere", - ))); - } - PathBuf::from(p) - } else { - let config_dir = crate::atuin_common::utils::config_dir(); - let mut theme_file = if let Ok(p) = std::env::var("ATUIN_CONFIG_DIR") { - PathBuf::from(p) - } else { - let mut theme_file = PathBuf::new(); - theme_file.push(config_dir); - theme_file - }; - theme_file.push("themes"); - theme_file - }; - - let theme_toml = format!("{name}.toml"); - theme_file.push(theme_toml); - - let mut config_builder = Config::builder(); - - config_builder = config_builder.add_source(ConfigFile::new( - theme_file.to_str().unwrap(), - FileFormat::Toml, - )); - - let config = config_builder.build()?; - self.load_theme_from_config(name, config, max_depth) - } - - pub(crate) fn load_theme_from_config( - &mut self, - name: &str, - config: Config, - max_depth: u8, - ) -> Result<&Theme, Box<dyn error::Error>> { - let debug = self.debug; - let theme_config: ThemeConfig = match config.try_deserialize() { - Ok(tc) => tc, - Err(e) => { - return Err(Box::new(Error::new( - ErrorKind::InvalidInput, - format!( - "Failed to deserialize theme: {}", - if debug { - e.to_string() - } else { - "set theme debug on for more info".to_string() - } - ), - ))); - } - }; - let colors: HashMap<Meaning, String> = theme_config.colors; - let parent: Option<&Theme> = match theme_config.theme.parent { - Some(parent_name) => { - if max_depth == 0 { - return Err(Box::new(Error::new( - ErrorKind::InvalidInput, - "Parent requested but we hit the recursion limit", - ))); - } - Some(self.load_theme(parent_name.as_str(), Some(max_depth - 1))) - } - None => Some(self.load_theme("default", Some(max_depth - 1))), - }; - - if debug && name != theme_config.theme.name { - log::warn!( - "Your theme config name is not the name of your loaded theme {} != {}", - name, - theme_config.theme.name - ); - } - - let theme = Theme::from_foreground_colors(theme_config.theme.name, parent, colors, debug); - let name = name.to_string(); - self.loaded_themes.insert(name.clone(), theme); - let theme = self.loaded_themes.get(&name).unwrap(); - Ok(theme) - } - - // Check if the requested theme is loaded and, if not, then attempt to get it - // from the builtins or, if not there, from file - pub(crate) fn load_theme(&mut self, name: &str, max_depth: Option<u8>) -> &Theme { - if self.loaded_themes.contains_key(name) { - return self.loaded_themes.get(name).unwrap(); - } - let built_ins = &BUILTIN_THEMES; - match built_ins.get(name) { - Some(theme) => theme, - None => match self.load_theme_from_file(name, max_depth.unwrap_or(DEFAULT_MAX_DEPTH)) { - Ok(theme) => theme, - Err(err) => { - log::warn!("Could not load theme {name}: {err}"); - built_ins.get("(none)").unwrap() - } - }, - } +pub(crate) fn style_alerterror() -> ContentStyle { + ContentStyle { + foreground_color: Some(Color::DarkRed), + ..ContentStyle::default() } } - -#[cfg(test)] -mod theme_tests { - use super::*; - - #[test] - fn test_can_load_builtin_theme() { - let mut manager = ThemeManager::new(Some(false), Some("".to_string())); - let theme = manager.load_theme("autumn", None); - assert_eq!( - theme.as_style(Meaning::Guidance).foreground_color, - from_string("brown").ok() - ); - } - - #[test] - fn test_can_create_theme() { - let mut manager = ThemeManager::new(Some(false), Some("".to_string())); - let mytheme = Theme::new( - "mytheme".to_string(), - None, - HashMap::from([( - Meaning::AlertError, - StyleFactory::known_fg_string("yellowgreen"), - )]), - ); - manager.loaded_themes.insert("mytheme".to_string(), mytheme); - let theme = manager.load_theme("mytheme", None); - assert_eq!( - theme.as_style(Meaning::AlertError).foreground_color, - from_string("yellowgreen").ok() - ); +pub(crate) fn style_alertinfo() -> ContentStyle { + ContentStyle { + foreground_color: Some(Color::DarkGreen), + ..ContentStyle::default() } - - #[test] - fn test_can_fallback_when_meaning_missing() { - let mut manager = ThemeManager::new(Some(false), Some("".to_string())); - - // We use title as an example of a meaning that is not defined - // even in the base theme. - assert!(!DEFAULT_THEME.styles.contains_key(&Meaning::Title)); - - let config = Config::builder() - .add_source(ConfigFile::from_str( - " - [theme] - name = \"title_theme\" - - [colors] - Guidance = \"white\" - AlertInfo = \"zomp\" - ", - FileFormat::Toml, - )) - .build() - .unwrap(); - let theme = manager - .load_theme_from_config("config_theme", config, 1) - .unwrap(); - - // Correctly picks overridden color. - assert_eq!( - theme.as_style(Meaning::Guidance).foreground_color, - from_string("white").ok() - ); - - // Does not fall back to any color. - assert_eq!(theme.as_style(Meaning::AlertInfo).foreground_color, None); - - // Even for the base. - assert_eq!(theme.as_style(Meaning::Base).foreground_color, None); - - // Falls back to red as meaning missing from theme, so picks base default. - assert_eq!( - theme.as_style(Meaning::AlertError).foreground_color, - Some(Color::DarkRed) - ); - - // Falls back to Important as Title not available. - assert_eq!( - theme.as_style(Meaning::Title).foreground_color, - theme.as_style(Meaning::Important).foreground_color, - ); - - let title_config = Config::builder() - .add_source(ConfigFile::from_str( - " - [theme] - name = \"title_theme\" - - [colors] - Title = \"white\" - AlertInfo = \"zomp\" - ", - FileFormat::Toml, - )) - .build() - .unwrap(); - let title_theme = manager - .load_theme_from_config("title_theme", title_config, 1) - .unwrap(); - - assert_eq!( - title_theme.as_style(Meaning::Title).foreground_color, - Some(Color::White) - ); - } - - #[test] - fn test_no_fallbacks_are_circular() { - let mytheme = Theme::new("mytheme".to_string(), None, HashMap::from([])); - MEANING_FALLBACKS - .iter() - .for_each(|pair| assert_eq!(mytheme.closest_meaning(pair.0), &Meaning::Base)) - } - - #[test] - fn test_can_get_colors_via_convenience_functions() { - let mut manager = ThemeManager::new(Some(true), Some("".to_string())); - let theme = manager.load_theme("default", None); - assert_eq!(theme.get_error().foreground_color.unwrap(), Color::DarkRed); - assert_eq!( - theme.get_warning().foreground_color.unwrap(), - Color::DarkYellow - ); - assert_eq!(theme.get_info().foreground_color.unwrap(), Color::DarkGreen); - assert_eq!(theme.get_base().foreground_color, None); - assert_eq!( - theme.get_alert(log::Level::Error).foreground_color.unwrap(), - Color::DarkRed - ) - } - - #[test] - fn test_can_use_parent_theme_for_fallbacks() { - testing_logger::setup(); - - let mut manager = ThemeManager::new(Some(false), Some("".to_string())); - - // First, we introduce a base theme - let solarized = Config::builder() - .add_source(ConfigFile::from_str( - " - [theme] - name = \"solarized\" - - [colors] - Guidance = \"white\" - AlertInfo = \"pink\" - ", - FileFormat::Toml, - )) - .build() - .unwrap(); - let solarized_theme = manager - .load_theme_from_config("solarized", solarized, 1) - .unwrap(); - - assert_eq!( - solarized_theme - .as_style(Meaning::AlertInfo) - .foreground_color, - from_string("pink").ok() - ); - - // Then we introduce a derived theme - let unsolarized = Config::builder() - .add_source(ConfigFile::from_str( - " - [theme] - name = \"unsolarized\" - parent = \"solarized\" - - [colors] - AlertInfo = \"red\" - ", - FileFormat::Toml, - )) - .build() - .unwrap(); - let unsolarized_theme = manager - .load_theme_from_config("unsolarized", unsolarized, 1) - .unwrap(); - - // It will take its own values - assert_eq!( - unsolarized_theme - .as_style(Meaning::AlertInfo) - .foreground_color, - from_string("red").ok() - ); - - // ...or fall back to the parent - assert_eq!( - unsolarized_theme - .as_style(Meaning::Guidance) - .foreground_color, - from_string("white").ok() - ); - - testing_logger::validate(|captured_logs| assert_eq!(captured_logs.len(), 0)); - - // If the parent is not found, we end up with the no theme colors or styling - // as this is considered a (soft) error state. - let nunsolarized = Config::builder() - .add_source(ConfigFile::from_str( - " - [theme] - name = \"nunsolarized\" - parent = \"nonsolarized\" - - [colors] - AlertInfo = \"red\" - ", - FileFormat::Toml, - )) - .build() - .unwrap(); - let nunsolarized_theme = manager - .load_theme_from_config("nunsolarized", nunsolarized, 1) - .unwrap(); - - assert_eq!( - nunsolarized_theme - .as_style(Meaning::Guidance) - .foreground_color, - None - ); - - testing_logger::validate(|captured_logs| { - assert_eq!(captured_logs.len(), 1); - assert_eq!( - captured_logs[0].body, - "Could not load theme nonsolarized: Empty theme directory override and could not find theme elsewhere" - ); - assert_eq!(captured_logs[0].level, log::Level::Warn) - }); - } - - #[test] - fn test_can_debug_theme() { - testing_logger::setup(); - [true, false].iter().for_each(|debug| { - let mut manager = ThemeManager::new(Some(*debug), Some("".to_string())); - let config = Config::builder() - .add_source(ConfigFile::from_str( - " - [theme] - name = \"mytheme\" - - [colors] - Guidance = \"white\" - AlertInfo = \"xinetic\" - ", - FileFormat::Toml, - )) - .build() - .unwrap(); - manager - .load_theme_from_config("config_theme", config, 1) - .unwrap(); - testing_logger::validate(|captured_logs| { - if *debug { - assert_eq!(captured_logs.len(), 2); - assert_eq!( - captured_logs[0].body, - "Your theme config name is not the name of your loaded theme config_theme != mytheme" - ); - assert_eq!(captured_logs[0].level, log::Level::Warn); - assert_eq!( - captured_logs[1].body, - "Tried to load string as a color unsuccessfully: (AlertInfo=xinetic) No such color in palette" - ); - assert_eq!(captured_logs[1].level, log::Level::Warn) - } else { - assert_eq!(captured_logs.len(), 0) - } - }) - }) - } - - #[test] - fn test_can_parse_color_strings_correctly() { - assert_eq!( - from_string("brown").unwrap(), - Color::Rgb { - r: 165, - g: 42, - b: 42 - } - ); - - assert_eq!(from_string(""), Err("Empty string".into())); - - ["manatee", "caput mortuum", "123456"] - .iter() - .for_each(|inp| { - assert_eq!(from_string(inp), Err("No such color in palette".into())); - }); - - assert_eq!( - from_string("#ff1122").unwrap(), - Color::Rgb { - r: 255, - g: 17, - b: 34 - } - ); - ["#1122", "#ffaa112", "#brown"].iter().for_each(|inp| { - assert_eq!( - from_string(inp), - Err("Could not parse 3 hex values from string".into()) - ); - }); - - assert_eq!(from_string("@dark_grey").unwrap(), Color::DarkGrey); - assert_eq!( - from_string("@rgb_(255,255,255)").unwrap(), - Color::Rgb { - r: 255, - g: 255, - b: 255 - } - ); - assert_eq!(from_string("@ansi_(255)").unwrap(), Color::AnsiValue(255)); - ["@", "@DarkGray", "@Dark 4ay", "@ansi(256)"] - .iter() - .for_each(|inp| { - assert_eq!( - from_string(inp), - Err(format!( - "Could not convert color name {inp} to Crossterm color" - )) - ); - }); +} +pub(crate) fn style_alertwarn() -> ContentStyle { + ContentStyle { + foreground_color: Some(Color::DarkYellow), + ..ContentStyle::default() } } diff --git a/crates/turtle/src/atuin_client/utils.rs b/crates/turtle/src/atuin_client/utils.rs index 35d7db26..6d178b77 100644 --- a/crates/turtle/src/atuin_client/utils.rs +++ b/crates/turtle/src/atuin_client/utils.rs @@ -1,3 +1,4 @@ + pub(crate) fn get_hostname() -> String { std::env::var("ATUIN_HOST_NAME") .unwrap_or_else(|_| whoami::hostname().unwrap_or_else(|_| "unknown-host".to_string())) |
