Skip to content

Commit 0e6d60f

Browse files
committed
Refactor logging and configuration handling across multiple modules
- Removed unused logging functions in `logging.rs` to streamline the code. - Updated session management in `session_manager.rs` by renaming a variable for clarity. - Refactored command handling in `config.rs` to use `first()` instead of `get(0)` for better readability. - Cleaned up unused constants and improved struct definitions in `daemon-manager` and `mcp` modules. - Enhanced error handling and logging consistency across various files, improving overall code maintainability.
1 parent ac00673 commit 0e6d60f

25 files changed

Lines changed: 330 additions & 340 deletions

cli/src/logging.rs

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,22 +4,12 @@ use std::env;
44
// Simple logging functions
55
// In a more advanced setup, we might use the `log` crate
66

7-
pub fn log_debug(message: &str) {
8-
if env::var("GEMINI_DEBUG").is_ok() {
9-
eprintln!("{} {}", "[DEBUG]".dimmed(), message);
10-
}
11-
}
12-
137
pub fn log_info(message: &str) {
148
if env::var("GEMINI_DEBUG").is_ok() {
159
eprintln!("{} {}", "[INFO]".cyan(), message);
1610
}
1711
}
1812

19-
pub fn log_warning(message: &str) {
20-
eprintln!("{} {}", "[WARNING]".yellow(), message);
21-
}
22-
2313
pub fn log_error(message: &str) {
2414
eprintln!("{} {}", "[ERROR]".red().bold(), message);
2515
}

