feat: initialize cookie once and use set_flags for subsequent operations

Co-authored-by: aider (openai/andrew/openrouter/qwen/qwen3-coder) <aider@aider.chat>
This commit is contained in:
Andrew Phillips
2025-08-18 09:16:40 -03:00
parent e86fbda144
commit 9e62356a30

View File

@@ -28,28 +28,30 @@ impl MagicFileMetaPlugin {
}
fn get_magic_result(&self, flags: CookieFlags) -> io::Result<String> {
// Create a new cookie with the specific flags for this request
let cookie = Cookie::open(flags)
.map_err(|e| io::Error::new(io::ErrorKind::Other, format!("Failed to open magic cookie: {}", e)))?;
cookie.load(&[] as &[&str])
.map_err(|e| io::Error::new(io::ErrorKind::Other, format!("Failed to load magic database: {}", e)))?;
// Use the existing cookie and just change flags
if let Some(cookie) = &self.cookie {
cookie.set_flags(flags)
.map_err(|e| io::Error::new(io::ErrorKind::Other, format!("Failed to set magic flags: {}", e)))?;
let result = cookie.buffer(&self.buffer)
.map_err(|e| io::Error::new(io::ErrorKind::Other, format!("Failed to analyze buffer: {}", e)))?;
let result = cookie.buffer(&self.buffer)
.map_err(|e| io::Error::new(io::ErrorKind::Other, format!("Failed to analyze buffer: {}", e)))?;
// Clean up the result - remove extra whitespace and take first part if needed
let trimmed = result.trim();
// For some magic results, we might want just the first part before semicolon or comma
let cleaned = if trimmed.contains(';') {
trimmed.split(';').next().unwrap_or(trimmed).trim()
} else if trimmed.contains(',') && flags.contains(CookieFlags::MIME_TYPE | CookieFlags::MIME_ENCODING) {
trimmed.split(',').next().unwrap_or(trimmed).trim()
// Clean up the result - remove extra whitespace and take first part if needed
let trimmed = result.trim();
// For some magic results, we might want just the first part before semicolon or comma
let cleaned = if trimmed.contains(';') {
trimmed.split(';').next().unwrap_or(trimmed).trim()
} else if trimmed.contains(',') && flags.contains(CookieFlags::MIME_TYPE | CookieFlags::MIME_ENCODING) {
trimmed.split(',').next().unwrap_or(trimmed).trim()
} else {
trimmed
};
Ok(cleaned.to_string())
} else {
trimmed
};
Ok(cleaned.to_string())
Err(io::Error::new(io::ErrorKind::Other, "Magic cookie not initialized"))
}
}
fn save_all_magic_metadata(&mut self) -> Result<()> {
@@ -109,6 +111,13 @@ impl MetaPlugin for MagicFileMetaPlugin {
// Store raw pointer to connection - unsafe but necessary for this design
self.conn = Some(conn as *const _ as *mut Connection);
// Initialize the magic cookie once
let cookie = Cookie::open(Default::default())
.map_err(|e| anyhow::anyhow!("Failed to open magic cookie: {}", e))?;
cookie.load(&[] as &[&str])
.map_err(|e| anyhow::anyhow!("Failed to load magic database: {}", e))?;
self.cookie = Some(cookie);
Ok(())
}