Run cargo fmt on all Rust source files

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
skepsismusic
2026-02-06 00:22:14 +01:00
parent dc6f027d6b
commit 10d7cfa739
18 changed files with 273 additions and 200 deletions

View File

@@ -31,10 +31,14 @@ pub fn init_data_dir() {
}
tracing::info!("Data directory: {}", path.display());
DATA_DIR.set(path).expect("Data directory already initialized");
DATA_DIR
.set(path)
.expect("Data directory already initialized");
}
/// Get the resolved data directory path.
pub fn data_dir() -> &'static Path {
DATA_DIR.get().expect("Data directory not initialized. Call config::init_data_dir() first.")
DATA_DIR
.get()
.expect("Data directory not initialized. Call config::init_data_dir() first.")
}

View File

@@ -121,7 +121,11 @@ async fn main() {
// Small delay to ensure server is ready
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
if let Err(e) = webbrowser::open(&url) {
tracing::warn!("Failed to open browser: {}. Open http://localhost:{} manually.", e, port);
tracing::warn!(
"Failed to open browser: {}. Open http://localhost:{} manually.",
e,
port
);
}
});
}

View File

@@ -79,7 +79,10 @@ async fn upload_asset(
if !is_allowed_content_type(&content_type) {
return (
StatusCode::BAD_REQUEST,
format!("Unsupported file type: {}. Only images are allowed.", content_type),
format!(
"Unsupported file type: {}. Only images are allowed.",
content_type
),
)
.into_response();
}
@@ -100,7 +103,10 @@ async fn upload_asset(
if data.len() > MAX_FILE_SIZE {
return (
StatusCode::BAD_REQUEST,
format!("File too large. Maximum size is {} MB.", MAX_FILE_SIZE / 1024 / 1024),
format!(
"File too large. Maximum size is {} MB.",
MAX_FILE_SIZE / 1024 / 1024
),
)
.into_response();
}
@@ -149,7 +155,11 @@ async fn upload_asset(
/// Validate that a path component doesn't contain directory traversal
fn validate_path_component(component: &str) -> Result<(), String> {
if component.contains("..") || component.contains('/') || component.contains('\\') || component.is_empty() {
if component.contains("..")
|| component.contains('/')
|| component.contains('\\')
|| component.is_empty()
{
return Err("Invalid path component".to_string());
}
Ok(())
@@ -199,12 +209,7 @@ async fn get_asset(Path((project, filename)): Path<(String, String)>) -> impl In
let stream = ReaderStream::new(file);
let body = Body::from_stream(stream);
(
StatusCode::OK,
[(header::CONTENT_TYPE, content_type)],
body,
)
.into_response()
(StatusCode::OK, [(header::CONTENT_TYPE, content_type)], body).into_response()
}
fn is_allowed_content_type(content_type: &str) -> bool {
@@ -220,11 +225,7 @@ fn is_allowed_content_type(content_type: &str) -> bool {
}
fn get_content_type(filename: &str) -> &'static str {
let ext = filename
.rsplit('.')
.next()
.unwrap_or("")
.to_lowercase();
let ext = filename.rsplit('.').next().unwrap_or("").to_lowercase();
match ext.as_str() {
"jpg" | "jpeg" => "image/jpeg",
@@ -248,7 +249,13 @@ fn generate_unique_filename(dir: &StdPath, original: &str) -> String {
// Sanitize filename
let sanitized_name: String = name
.chars()
.map(|c| if c.is_alphanumeric() || c == '-' || c == '_' { c } else { '_' })
.map(|c| {
if c.is_alphanumeric() || c == '-' || c == '_' {
c
} else {
'_'
}
})
.collect();
let base_filename = format!("{}{}", sanitized_name, ext);

View File

@@ -1,17 +1,13 @@
use axum::{
body::Bytes,
extract::Path,
http::StatusCode,
response::IntoResponse,
routing::get,
Json, Router,
body::Bytes, extract::Path, http::StatusCode, response::IntoResponse, routing::get, Json,
Router,
};
use chrono::{NaiveDate, Utc};
use serde::{Deserialize, Serialize};
use std::fs;
use crate::services::filesystem;
use crate::config;
use crate::services::filesystem;
use crate::services::frontmatter;
#[derive(Debug, Serialize)]
@@ -35,7 +31,12 @@ pub fn router() -> Router {
Router::new()
.route("/", get(list_daily_notes))
.route("/today", get(get_or_create_today))
.route("/{date}", get(get_daily_note).post(create_daily_note).put(update_daily_note))
.route(
"/{date}",
get(get_daily_note)
.post(create_daily_note)
.put(update_daily_note),
)
}
/// List all daily notes
@@ -123,14 +124,16 @@ async fn get_or_create_today() -> impl IntoResponse {
async fn get_daily_note(Path(date): Path<String>) -> impl IntoResponse {
// Validate date format
if NaiveDate::parse_from_str(&date, "%Y-%m-%d").is_err() {
return (StatusCode::BAD_REQUEST, "Invalid date format. Use YYYY-MM-DD").into_response();
return (
StatusCode::BAD_REQUEST,
"Invalid date format. Use YYYY-MM-DD",
)
.into_response();
}
match get_daily_note_impl(&date) {
Ok(note) => Json(note).into_response(),
Err(err) if err.contains("not found") => {
(StatusCode::NOT_FOUND, err).into_response()
}
Err(err) if err.contains("not found") => (StatusCode::NOT_FOUND, err).into_response(),
Err(err) => (
StatusCode::INTERNAL_SERVER_ERROR,
format!("Failed to get daily note: {}", err),
@@ -171,16 +174,18 @@ async fn create_daily_note(
) -> impl IntoResponse {
// Validate date format
if NaiveDate::parse_from_str(&date, "%Y-%m-%d").is_err() {
return (StatusCode::BAD_REQUEST, "Invalid date format. Use YYYY-MM-DD").into_response();
return (
StatusCode::BAD_REQUEST,
"Invalid date format. Use YYYY-MM-DD",
)
.into_response();
}
let content = body.and_then(|b| b.content.clone());
match create_daily_note_impl(&date, content.as_deref()) {
Ok(note) => (StatusCode::CREATED, Json(note)).into_response(),
Err(err) if err.contains("already exists") => {
(StatusCode::CONFLICT, err).into_response()
}
Err(err) if err.contains("already exists") => (StatusCode::CONFLICT, err).into_response(),
Err(err) => (
StatusCode::INTERNAL_SERVER_ERROR,
format!("Failed to create daily note: {}", err),
@@ -206,8 +211,7 @@ fn create_daily_note_impl(date: &str, initial_content: Option<&str>) -> Result<D
let now = Utc::now().to_rfc3339();
// Parse date for display
let parsed_date = NaiveDate::parse_from_str(date, "%Y-%m-%d")
.map_err(|e| e.to_string())?;
let parsed_date = NaiveDate::parse_from_str(date, "%Y-%m-%d").map_err(|e| e.to_string())?;
let display_date = parsed_date.format("%A, %B %d, %Y").to_string();
// Create frontmatter
@@ -238,9 +242,7 @@ fn create_daily_note_impl(date: &str, initial_content: Option<&str>) -> Result<D
);
// Use provided content or default template
let body = initial_content
.map(|c| c.to_string())
.unwrap_or_else(|| {
let body = initial_content.map(|c| c.to_string()).unwrap_or_else(|| {
format!(
"# {}\n\n## Today's Focus\n\n- \n\n## Notes\n\n\n\n## Tasks\n\n- [ ] \n",
display_date
@@ -261,22 +263,21 @@ fn create_daily_note_impl(date: &str, initial_content: Option<&str>) -> Result<D
}
/// Update a daily note's content
async fn update_daily_note(
Path(date): Path<String>,
body: Bytes,
) -> impl IntoResponse {
async fn update_daily_note(Path(date): Path<String>, body: Bytes) -> impl IntoResponse {
// Validate date format
if NaiveDate::parse_from_str(&date, "%Y-%m-%d").is_err() {
return (StatusCode::BAD_REQUEST, "Invalid date format. Use YYYY-MM-DD").into_response();
return (
StatusCode::BAD_REQUEST,
"Invalid date format. Use YYYY-MM-DD",
)
.into_response();
}
let content = String::from_utf8_lossy(&body).to_string();
match update_daily_note_impl(&date, &content) {
Ok(note) => Json(note).into_response(),
Err(err) if err.contains("not found") => {
(StatusCode::NOT_FOUND, err).into_response()
}
Err(err) if err.contains("not found") => (StatusCode::NOT_FOUND, err).into_response(),
Err(err) => (
StatusCode::INTERNAL_SERVER_ERROR,
format!("Failed to update daily note: {}", err),

View File

@@ -1,17 +1,10 @@
use axum::{
extract::Path,
http::StatusCode,
response::IntoResponse,
routing::get,
Json, Router,
};
use axum::{extract::Path, http::StatusCode, response::IntoResponse, routing::get, Json, Router};
use crate::models::note::{Note, NoteSummary};
use crate::services::filesystem;
pub fn router() -> Router {
Router::new()
.route("/{id}", get(get_note).put(update_note).delete(delete_note))
Router::new().route("/{id}", get(get_note).put(update_note).delete(delete_note))
}
pub async fn list_notes() -> impl IntoResponse {
@@ -50,10 +43,7 @@ pub async fn create_note() -> impl IntoResponse {
}
}
async fn update_note(
Path(id): Path<String>,
body: String,
) -> impl IntoResponse {
async fn update_note(Path(id): Path<String>, body: String) -> impl IntoResponse {
match filesystem::update_note(&id, &body) {
Ok(note) => Json::<Note>(note).into_response(),
Err(err) if err.starts_with("Note not found") => {

View File

@@ -8,14 +8,13 @@ use axum::{
use serde::{Deserialize, Serialize};
use std::fs;
use crate::config;
use crate::routes::tasks::{
CreateTaskRequest, UpdateTaskMetaRequest,
list_project_tasks_handler, create_task_handler, get_task_handler,
update_task_content_handler, toggle_task_handler, update_task_meta_handler,
delete_task_handler,
create_task_handler, delete_task_handler, get_task_handler, list_project_tasks_handler,
toggle_task_handler, update_task_content_handler, update_task_meta_handler, CreateTaskRequest,
UpdateTaskMetaRequest,
};
use crate::services::filesystem;
use crate::config;
use crate::services::frontmatter;
#[derive(Debug, Serialize)]
@@ -75,15 +74,34 @@ pub fn router() -> Router {
Router::new()
.route("/", get(list_projects).post(create_project))
.route("/{id}", get(get_project))
.route("/{id}/content", get(get_project_content).put(update_project_content))
.route(
"/{id}/content",
get(get_project_content).put(update_project_content),
)
// Task routes (file-based)
.route("/{id}/tasks", get(get_project_tasks).post(create_project_task))
.route("/{id}/tasks/{task_id}", get(get_project_task).put(update_project_task).delete(delete_project_task))
.route(
"/{id}/tasks",
get(get_project_tasks).post(create_project_task),
)
.route(
"/{id}/tasks/{task_id}",
get(get_project_task)
.put(update_project_task)
.delete(delete_project_task),
)
.route("/{id}/tasks/{task_id}/toggle", put(toggle_project_task))
.route("/{id}/tasks/{task_id}/meta", put(update_project_task_meta))
// Note routes
.route("/{id}/notes", get(list_project_notes).post(create_project_note))
.route("/{id}/notes/{note_id}", get(get_project_note).put(update_project_note).delete(delete_project_note))
.route(
"/{id}/notes",
get(list_project_notes).post(create_project_note),
)
.route(
"/{id}/notes/{note_id}",
get(get_project_note)
.put(update_project_note)
.delete(delete_project_note),
)
}
// ============ Task Handlers ============
@@ -355,10 +373,7 @@ async fn get_project_content(Path(id): Path<String>) -> impl IntoResponse {
}
}
async fn update_project_content(
Path(id): Path<String>,
body: String,
) -> impl IntoResponse {
async fn update_project_content(Path(id): Path<String>, body: String) -> impl IntoResponse {
let index_path = config::data_dir()
.join("projects")
.join(&id)
@@ -618,7 +633,9 @@ async fn create_project_note(
.into_response()
}
async fn get_project_note(Path((project_id, note_id)): Path<(String, String)>) -> impl IntoResponse {
async fn get_project_note(
Path((project_id, note_id)): Path<(String, String)>,
) -> impl IntoResponse {
let notes_dir = config::data_dir()
.join("projects")
.join(&project_id)

View File

@@ -1,10 +1,4 @@
use axum::{
extract::Query,
http::StatusCode,
response::IntoResponse,
routing::get,
Json, Router,
};
use axum::{extract::Query, http::StatusCode, response::IntoResponse, routing::get, Json, Router};
use serde::Deserialize;
use crate::services::search;

View File

@@ -1,15 +1,10 @@
use axum::{
http::StatusCode,
response::IntoResponse,
routing::get,
Json, Router,
};
use axum::{http::StatusCode, response::IntoResponse, routing::get, Json, Router};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::Path as StdPath;
use crate::services::filesystem;
use crate::config;
use crate::services::filesystem;
use crate::services::frontmatter;
/// Task summary for list views
@@ -73,8 +68,7 @@ pub struct UpdateTaskMetaRequest {
}
pub fn router() -> Router {
Router::new()
.route("/", get(list_all_tasks_handler))
Router::new().route("/", get(list_all_tasks_handler))
}
// ============ Handler Functions (called from projects.rs) ============
@@ -96,7 +90,12 @@ pub async fn create_task_handler(
project_id: String,
payload: CreateTaskRequest,
) -> impl IntoResponse {
match create_task_impl(&project_id, &payload.title, payload.section.as_deref(), payload.parent_id.as_deref()) {
match create_task_impl(
&project_id,
&payload.title,
payload.section.as_deref(),
payload.parent_id.as_deref(),
) {
Ok(task) => (StatusCode::CREATED, Json(task)).into_response(),
Err(err) => (
StatusCode::INTERNAL_SERVER_ERROR,
@@ -110,9 +109,7 @@ pub async fn create_task_handler(
pub async fn get_task_handler(project_id: String, task_id: String) -> impl IntoResponse {
match get_task_impl(&project_id, &task_id) {
Ok(task) => Json(task).into_response(),
Err(err) if err.contains("not found") => {
(StatusCode::NOT_FOUND, err).into_response()
}
Err(err) if err.contains("not found") => (StatusCode::NOT_FOUND, err).into_response(),
Err(err) => (
StatusCode::INTERNAL_SERVER_ERROR,
format!("Failed to get task: {}", err),
@@ -129,9 +126,7 @@ pub async fn update_task_content_handler(
) -> impl IntoResponse {
match update_task_content_impl(&project_id, &task_id, &body) {
Ok(task) => Json(task).into_response(),
Err(err) if err.contains("not found") => {
(StatusCode::NOT_FOUND, err).into_response()
}
Err(err) if err.contains("not found") => (StatusCode::NOT_FOUND, err).into_response(),
Err(err) => (
StatusCode::INTERNAL_SERVER_ERROR,
format!("Failed to update task: {}", err),
@@ -144,9 +139,7 @@ pub async fn update_task_content_handler(
pub async fn toggle_task_handler(project_id: String, task_id: String) -> impl IntoResponse {
match toggle_task_impl(&project_id, &task_id) {
Ok(task) => Json(task).into_response(),
Err(err) if err.contains("not found") => {
(StatusCode::NOT_FOUND, err).into_response()
}
Err(err) if err.contains("not found") => (StatusCode::NOT_FOUND, err).into_response(),
Err(err) => (
StatusCode::INTERNAL_SERVER_ERROR,
format!("Failed to toggle task: {}", err),
@@ -163,9 +156,7 @@ pub async fn update_task_meta_handler(
) -> impl IntoResponse {
match update_task_meta_impl(&project_id, &task_id, payload) {
Ok(task) => Json(task).into_response(),
Err(err) if err.contains("not found") => {
(StatusCode::NOT_FOUND, err).into_response()
}
Err(err) if err.contains("not found") => (StatusCode::NOT_FOUND, err).into_response(),
Err(err) => (
StatusCode::INTERNAL_SERVER_ERROR,
format!("Failed to update task metadata: {}", err),
@@ -178,9 +169,7 @@ pub async fn update_task_meta_handler(
pub async fn delete_task_handler(project_id: String, task_id: String) -> impl IntoResponse {
match delete_task_impl(&project_id, &task_id) {
Ok(()) => StatusCode::NO_CONTENT.into_response(),
Err(err) if err.contains("not found") => {
(StatusCode::NOT_FOUND, err).into_response()
}
Err(err) if err.contains("not found") => (StatusCode::NOT_FOUND, err).into_response(),
Err(err) => (
StatusCode::INTERNAL_SERVER_ERROR,
format!("Failed to delete task: {}", err),
@@ -483,11 +472,7 @@ fn toggle_task_impl(project_id: &str, task_id: &str) -> Result<Task, String> {
);
// Update section based on completion status
let new_section = if new_completed {
"Completed"
} else {
"Active"
};
let new_section = if new_completed { "Completed" } else { "Active" };
fm.insert(
serde_yaml::Value::from("section"),
serde_yaml::Value::from(new_section),
@@ -554,14 +539,22 @@ fn toggle_task_impl(project_id: &str, task_id: &str) -> Result<Task, String> {
}
// Return updated task
let task = parse_task_file(&fs::read_to_string(&task_path).unwrap(), &task_path, project_id)
let task = parse_task_file(
&fs::read_to_string(&task_path).unwrap(),
&task_path,
project_id,
)
.ok_or_else(|| "Failed to parse updated task".to_string())?;
Ok(task)
}
fn calculate_next_due_date(current_due: Option<&str>, recurrence: &str, interval: i64) -> Option<String> {
use chrono::{NaiveDate, Duration, Utc, Months};
fn calculate_next_due_date(
current_due: Option<&str>,
recurrence: &str,
interval: i64,
) -> Option<String> {
use chrono::{Duration, Months, NaiveDate, Utc};
let base_date = if let Some(due_str) = current_due {
NaiveDate::parse_from_str(due_str, "%Y-%m-%d").unwrap_or_else(|_| Utc::now().date_naive())
@@ -600,28 +593,73 @@ fn create_recurring_task_impl(
let id = format!("{}-{}", project_id, filename);
let mut fm = serde_yaml::Mapping::new();
fm.insert(serde_yaml::Value::from("id"), serde_yaml::Value::from(id.clone()));
fm.insert(serde_yaml::Value::from("type"), serde_yaml::Value::from("task"));
fm.insert(serde_yaml::Value::from("title"), serde_yaml::Value::from(title));
fm.insert(serde_yaml::Value::from("completed"), serde_yaml::Value::from(false));
fm.insert(serde_yaml::Value::from("section"), serde_yaml::Value::from("Active"));
fm.insert(serde_yaml::Value::from("priority"), serde_yaml::Value::from("normal"));
fm.insert(serde_yaml::Value::from("is_active"), serde_yaml::Value::from(true));
fm.insert(serde_yaml::Value::from("project_id"), serde_yaml::Value::from(project_id));
fm.insert(serde_yaml::Value::from("recurrence"), serde_yaml::Value::from(recurrence));
fm.insert(serde_yaml::Value::from("recurrence_interval"), serde_yaml::Value::from(interval as u64));
fm.insert(
serde_yaml::Value::from("id"),
serde_yaml::Value::from(id.clone()),
);
fm.insert(
serde_yaml::Value::from("type"),
serde_yaml::Value::from("task"),
);
fm.insert(
serde_yaml::Value::from("title"),
serde_yaml::Value::from(title),
);
fm.insert(
serde_yaml::Value::from("completed"),
serde_yaml::Value::from(false),
);
fm.insert(
serde_yaml::Value::from("section"),
serde_yaml::Value::from("Active"),
);
fm.insert(
serde_yaml::Value::from("priority"),
serde_yaml::Value::from("normal"),
);
fm.insert(
serde_yaml::Value::from("is_active"),
serde_yaml::Value::from(true),
);
fm.insert(
serde_yaml::Value::from("project_id"),
serde_yaml::Value::from(project_id),
);
fm.insert(
serde_yaml::Value::from("recurrence"),
serde_yaml::Value::from(recurrence),
);
fm.insert(
serde_yaml::Value::from("recurrence_interval"),
serde_yaml::Value::from(interval as u64),
);
if let Some(due) = due_date {
fm.insert(serde_yaml::Value::from("due_date"), serde_yaml::Value::from(due));
fm.insert(
serde_yaml::Value::from("due_date"),
serde_yaml::Value::from(due),
);
}
if !tags.is_empty() {
let yaml_tags: Vec<serde_yaml::Value> = tags.iter().map(|t| serde_yaml::Value::from(t.as_str())).collect();
fm.insert(serde_yaml::Value::from("tags"), serde_yaml::Value::Sequence(yaml_tags));
let yaml_tags: Vec<serde_yaml::Value> = tags
.iter()
.map(|t| serde_yaml::Value::from(t.as_str()))
.collect();
fm.insert(
serde_yaml::Value::from("tags"),
serde_yaml::Value::Sequence(yaml_tags),
);
}
fm.insert(serde_yaml::Value::from("created"), serde_yaml::Value::from(now_str.clone()));
fm.insert(serde_yaml::Value::from("updated"), serde_yaml::Value::from(now_str.clone()));
fm.insert(
serde_yaml::Value::from("created"),
serde_yaml::Value::from(now_str.clone()),
);
fm.insert(
serde_yaml::Value::from("updated"),
serde_yaml::Value::from(now_str.clone()),
);
let body = format!("# {}\n\n", title);
let content = frontmatter::serialize_frontmatter(&fm, &body)?;
@@ -728,7 +766,11 @@ fn update_task_meta_impl(
filesystem::atomic_write(&task_path, new_content.as_bytes())?;
// Return updated task
let task = parse_task_file(&fs::read_to_string(&task_path).unwrap(), &task_path, project_id)
let task = parse_task_file(
&fs::read_to_string(&task_path).unwrap(),
&task_path,
project_id,
)
.ok_or_else(|| "Failed to parse updated task".to_string())?;
Ok(task)

View File

@@ -60,7 +60,9 @@ fn is_note_file(path: &Path) -> bool {
}
// data/projects/*/index.md
if path_str.contains("projects") && path.file_name().and_then(|s| s.to_str()) == Some("index.md") {
if path_str.contains("projects")
&& path.file_name().and_then(|s| s.to_str()) == Some("index.md")
{
return true;
}
@@ -123,7 +125,10 @@ pub fn normalize_path(path: &Path) -> String {
} else {
&path_str
};
stripped.replace('\\', "/").trim_start_matches('/').to_string()
stripped
.replace('\\', "/")
.trim_start_matches('/')
.to_string()
}
/// Read a full note by deterministic ID.
@@ -326,9 +331,7 @@ pub fn atomic_write(path: &Path, contents: &[u8]) -> Result<(), String> {
let parent = path.parent().ok_or("Invalid path")?;
let temp_name = format!(
".{}.tmp",
path.file_name()
.and_then(|s| s.to_str())
.unwrap_or("file")
path.file_name().and_then(|s| s.to_str()).unwrap_or("file")
);
let temp_path = parent.join(temp_name);

View File

@@ -165,8 +165,14 @@ mod tests {
let (fm, body, has_fm) = parse_frontmatter(content);
assert!(has_fm);
assert_eq!(fm.get(&Value::from("id")).unwrap().as_str().unwrap(), "test");
assert_eq!(fm.get(&Value::from("title")).unwrap().as_str().unwrap(), "Test Note");
assert_eq!(
fm.get(&Value::from("id")).unwrap().as_str().unwrap(),
"test"
);
assert_eq!(
fm.get(&Value::from("title")).unwrap().as_str().unwrap(),
"Test Note"
);
assert!(body.contains("Body content"));
}

View File

@@ -161,8 +161,7 @@ pub fn get_status() -> Result<RepoStatus, String> {
Some(CommitInfo {
id: commit.id().to_string()[..8].to_string(),
message: commit.message()?.trim().to_string(),
timestamp: chrono::DateTime::from_timestamp(commit.time().seconds(), 0)?
.to_rfc3339(),
timestamp: chrono::DateTime::from_timestamp(commit.time().seconds(), 0)?.to_rfc3339(),
})
});
@@ -311,7 +310,9 @@ pub fn push_to_remote() -> Result<(), String> {
.map_err(|e| format!("Remote 'origin' not found: {}", e))?;
// Check if remote URL is configured
let remote_url = remote.url().ok_or_else(|| "No remote URL configured".to_string())?;
let remote_url = remote
.url()
.ok_or_else(|| "No remote URL configured".to_string())?;
if remote_url.is_empty() {
return Err("No remote URL configured".to_string());
}
@@ -402,9 +403,7 @@ pub fn get_log(limit: Option<usize>) -> Result<Vec<CommitDetail>, String> {
let commit_tree = commit.tree().ok();
if let (Some(pt), Some(ct)) = (parent_tree, commit_tree) {
let diff = repo
.diff_tree_to_tree(Some(&pt), Some(&ct), None)
.ok();
let diff = repo.diff_tree_to_tree(Some(&pt), Some(&ct), None).ok();
diff.map(|d| d.deltas().count()).unwrap_or(0)
} else {
0
@@ -418,8 +417,7 @@ pub fn get_log(limit: Option<usize>) -> Result<Vec<CommitDetail>, String> {
.unwrap_or(0)
};
let timestamp =
chrono::DateTime::from_timestamp(commit.time().seconds(), 0)
let timestamp = chrono::DateTime::from_timestamp(commit.time().seconds(), 0)
.map(|dt| dt.to_rfc3339())
.unwrap_or_else(|| "Unknown".to_string());
@@ -449,10 +447,7 @@ pub fn get_working_diff() -> Result<DiffInfo, String> {
let repo = Repository::open(data_path).map_err(|e| format!("Not a git repository: {}", e))?;
// Get HEAD tree (or empty tree if no commits)
let head_tree = repo
.head()
.ok()
.and_then(|h| h.peel_to_tree().ok());
let head_tree = repo.head().ok().and_then(|h| h.peel_to_tree().ok());
// Diff against working directory
let diff = repo
@@ -609,10 +604,7 @@ pub fn get_remote_info() -> Result<Option<RemoteInfo>, String> {
let (ahead, behind) = if let Some(ref up) = upstream {
// Calculate ahead/behind
let local_oid = head.target().unwrap_or_else(git2::Oid::zero);
let upstream_oid = up
.get()
.target()
.unwrap_or_else(git2::Oid::zero);
let upstream_oid = up.get().target().unwrap_or_else(git2::Oid::zero);
repo.graph_ahead_behind(local_oid, upstream_oid)
.unwrap_or((0, 0))

View File

@@ -0,0 +1 @@

View File

@@ -33,7 +33,10 @@ pub fn search_notes(query: &str) -> Result<Vec<SearchResult>, String> {
match search_with_ripgrep(query) {
Ok(results) => return Ok(results),
Err(e) => {
tracing::debug!("ripgrep not available, falling back to manual search: {}", e);
tracing::debug!(
"ripgrep not available, falling back to manual search: {}",
e
);
}
}
@@ -48,8 +51,10 @@ fn search_with_ripgrep(query: &str) -> Result<Vec<SearchResult>, String> {
.args([
"--json", // JSON output for parsing
"--ignore-case", // Case insensitive
"--type", "md", // Only markdown files
"--max-count", "5", // Max 5 matches per file
"--type",
"md", // Only markdown files
"--max-count",
"5", // Max 5 matches per file
query,
&data_dir_str,
])
@@ -88,12 +93,12 @@ fn parse_ripgrep_output(output: &[u8]) -> Result<Vec<SearchResult>, String> {
let normalized_path = normalize_path(path_str);
let title = extract_title_from_path(&normalized_path);
let result = results_map.entry(normalized_path.clone()).or_insert_with(|| {
SearchResult {
let result = results_map
.entry(normalized_path.clone())
.or_insert_with(|| SearchResult {
path: normalized_path,
title,
matches: Vec::new(),
}
});
result.matches.push(SearchMatch {

View File

@@ -28,7 +28,10 @@ pub async fn start_watcher(ws_state: Arc<WsState>) -> Result<(), String> {
// Watch the data directory
let data_path = config::data_dir();
if !data_path.exists() {
return Err(format!("Data directory does not exist: {}", data_path.display()));
return Err(format!(
"Data directory does not exist: {}",
data_path.display()
));
}
// We need to keep the debouncer alive, so we'll store it
@@ -36,7 +39,8 @@ pub async fn start_watcher(ws_state: Arc<WsState>) -> Result<(), String> {
{
let mut d = debouncer.lock().await;
d.watcher().watch(data_path, RecursiveMode::Recursive)
d.watcher()
.watch(data_path, RecursiveMode::Recursive)
.map_err(|e| format!("Failed to watch directory: {}", e))?;
}
@@ -58,9 +62,9 @@ pub async fn start_watcher(ws_state: Arc<WsState>) -> Result<(), String> {
Ok(())
}
use std::collections::HashMap;
/// Track recent saves to avoid notifying about our own changes
use std::sync::Mutex;
use std::collections::HashMap;
use std::time::Instant;
lazy_static::lazy_static! {
@@ -154,7 +158,10 @@ fn normalize_path(path: &Path) -> String {
// Find "data" in the path and strip everything before and including it
if let Some(idx) = path_str.find("data") {
let stripped = &path_str[idx + 5..]; // Skip "data" + separator
return stripped.replace('\\', "/").trim_start_matches('/').to_string();
return stripped
.replace('\\', "/")
.trim_start_matches('/')
.to_string();
}
path_str.replace('\\', "/")

View File

@@ -147,11 +147,7 @@ async fn handle_socket(socket: WebSocket, state: Arc<WsState>) {
if let Ok(client_msg) = serde_json::from_str::<ClientMessage>(&text) {
handle_client_message(&state_clone, &client_id_clone, client_msg).await;
} else {
tracing::debug!(
"Unknown message from {}: {}",
client_id_clone,
text
);
tracing::debug!("Unknown message from {}: {}", client_id_clone, text);
}
}
Message::Close(_) => break,
@@ -195,7 +191,11 @@ async fn handle_client_message(state: &Arc<WsState>, client_id: &str, msg: Clien
}
};
match state.lock_manager.acquire(&path, client_id, lock_type).await {
match state
.lock_manager
.acquire(&path, client_id, lock_type)
.await
{
Ok(lock_info) => {
let lock_type_str = match lock_info.lock_type {
LockType::Editor => "editor",