cli/src/session_manager.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ impl SessionManager {
3131
let parts: Vec<&str> = session_id.split('_').collect();
3232
if parts.len() >= 3 {
3333
let terminal_id = parts[1];
34-
let timestamp = parts[2];
34+
let _timestamp = parts[2];
3535
println!(" {}. {} (Terminal {})", i + 1, session_id.blue(), terminal_id);
3636
} else {
3737
println!(" {}. {}", i + 1, session_id.blue());

core/src/config.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -517,7 +517,7 @@ pub fn save_mcp_servers(
517517
let mut claude_servers = HashMap::new();
518518

519519
for server in servers {
520-
let command = server.command.get(0).cloned().unwrap_or_default();
520+
let command = server.command.first().cloned().unwrap_or_default();
521521

522522
claude_servers.insert(
523523
server.name.clone(),

daemon-manager/src/config.rs

Lines changed: 13 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1,55 +1,22 @@
11
use anyhow::{anyhow, Context, Result};
22
use gemini_core::config::{get_mcp_servers_config_path, get_unified_config_path, UnifiedConfig};
33
use std::fs;
4-
use std::path::PathBuf;
54
use std::process::Command;
5+
use serde::Deserialize;
66

7-
// Constants for default configuration content
8-
const DEFAULT_MCP_SERVERS_CONFIG: &str = r#"{
9-
"servers": []
10-
}"#;
11-
12-
const DEFAULT_GEMINI_CONFIG: &str = r#"# Gemini CLI Configuration
13-
14-
[api]
15-
key = ""
16-
model = "gemini-1.5-pro"
17-
18-
[system]
19-
prompt = ""
20-
21-
[features]
22-
history = true
23-
memory = true
24-
"#;
25-
26-
// Gets path to the unified configuration file or component-specific configuration
27-
fn get_config_path(component: &str) -> Result<PathBuf> {
28-
if component == "unified" {
29-
return get_unified_config_path()
30-
.map_err(|e| anyhow!("Could not get unified config path: {}", e));
31-
} else if component == "mcp-servers" {
32-
return get_mcp_servers_config_path()
33-
.map_err(|e| anyhow!("Could not get MCP servers config path: {}", e));
34-
}
35-
36-
// For backward compatibility, support old component-specific files
37-
// But they should be phased out in favor of the unified config
38-
let config_dir = get_unified_config_path()
39-
.map_err(|e| anyhow!("Could not get unified config path: {}", e))?
40-
.parent()
41-
.ok_or_else(|| anyhow!("Could not determine parent directory of unified config"))?
42-
.to_path_buf();
43-
44-
let path = match component {
45-
"cli" | "gemini-cli" => config_dir.join("cli.toml"),
46-
"happe" => config_dir.join("happe.toml"),
47-
"ida" => config_dir.join("ida.toml"),
48-
"mcp-hostd" => config_dir.join("mcp-hostd.toml"),
49-
_ => return Err(anyhow!("Unknown component: {}", component)),
50-
};
7+
// Minimal definition for the section needed by the manager
8+
#[allow(dead_code)] // Fields might be used later or are part of a broader pattern
9+
#[derive(Deserialize, Debug)]
10+
struct GeminiApiConfigSection {
11+
api_key: Option<String>,
12+
}
5113

52-
Ok(path)
14+
// This struct is intentionally simplified for the manager
15+
#[allow(dead_code)] // Fields might be used later or are part of a broader pattern
16+
#[derive(Deserialize, Debug)]
17+
struct Config {
18+
#[serde(rename = "gemini-api")]
19+
gemini_api: Option<GeminiApiConfigSection>,
5320
}
5421

5522
// Get default configuration content for a component

daemon-manager/src/daemon.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ use std::env;
66
use std::fs;
77
use std::path::PathBuf;
88
use std::process::Command;
9-
use toml;
109
use which::which;
1110

1211
// Enum for representing daemon status
@@ -225,7 +224,7 @@ fn process_exists(pid: i32) -> bool {
225224
// Helper function to kill a process
226225
fn kill_process(pid: i32) -> Result<()> {
227226
let status = Command::new("kill")
228-
.arg(&pid.to_string())
227+
.arg(pid.to_string())
229228
.status()
230229
.with_context(|| format!("Failed to execute kill command for PID {}", pid))?;
231230

daemon-manager/src/mcp.rs

Lines changed: 13 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -30,14 +30,12 @@ pub struct McpServer {
3030
pub transport: String,
3131
#[serde(skip_serializing_if = "Option::is_none")]
3232
pub connection: Option<String>,
33-
#[serde(skip_serializing_if = "Option::is_none", rename = "command")]
33+
#[serde(skip_serializing_if = "Option::is_none")]
3434
pub command_string: Option<String>,
35-
#[serde(skip_serializing_if = "Option::is_none", rename = "command", default)]
36-
pub command_array: Option<Vec<String>>,
3735
#[serde(skip_serializing_if = "Option::is_none")]
38-
pub enabled: Option<bool>,
39-
#[serde(skip_serializing_if = "Option::is_none", default)]
4036
pub args: Option<Vec<String>>,
37+
#[serde(skip_serializing_if = "Option::is_none")]
38+
pub enabled: Option<bool>,
4139
#[serde(skip_serializing_if = "Option::is_none", default)]
4240
pub env: Option<HashMap<String, String>>,
4341
#[serde(skip_serializing_if = "Option::is_none", default)]
@@ -65,7 +63,8 @@ pub struct ClaudeServer {
6563
// Claude-compatible format with servers as a map
6664
#[derive(Debug, Serialize, Deserialize)]
6765
pub struct ClaudeServersConfig {
68-
pub mcpServers: HashMap<String, ClaudeServer>,
66+
#[serde(rename = "mcpServers")]
67+
pub mcp_servers: HashMap<String, ClaudeServer>,
6968
}
7069

7170
// Get path to MCP servers configuration file
@@ -111,22 +110,21 @@ fn read_mcp_config() -> Result<McpServers> {
111110
let claude_format_result: Result<ClaudeServersConfig, _> =
112111
serde_json::from_str(&content);
113112

114-
if let Ok(claude_format) = claude_format_result {
113+
if let Ok(mut claude_format) = claude_format_result {
115114
tracing::debug!("Successfully parsed mcp_servers.json as Claude format");
116115
// Convert to our internal format
117116
let mut servers = Vec::new();
118117

119-
for (name, server) in claude_format.mcpServers {
118+
for (name, server) in claude_format.mcp_servers.drain() {
120119
servers.push(McpServer {
121120
name,
122121
transport: "stdio".to_string(), // Claude format assumes stdio
123122
connection: None,
124123
command_string: Some(server.command),
125-
command_array: None,
126-
enabled: server.enabled.or(Some(true)), // Default to enabled if not specified
127124
args: Some(server.args),
128125
env: Some(server.env),
129126
auto_execute: Some(Vec::new()), // Claude format doesn't specify auto_execute
127+
enabled: server.enabled,
130128
});
131129
}
132130

@@ -187,7 +185,7 @@ fn write_mcp_config(servers: &McpServers) -> Result<()> {
187185
.clone()
188186
.or_else(|| {
189187
server
190-
.command_array
188+
.args
191189
.as_ref()
192190
.and_then(|cmd| cmd.first().cloned())
193191
})
@@ -196,7 +194,7 @@ fn write_mcp_config(servers: &McpServers) -> Result<()> {
196194
let args = server.args.clone().unwrap_or_else(|| {
197195
// If we have a command array with more than one element, use all but the first as args
198196
server
199-
.command_array
197+
.args
200198
.as_ref()
201199
.map(|cmd| {
202200
if cmd.len() > 1 {
@@ -222,7 +220,7 @@ fn write_mcp_config(servers: &McpServers) -> Result<()> {
222220
}
223221

224222
let claude_config = ClaudeServersConfig {
225-
mcpServers: claude_servers,
223+
mcp_servers: claude_servers,
226224
};
227225

228226
// Serialize in the Claude-compatible format
@@ -306,10 +304,9 @@ pub async fn enable_server(name: &str) -> Result<()> {
306304
name: name.to_string(),
307305
transport: "stdio".to_string(),
308306
command_string: Some(command_str.clone()),
309-
command_array: None,
307+
args: Some(Vec::new()),
310308
connection: None,
311309
enabled: Some(true),
312-
args: Some(Vec::new()),
313310
env: Some(HashMap::new()),
314311
auto_execute: Some(vec![]),
315312
});
@@ -349,10 +346,9 @@ pub async fn disable_server(name: &str) -> Result<()> {
349346
name: name.to_string(),
350347
transport: "stdio".to_string(),
351348
command_string: Some(command_str.clone()),
352-
command_array: None,
349+
args: Some(Vec::new()),
353350
connection: None,
354351
enabled: Some(false),
355-
args: Some(Vec::new()),
356352
env: Some(HashMap::new()),
357353
auto_execute: Some(vec![]),
358354
});
@@ -493,7 +489,6 @@ pub async fn install_server(path: &str, custom_name: Option<String>) -> Result<S
493489
command_string: Some(command),
494490
connection: None,
495491
enabled: Some(true),
496-
command_array: None,
497492
args: Some(args),
498493
env: Some(HashMap::new()),
499494
auto_execute: Some(Vec::new()),

happe/src/coordinator.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ pub async fn process_query(
7676
gemini_client,
7777
contents, // Pass the constructed Vec<Content>
7878
&system_prompt,
79-
tools.as_ref().map(|v| &**v),
79+
tools.as_deref(),
8080
)
8181
.await
8282
{
@@ -216,7 +216,7 @@ fn construct_prompt(query: &str, memories: &[MemoryItem]) -> Vec<Content> {
216216
memory_text.push_str(&format!("{}. {}\n", i + 1, mem.content));
217217
}
218218

219-
memory_text.push_str("\n");
219+
memory_text.push('\n');
220220
content_parts.push(Content {
221221
parts: vec![Part::text(memory_text)],
222222
role: Some("user".to_string()),

happe/src/http_server.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use crate::mcp_client::McpHostClient;
33
use gemini_core::config::HappeConfig;
44
use crate::session::{InMemorySessionStore, Session, SessionStoreRef};
55
use axum::{
6-
extract::{Extension, State},
6+
extract::State,
77
http::{HeaderMap, StatusCode},
88
response::{IntoResponse, Response},
99
routing::{get, post},

happe/src/mcp_client.rs

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -178,14 +178,3 @@ fn is_valid_function_name(name: &str) -> bool {
178178
name.chars()
179179
.all(|c| c.is_alphanumeric() || c == '_' || c == '-' || c == '.')
180180
}
181-
182-
/// Sanitize JSON schema for Gemini API
183-
fn sanitize_json_schema(schema: Value) -> Value {
184-
// Gemini has stricter requirements for JSON schema than some MCP servers might provide
185-
// This is a simple implementation that keeps the schema as-is
186-
// In a real implementation, you might want to:
187-
// - Remove unsupported keywords
188-
// - Ensure all required fields are present
189-
// - Convert formats to supported ones
190-
schema
191-
}

happe/src/session/adapters/in_memory.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,12 @@ use log::{debug, warn};
66

77
use crate::session::store::{Session, SessionStore, SessionStoreError};
88

9+
impl Default for InMemorySessionStore {
10+
fn default() -> Self {
11+
Self::new()
12+
}
13+
}
14+
915
/// In-memory implementation of SessionStore
1016
#[derive(Debug)]
1117
pub struct InMemorySessionStore {

0 commit comments

Comments
 (0)