Skip to content

A command-line tool to convert handwritten notes to markdown files

fix: improved error handling and error messages

Tejas Raskard96816f7aabd
diff --git a/Cargo.lock b/Cargo.lock
index 9f89970..64338ae 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -820,7 +820,7 @@ dependencies = [
[[package]]
name = "notedmd"
-version = "0.2.2"
+version = "0.2.3"
dependencies = [
"async-trait",
"base64",
@@ -833,6 +833,7 @@ dependencies = [
"reqwest",
"serde",
"serde_json",
+ "thiserror 2.0.12",
"tokio",
"toml",
]
diff --git a/Cargo.toml b/Cargo.toml
index 0f9cffa..59d580b 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "notedmd"
-version = "0.2.2"
+version = "0.2.3"
edition = "2024"
description = "A command-line tool to convert handwritten notes into a clean and readable Markdown file."
license = "MIT"
@@ -23,3 +23,4 @@ dialoguer = "0.11.0"
colored = "3.0.0"
indicatif = "0.17.11"
async-trait = "0.1.88"
+thiserror = "2.0.12"
diff --git a/src/ai_provider.rs b/src/ai_provider.rs
index c2bb829..64046f9 100644
--- a/src/ai_provider.rs
+++ b/src/ai_provider.rs
@@ -1,9 +1,7 @@
+use crate::{error::NotedError, file_utils::FileData};
use async_trait::async_trait;
-use crate::file_utils::FileData;
-
#[async_trait]
pub trait AiProvider {
- async fn send_request(&self, file_data: FileData)
- -> Result<String, Box<dyn std::error::Error>>;
+ async fn send_request(&self, file_data: FileData) -> Result<String, NotedError>;
}
diff --git a/src/clients/claude_client.rs b/src/clients/claude_client.rs
index 24cc7a9..91b9024 100644
--- a/src/clients/claude_client.rs
+++ b/src/clients/claude_client.rs
@@ -1,7 +1,8 @@
use crate::ai_provider::AiProvider;
+use crate::error::NotedError;
use crate::file_utils::FileData;
use async_trait::async_trait;
-use reqwest::Client;
+use reqwest::{Client, StatusCode};
use serde::{Deserialize, Serialize};
// Request structs
@@ -42,6 +43,13 @@ struct Source {
#[derive(Deserialize, Debug)]
pub struct ClaudeResponse {
pub content: Vec<ContentResponse>,
+ #[serde(default)]
+ pub error: Option<ClaudeError>,
+}
+
+#[derive(Deserialize, Debug)]
+pub struct ClaudeError {
+ pub message: String,
}
#[derive(Deserialize, Debug)]
@@ -70,10 +78,7 @@ impl ClaudeClient {
#[async_trait]
impl AiProvider for ClaudeClient {
- async fn send_request(
- &self,
- file_data: FileData,
- ) -> Result<String, Box<dyn std::error::Error>> {
+ async fn send_request(&self, file_data: FileData) -> Result<String, NotedError> {
let url = "https://api.anthropic.com/v1/messages".to_string();
let prompt = if let Some(custom_prompt) = &self.prompt {
@@ -113,20 +118,42 @@ impl AiProvider for ClaudeClient {
.header("anthropic-version", "2023-06-01")
.json(&request_body)
.send()
- .await?
- .json::<ClaudeResponse>()
.await?;
- let response_text = response.content.first();
- let markdown_text = if let Some(part) = response_text {
- &part.text
- } else {
- println!("{}", "Could not find text in Claude response.");
- std::process::exit(1);
- };
+ let status = response.status();
+ let response_body = response.text().await?;
+
+ if status != StatusCode::OK {
+ if status == StatusCode::UNAUTHORIZED {
+ return Err(NotedError::InvalidApiKey);
+ }
+ let error_response: Result<ClaudeResponse, _> = serde_json::from_str(&response_body);
+ if let Ok(err_resp) = error_response {
+ if let Some(error) = err_resp.error {
+ return Err(NotedError::ApiError(error.message));
+ }
+ }
+ return Err(NotedError::ApiError(format!(
+ "Received status code: {}",
+ status
+ )));
+ }
+
+ let claude_response: ClaudeResponse = serde_json::from_str(&response_body)
+ .map_err(|e| NotedError::ResponseDecodeError(e.to_string()))?;
+
+ if let Some(error) = claude_response.error {
+ return Err(NotedError::ApiError(error.message));
+ }
+
+ let markdown_text = claude_response
+ .content
+ .first()
+ .map(|c| c.text.as_str())
+ .unwrap_or("");
let cleaned_markdown = markdown_text
- .trim_start_matches("```markdown")
+ .trim_start_matches("```markdown\n")
.trim_end_matches("```");
Ok(cleaned_markdown.to_string())
diff --git a/src/clients/gemini_client.rs b/src/clients/gemini_client.rs
index b352164..f2cd83c 100644
--- a/src/clients/gemini_client.rs
+++ b/src/clients/gemini_client.rs
@@ -1,7 +1,8 @@
use crate::ai_provider::AiProvider;
+use crate::error::NotedError;
use crate::file_utils::FileData;
use async_trait::async_trait;
-use reqwest::Client;
+use reqwest::{Client, StatusCode};
use serde::{Deserialize, Serialize};
// Request structs
@@ -36,7 +37,14 @@ struct InlineData {
#[derive(Deserialize, Debug)]
pub struct GeminiResponse {
- pub candidates: Vec<Candidate>,
+ pub candidates: Option<Vec<Candidate>>,
+ #[serde(default)]
+ pub error: Option<GeminiError>,
+}
+
+#[derive(Deserialize, Debug)]
+pub struct GeminiError {
+ pub message: String,
}
#[derive(Deserialize, Debug)]
@@ -73,10 +81,7 @@ impl GeminiClient {
#[async_trait]
impl AiProvider for GeminiClient {
- async fn send_request(
- &self,
- file_data: FileData,
- ) -> Result<String, Box<dyn std::error::Error>> {
+ async fn send_request(&self, file_data: FileData) -> Result<String, NotedError> {
let url = format!(
"https://generativelanguage.googleapis.com/v1beta/models/gemma-3-27b-it:generateContent?key={}",
self.api_key
@@ -106,25 +111,41 @@ impl AiProvider for GeminiClient {
}],
};
- let response = self
- .client
- .post(&url)
- .json(&request_body)
- .send()
- .await?
- .json::<GeminiResponse>()
- .await?;
+ let response = self.client.post(&url).json(&request_body).send().await?;
+
+ let status = response.status();
+ let response_body = response.text().await?;
+
+ if status != StatusCode::OK {
+ if status == StatusCode::UNAUTHORIZED {
+ return Err(NotedError::InvalidApiKey);
+ }
+ let error_response: Result<GeminiResponse, _> = serde_json::from_str(&response_body);
+ if let Ok(err_resp) = error_response {
+ if let Some(error) = err_resp.error {
+ return Err(NotedError::ApiError(error.message));
+ }
+ }
+ return Err(NotedError::ApiError(format!(
+ "Received status code: {}",
+ status
+ )));
+ }
+
+ let gemini_response: GeminiResponse = serde_json::from_str(&response_body)
+ .map_err(|e| NotedError::ResponseDecodeError(e.to_string()))?;
- let response_text = response
+ if let Some(error) = gemini_response.error {
+ return Err(NotedError::ApiError(error.message));
+ }
+
+ let markdown_text = gemini_response
.candidates
- .first()
- .and_then(|candidate| candidate.content.parts.first());
- let markdown_text = if let Some(part) = response_text {
- &part.text
- } else {
- println!("{}", "Could not find text in Gemini response.");
- std::process::exit(1);
- };
+ .as_ref()
+ .and_then(|candidates| candidates.first())
+ .and_then(|candidate| candidate.content.parts.first())
+ .map(|part| part.text.as_str())
+ .unwrap_or("");
let cleaned_markdown = markdown_text
.trim_start_matches("```markdown\n")
diff --git a/src/clients/mod.rs b/src/clients/mod.rs
index 354cffa..ddf7ef0 100644
--- a/src/clients/mod.rs
+++ b/src/clients/mod.rs
@@ -1,4 +1,3 @@
-
pub mod claude_client;
pub mod gemini_client;
pub mod ollama_client;
diff --git a/src/clients/ollama_client.rs b/src/clients/ollama_client.rs
index 8a59754..6041a14 100644
--- a/src/clients/ollama_client.rs
+++ b/src/clients/ollama_client.rs
@@ -1,8 +1,8 @@
use async_trait::async_trait;
-use reqwest::Client;
+use reqwest::{Client, StatusCode};
use serde::{Deserialize, Serialize};
-use crate::{ai_provider::AiProvider, file_utils::FileData};
+use crate::{ai_provider::AiProvider, error::NotedError, file_utils::FileData};
// Request struct
#[derive(Serialize)]
@@ -17,6 +17,8 @@ struct OllamaRequest {
#[derive(Deserialize, Debug)]
pub struct OllamaResponse {
pub response: String,
+ #[serde(default)]
+ pub error: Option<String>,
}
// Client struct
@@ -40,10 +42,7 @@ impl OllamaClient {
#[async_trait]
impl AiProvider for OllamaClient {
- async fn send_request(
- &self,
- file_data: FileData,
- ) -> Result<String, Box<dyn std::error::Error>> {
+ async fn send_request(&self, file_data: FileData) -> Result<String, NotedError> {
let url = format!("{}/api/generate", self.url);
let prompt = if let Some(custom_prompt) = &self.prompt {
custom_prompt.clone()
@@ -58,17 +57,33 @@ impl AiProvider for OllamaClient {
stream: false,
};
- let response = self
- .client
- .post(&url)
- .json(&request_body)
- .send()
- .await?
- .json::<OllamaResponse>()
- .await?;
+ let response = self.client.post(&url).json(&request_body).send().await?;
- let response_text = response.response;
- let cleaned_markdown = response_text
+ let status = response.status();
+ let response_body = response.text().await?;
+
+ if status != StatusCode::OK {
+ let error_response: Result<OllamaResponse, _> = serde_json::from_str(&response_body);
+ if let Ok(err_resp) = error_response {
+ if let Some(error) = err_resp.error {
+ return Err(NotedError::ApiError(error));
+ }
+ }
+ return Err(NotedError::ApiError(format!(
+ "Received status code: {}",
+ status
+ )));
+ }
+
+ let ollama_response: OllamaResponse = serde_json::from_str(&response_body)
+ .map_err(|e| NotedError::ResponseDecodeError(e.to_string()))?;
+
+ if let Some(error) = ollama_response.error {
+ return Err(NotedError::ApiError(error));
+ }
+
+ let cleaned_markdown = ollama_response
+ .response
.trim_start_matches("```markdown\n")
.trim_end_matches("```");
diff --git a/src/config.rs b/src/config.rs
index 6e75c20..4b3ca74 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -1,7 +1,7 @@
-use std::{fs, path::PathBuf};
-
+use crate::error::NotedError;
use directories::ProjectDirs;
use serde::{Deserialize, Serialize};
+use std::{fs, path::PathBuf};
#[derive(Serialize, Deserialize, Debug, Default)]
pub struct Config {
@@ -39,17 +39,17 @@ pub fn get_config_path() -> Option<PathBuf> {
}
impl Config {
- pub fn load() -> Self {
+ pub fn load() -> Result<Self, NotedError> {
if let Some(config_path) = get_config_path() {
if config_path.exists() {
- let content = fs::read_to_string(config_path).unwrap_or_default();
- return toml::from_str(&content).unwrap_or_default();
+ let content = fs::read_to_string(config_path)?;
+ return Ok(toml::from_str(&content)?);
}
}
- Self::default()
+ Ok(Self::default())
}
- pub fn save(&self) -> Result<(), Box<dyn std::error::Error>> {
+ pub fn save(&self) -> Result<(), NotedError> {
if let Some(config_path) = get_config_path() {
let toml_string = toml::to_string_pretty(self)?;
fs::write(config_path, toml_string)?;
diff --git a/src/error.rs b/src/error.rs
new file mode 100644
index 0000000..6050bfc
--- /dev/null
+++ b/src/error.rs
@@ -0,0 +1,49 @@
+use thiserror::Error;
+
+#[derive(Debug, Error)]
+pub enum NotedError {
+ #[error(" Configuration file not found. Please run 'notedmd config --edit' to set it up.")]
+ ConfigNotFound,
+
+ #[error(" Failed to save configuration: {0}")]
+ ConfigSaveError(#[from] toml::ser::Error),
+
+ #[error(" Failed to read configuration: {0}")]
+ ConfigReadError(#[from] toml::de::Error),
+
+ #[error(" I/O error: {0}")]
+ IoError(#[from] std::io::Error),
+
+ #[error(" Network request failed: {0}")]
+ NetworkError(#[from] reqwest::Error),
+
+ #[error(" API key is invalid or missing. Please check your configuration.")]
+ InvalidApiKey,
+
+ #[error(" The AI provider returned an error: {0}")]
+ ApiError(String),
+
+ #[error(" Failed to decode API response: {0}")]
+ ResponseDecodeError(String),
+
+ #[error(" Could not determine the file name for the path: {0}")]
+ FileNameError(String),
+
+ #[error(" File type not supported: {0}")]
+ UnsupportedFileType(String),
+
+ #[error(" Ollama is not configured properly. Please run 'notedmd config --edit' to set it up.")]
+ OllamaNotConfigured,
+
+ #[error(" Gemini is not configured properly. Please run 'notedmd config --edit' to set it up.")]
+ GeminiNotConfigured,
+
+ #[error(" Claude is not configured properly. Please run 'notedmd config --edit' to set it up.")]
+ ClaudeNotConfigured,
+
+ #[error(" No active provider. Please run 'notedmd config --edit' to set a provider.")]
+ NoActiveProvider,
+
+ #[error(" Dialoguer error: {0}")]
+ DialoguerError(#[from] dialoguer::Error),
+}
diff --git a/src/file_utils.rs b/src/file_utils.rs
index 01686f4..61cde93 100644
--- a/src/file_utils.rs
+++ b/src/file_utils.rs
@@ -1,3 +1,4 @@
+use crate::error::NotedError;
use base64::{Engine, engine::general_purpose};
use std::{fs, path::Path};
@@ -6,10 +7,10 @@ pub struct FileData {
pub mime_type: String,
}
-pub fn process_file(file_path: &str) -> Result<FileData, std::io::Error> {
+pub fn process_file(file_path: &str) -> Result<FileData, NotedError> {
let data = fs::read(file_path)?;
let encoded_data: String = general_purpose::STANDARD.encode(&data);
- let mime_type = get_file_mime_type(file_path);
+ let mime_type = get_file_mime_type(file_path)?;
Ok(FileData {
encoded_data,
@@ -17,19 +18,17 @@ pub fn process_file(file_path: &str) -> Result<FileData, std::io::Error> {
})
}
-pub fn get_file_mime_type(file_path: &str) -> String {
+pub fn get_file_mime_type(file_path: &str) -> Result<String, NotedError> {
let file_extension = Path::new(file_path)
.extension()
.and_then(|ext| ext.to_str());
match file_extension {
- Some("png") => "image/png".to_string(),
- Some("pdf") => "application/pdf".to_string(),
- Some("jpg") => "image/jpeg".to_string(),
- Some("jpeg") => "image/jpeg".to_string(),
- _ => {
- println!("Warning: Unknown file type, defaulting to application/octet-stream");
- "application/octet-stream".to_string()
- }
+ Some("png") => Ok("image/png".to_string()),
+ Some("pdf") => Ok("application/pdf".to_string()),
+ Some("jpg") => Ok("image/jpeg".to_string()),
+ Some("jpeg") => Ok("image/jpeg".to_string()),
+ Some(ext) => Err(NotedError::UnsupportedFileType(ext.to_string())),
+ None => Err(NotedError::UnsupportedFileType("No extension".to_string())),
}
}
diff --git a/src/main.rs b/src/main.rs
index 8de2721..78fb3c7 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -2,6 +2,7 @@ mod ai_provider;
mod cli;
mod clients;
mod config;
+mod error;
mod file_utils;
mod ui;
@@ -13,6 +14,7 @@ use config::{ClaudeConfig, Config, GeminiConfig, OllamaConfig};
use dialoguer::Input;
use dialoguer::Select;
use dialoguer::{Password, theme::ColorfulTheme};
+use error::NotedError;
use indicatif::ProgressBar;
use indicatif::ProgressStyle;
@@ -29,21 +31,12 @@ async fn process_and_save_file(
client: &dyn AiProvider,
output_dir: Option<&str>,
progress_bar: &ProgressBar,
-) {
+) -> Result<(), NotedError> {
let path = Path::new(file_path);
let file_name = match path.file_name() {
Some(name) => name,
None => {
- progress_bar.println(format!(
- "{} {}",
- "✖".red(),
- format!(
- "Could not determine filename for '{}'. Skipping.",
- file_path
- )
- .red()
- ));
- return;
+ return Err(NotedError::FileNameError(file_path.to_string()));
}
};
@@ -52,17 +45,7 @@ async fn process_and_save_file(
format!("Processing file: {:#?}", file_name).bold()
));
- let file_data = match file_utils::process_file(file_path) {
- Ok(data) => data,
- Err(e) => {
- progress_bar.println(format!(
- "{} {}",
- "✖".red(),
- format!("Failed to read file. Error: {}", e).red()
- ));
- return;
- }
- };
+ let file_data = file_utils::process_file(file_path)?;
progress_bar.println(format!(
"{} {}",
"✔".green(),
@@ -71,18 +54,15 @@ async fn process_and_save_file(
progress_bar.set_message(format!("{}", "Sending to your AI model...".yellow()));
- let markdown = match client.send_request(file_data).await {
- Ok(cleaned_markdown) => cleaned_markdown,
- Err(e) => {
- progress_bar.println(format!("{} {}", "✖".red(), format!("Error: {}", e).red()));
- return;
- }
- };
+ let markdown = client.send_request(file_data).await?;
progress_bar.println(format!("{} {}", "✔".green(), "Received response.".green()));
let output_path = match output_dir {
Some(dir) => {
let dir_path = Path::new(dir);
+ if !dir_path.exists() {
+ std::fs::create_dir_all(dir_path)?;
+ }
let final_path = dir_path.join(file_name);
final_path
.with_extension("md")
@@ -93,21 +73,26 @@ async fn process_and_save_file(
};
match std::fs::write(&output_path, markdown) {
- Ok(_) => progress_bar.println(format!(
- "{} {}",
- "✔".green(),
- format!("Markdown saved to '{}'", output_path.cyan()).green()
- )),
- Err(e) => progress_bar.println(format!(
- "{} {}",
- "✖".red(),
- format!("Failed to save file. Error: {}", e).red()
- )),
+ Ok(_) => {
+ progress_bar.println(format!(
+ "{} {}",
+ "✔".green(),
+ format!("Markdown saved to '{}'", output_path.cyan()).green()
+ ));
+ Ok(())
+ }
+ Err(e) => {
+ progress_bar.println(format!(
+ "{} {}",
+ "✖".red(),
+ format!("Failed to save file to '{}'. Error: {}", &output_path, e).red()
+ ));
+ Err(e.into())
+ }
}
}
-#[tokio::main]
-async fn main() {
+async fn run() -> Result<(), NotedError> {
let args = Cli::parse();
match args.command {
Commands::Config {
@@ -123,8 +108,7 @@ async fn main() {
if config_path.exists() {
println!("Config saved in {:?}", config_path);
} else {
- eprintln!("No config found.\nRun 'notedmd config --edit' to configure.");
- return;
+ return Err(NotedError::ConfigNotFound);
}
}
}
@@ -132,48 +116,40 @@ async fn main() {
if show {
if let Some(config_path) = config::get_config_path() {
if config_path.exists() {
- let config = Config::load();
+ let config = Config::load()?;
print_clean_config(config);
} else {
- eprintln!("No config found.\nRun 'notedmd config --edit' to configure.");
- return;
+ return Err(NotedError::ConfigNotFound);
}
}
}
if let Some(ref key) = set_api_key {
- let mut config = Config::load();
+ let mut config = Config::load()?;
config.active_provider = Some("gemini".to_string());
config.gemini = Some(config::GeminiConfig {
api_key: key.to_string(),
});
- if let Err(e) = config.save() {
- println!("Error while saving config: {}", e)
- } else {
- println!("Config saved successfully.");
- }
+ config.save()?;
+ println!("Config saved successfully.");
}
if let Some(ref key) = set_claude_api_key {
- let mut config = Config::load();
+ let mut config = Config::load()?;
config.active_provider = Some("claude".to_string());
let model = Input::with_theme(&ColorfulTheme::default())
.with_prompt("Claude model")
.default("claude-3-opus-20240229".to_string())
- .interact_text()
- .unwrap();
+ .interact_text()?;
config.claude = Some(config::ClaudeConfig {
api_key: key.to_string(),
- model: model,
+ model,
});
- if let Err(e) = config.save() {
- println!("Error while saving config: {}", e)
- } else {
- println!("Config saved successfully.");
- }
+ config.save()?;
+ println!("Config saved successfully.");
}
if edit {
@@ -192,123 +168,67 @@ async fn main() {
.with_prompt("Choose your AI provider")
.items(&providers)
.default(0)
- .interact()
- .unwrap();
+ .interact()?;
match selected_provider {
0 => {
- let mut config = Config::load();
- let _api_key = match Password::with_theme(&ColorfulTheme::default())
+ let mut config = Config::load()?;
+ let api_key = Password::with_theme(&ColorfulTheme::default())
.with_prompt("Enter your Gemini API key: ")
- .interact()
- {
- Ok(key) => {
- config.active_provider = Some("gemini".to_string());
- config.gemini = Some(GeminiConfig {
- api_key: key.clone(),
- });
- let _save = match config.save() {
- Ok(()) => {
- println!("{}", "Config saved successfully.".green())
- }
- Err(e) => {
- eprintln!("{}:{}", "Error saving the config.".red(), e)
- }
- };
- key
- }
- Err(e) => {
- eprintln!("{}", e);
- std::process::exit(1);
- }
- };
+ .interact()?;
+ config.active_provider = Some("gemini".to_string());
+ config.gemini = Some(GeminiConfig { api_key });
+ config.save()?;
+ println!("{}", "Config saved successfully.".green());
}
1 => {
- let mut config = Config::load();
- let _api_key = match Password::with_theme(&ColorfulTheme::default())
+ let mut config = Config::load()?;
+ let api_key = Password::with_theme(&ColorfulTheme::default())
.with_prompt("Enter your Claude API key: ")
- .interact()
- {
- Ok(key) => {
- config.active_provider = Some("claude".to_string());
- let anthropic_models = vec![
- " claude-opus-4-20250514",
- " claude-sonnet-4-20250514",
- " claude-3-7-sonnet-20250219",
- " claude-3-5-haiku-20241022",
- " claude-3-5-sonnet-20241022",
- " other",
- ];
- let selected_model = Select::with_theme(&ColorfulTheme::default())
- .with_prompt("Choose your Claude model:")
- .items(&anthropic_models)
- .default(0)
- .interact()
- .unwrap();
-
- if selected_model == &anthropic_models.len() - 1 {
- let other_model =
- Input::with_theme(&ColorfulTheme::default())
- .with_prompt(
- "Enter the custom model name (e.g., claude-3-sonnet-20240229)",
- )
- .interact()
- .unwrap();
-
- config.claude = Some(ClaudeConfig {
- api_key: key.clone(),
- model: other_model,
- });
- } else {
- config.claude = Some(ClaudeConfig {
- api_key: key.clone(),
- model: anthropic_models[selected_model].trim().to_string(),
- });
- }
-
- let _save = match config.save() {
- Ok(()) => {
- println!("{}", "Config saved successfully.".green())
- }
- Err(e) => {
- eprintln!("{}:{}", "Error saving the config.".red(), e)
- }
- };
- key
- }
- Err(e) => {
- eprintln!("{}", e);
- std::process::exit(1);
- }
+ .interact()?;
+ config.active_provider = Some("claude".to_string());
+ let anthropic_models = vec![
+ " claude-opus-4-20250514",
+ " claude-sonnet-4-20250514",
+ " claude-3-7-sonnet-20250219",
+ " claude-3-5-haiku-20241022",
+ " claude-3-5-sonnet-20241022",
+ " Other",
+ ];
+ let selected_model = Select::with_theme(&ColorfulTheme::default())
+ .with_prompt("Choose your Claude model:")
+ .items(&anthropic_models)
+ .default(0)
+ .interact()?;
+
+ let model = if selected_model == anthropic_models.len() - 1 {
+ Input::with_theme(&ColorfulTheme::default())
+ .with_prompt("Enter the custom model name:")
+ .interact_text()?
+ } else {
+ anthropic_models[selected_model].trim().to_string()
};
+
+ config.claude = Some(ClaudeConfig { api_key, model });
+ config.save()?;
+ println!("{}", "Config saved successfully.".green());
}
2 => {
let url = Input::with_theme(&ColorfulTheme::default())
.with_prompt("Ollama server url")
.default("http://localhost:11434".to_string())
- .interact_text()
- .unwrap();
+ .interact_text()?;
let model = Input::with_theme(&ColorfulTheme::default())
.with_prompt("Ollama model")
.default("gemma3:27b".to_string())
- .interact_text()
- .unwrap();
+ .interact_text()?;
- let mut config = Config::default();
+ let mut config = Config::load()?;
config.active_provider = Some("ollama".to_string());
- config.ollama = Some(OllamaConfig {
- url: url,
- model: model,
- });
- let _save = match config.save() {
- Ok(()) => {
- println!("{}", "Config saved successfully.".green())
- }
- Err(e) => {
- eprintln!("{}:{}", "Error saving the config.".red(), e)
- }
- };
+ config.ollama = Some(OllamaConfig { url, model });
+ config.save()?;
+ println!("{}", "Config saved successfully.".green());
}
_ => unreachable!(),
}
@@ -321,13 +241,10 @@ async fn main() {
if let Some(ref new_provider) = set_provider {
if let Some(config_path) = get_config_path() {
if !config_path.exists() {
- eprintln!(
- "No configuration file found. Please run 'notedmd config --edit' to get started."
- );
- return;
+ return Err(NotedError::ConfigNotFound);
}
- let mut config = Config::load();
+ let mut config = Config::load()?;
let new_provider_str = new_provider.as_str();
let is_configured = match new_provider_str {
"gemini" => config.gemini.is_some(),
@@ -338,17 +255,14 @@ async fn main() {
"Invalid provider '{}'. Please choose from 'gemini', 'claude', or 'ollama'.",
new_provider
);
- return;
+ return Ok(());
}
};
if is_configured {
config.active_provider = Some(new_provider_str.to_string());
- if let Err(e) = config.save() {
- eprintln!("{}: {}", "Error saving the config.".red(), e);
- } else {
- println!("Active provider set to '{}'.", new_provider_str.cyan());
- }
+ config.save()?;
+ println!("Active provider set to '{}'.", new_provider_str.cyan());
} else {
eprintln!(
"{} is not configured. Please run 'notedmd config --edit' to set it up.",
@@ -367,11 +281,10 @@ async fn main() {
{
if let Some(config_path) = get_config_path() {
if config_path.exists() {
- let config = Config::load();
+ let config = Config::load()?;
print_clean_config(config);
} else {
- eprintln!("No config found.\nRun 'notedmd config --edit' to configure.");
- return;
+ return Err(NotedError::ConfigNotFound);
}
}
}
@@ -382,7 +295,7 @@ async fn main() {
api_key,
prompt,
} => {
- let config = Config::load();
+ let config = Config::load()?;
let client: Box<dyn AiProvider> = match config.active_provider.as_deref() {
Some("gemini") => {
let final_api_key = if let Some(key) = api_key {
@@ -390,8 +303,7 @@ async fn main() {
} else if let Some(gemini_config) = &config.gemini {
gemini_config.api_key.clone()
} else {
- eprintln!("{}", "Gemini is not configured properly. Run 'notedmd config' to configure it.".red());
- std::process::exit(1);
+ return Err(NotedError::GeminiNotConfigured);
};
Box::new(GeminiClient::new(final_api_key, prompt))
}
@@ -399,14 +311,12 @@ async fn main() {
let url = if let Some(ollama_config) = &config.ollama {
ollama_config.url.clone()
} else {
- eprintln!("{}", "Ollama is not configured properly. Run 'notedmd config' to configure it.".red());
- std::process::exit(1);
+ return Err(NotedError::OllamaNotConfigured);
};
let model = if let Some(ollama_config) = &config.ollama {
ollama_config.model.clone()
} else {
- eprintln!("{}", "Ollama is not configured properly. Run 'notedmd config' to configure it.".red());
- std::process::exit(1);
+ return Err(NotedError::OllamaNotConfigured);
};
Box::new(OllamaClient::new(url, model, prompt))
}
@@ -416,68 +326,80 @@ async fn main() {
} else if let Some(claude_config) = &config.claude {
claude_config.api_key.clone()
} else {
- eprintln!("{}", "Claude is not configured properly. Run 'notedmd config' to configure it.".red());
- std::process::exit(1);
+ return Err(NotedError::ClaudeNotConfigured);
};
let model = if let Some(claude_config) = &config.claude {
claude_config.model.clone()
} else {
- eprintln!("{}", "Claude is not configured properly. Run 'notedmd config' to configure it.".red());
- std::process::exit(1);
+ return Err(NotedError::ClaudeNotConfigured);
};
Box::new(ClaudeClient::new(api_key, model, prompt))
}
- _ => {
- eprintln!(
- "{}",
- "notedmd is not configured. Run 'notedmd config' to configure it first."
- .red()
- );
- std::process::exit(1);
- }
+ _ => return Err(NotedError::NoActiveProvider),
};
let input_path = Path::new(&path);
+ if !input_path.exists() {
+ return Err(NotedError::IoError(std::io::Error::new(
+ std::io::ErrorKind::NotFound,
+ format!("Input path not found: {}", path),
+ )));
+ }
+
if input_path.is_dir() {
- let files_to_convert: Vec<_> = std::fs::read_dir(input_path)
- .unwrap()
+ let files_to_convert: Vec<_> = std::fs::read_dir(input_path)?
+ .filter_map(Result::ok)
.filter_map(|entry| {
- let entry = entry.ok()?;
let path = entry.path();
- let mime_type = file_utils::get_file_mime_type(path.to_str()?);
- if path.is_file() && mime_type != "application/octet-stream" {
- Some(path)
- } else {
- None
+ if path.is_file() {
+ if let Some(path_str) = path.to_str() {
+ if file_utils::get_file_mime_type(path_str).is_ok() {
+ return Some(path);
+ }
+ }
}
+ None
})
.collect();
+ if files_to_convert.is_empty() {
+ println!("No supported files found in the directory.");
+ return Ok(());
+ }
+
let progress_bar = ProgressBar::new(files_to_convert.len() as u64);
progress_bar.set_style(
ProgressStyle::default_bar()
.template("{bar:40.cyan/blue} {pos}/{len} {msg}")
.unwrap(),
);
-
progress_bar.set_message("Processing files...");
for file_path_buf in files_to_convert {
- process_and_save_file(
- file_path_buf.to_str().unwrap(),
- client.as_ref(),
- output.as_deref(),
- &progress_bar,
- )
- .await;
+ if let Some(file_path_str) = file_path_buf.to_str() {
+ if let Err(e) = process_and_save_file(
+ file_path_str,
+ client.as_ref(),
+ output.as_deref(),
+ &progress_bar,
+ )
+ .await
+ {
+ progress_bar.println(format!("{}", e.to_string().red()));
+ }
+ }
progress_bar.inc(1);
}
progress_bar
.finish_with_message(format!("{}", "Completed processing all files".green()));
} else {
+ let path_str = input_path.to_str().ok_or_else(|| {
+ NotedError::FileNameError(input_path.to_string_lossy().to_string())
+ })?;
+ file_utils::get_file_mime_type(path_str)?;
let progress_bar = ProgressBar::new(1);
progress_bar.set_style(
ProgressStyle::default_bar()
@@ -485,12 +407,29 @@ async fn main() {
.unwrap(),
);
progress_bar.set_message("Processing file...");
- process_and_save_file(&path, client.as_ref(), output.as_deref(), &progress_bar)
- .await;
+ if let Err(e) = process_and_save_file(
+ path_str,
+ client.as_ref(),
+ output.as_deref(),
+ &progress_bar,
+ )
+ .await
+ {
+ progress_bar.println(format!("{}", e.to_string().red()));
+ }
progress_bar.inc(1);
progress_bar
.finish_with_message(format!("{}", "Completed processing file".green()));
}
}
}
+ Ok(())
+}
+
+#[tokio::main]
+async fn main() {
+ if let Err(e) = run().await {
+ eprintln!("{} {}", "✖".red(), e.to_string().red());
+ std::process::exit(1);
+ }
}