agy_bridge/lib.rs
1#![doc = include_str!("../README.md")]
2//! agy-bridge: Standalone reusable `PyO3` bridge for the Google Antigravity SDK.
3
4// Allow `::agy_bridge::` paths (generated by the `#[llm_tool]` proc macro) to
5// resolve when compiling tests within this crate.
6extern crate self as agy_bridge;
7
8/// Agent lifecycle management: creation, chat, shutdown.
9pub mod agent;
10/// Configuration types for agents, models, capabilities, and MCP servers.
11pub mod config;
12
13/// Multimodal content types for chat input (text, image, document, audio, video).
14pub mod content;
15/// Error types for the bridge.
16pub mod error;
17/// Pre/post-turn and tool-call lifecycle hooks.
18pub mod hooks;
19/// Policy rules for tool-call filtering and workspace scoping.
20pub mod policies;
21/// Python runtime bridge: command dispatch over a dedicated thread.
22pub mod runtime;
23
24/// Streaming response channels for text, thought, and tool-call events.
25pub mod streaming;
26/// Custom Rust tool dispatch and definition types.
27pub mod tools;
28/// Event-driven trigger definitions.
29pub mod triggers;
30/// Shared domain types (messages, steps, usage metadata).
31pub mod types;
32
33// ── Re-exports ──────────────────────────────────────────────────────────────
34// Flat re-exports of the most commonly used types so callers can write
35// `use agy_bridge::{AgentConfig, Error, ToolRegistry, Content};`
36// without diving into sub-modules.
37
38pub use config::{
39 AgentConfig, BuiltinTools, CapabilitiesConfig, GeminiConfig, LocalAgentConfig, McpConfigError,
40 McpConfigFile, McpServer, McpServerSpec, McpSseServer, McpStdioServer, McpStreamableHttpServer,
41 SystemInstructions,
42};
43pub use content::{Audio, Content, ContentPrimitive, Document, Image, Video};
44pub use error::Error;
45pub use hooks::{HookCallback, HookEntry, HookPoint, HookResult, HookSet, Hooks};
46/// Re-export the `#[llm_tool]` proc-macro so users only need `agy_bridge` in
47/// their dependency list.
48pub use llm_tool_macros::llm_tool;
49pub use policies::{AskUserHandler, PolicyDecision, PolicyRule, PolicySet};
50pub use runtime::{BackendLogLevel, RuntimeConfig};
51pub use streaming::{ChatResponseHandle, ChatResult, ResponseEvent, StreamChunk};
52pub use tools::{
53 AvailableTool, RustTool, ToolContext, ToolDefinition, ToolError, ToolOutput, ToolRegistry,
54 ToolSource,
55};
56pub use triggers::{TriggerConfig, TriggerEntry};
57pub use types::{ConversationMessage, MessageRole, Step, UsageMetadata};
58
59/// Convenience prelude — pull in everything you need with a single glob import.
60///
61/// ```
62/// use agy_bridge::prelude::*;
63/// ```
64///
65/// This re-exports the most commonly used types, traits, and macros from the
66/// crate so you can get started quickly without hunting for individual paths.
67pub mod prelude {
68 pub use llm_tool_macros::llm_tool;
69
70 pub use crate::{
71 Agent, AgyBridge,
72 config::{
73 AgentConfig, BuiltinTools, CapabilitiesConfig, GeminiConfig, LocalAgentConfig,
74 McpConfigError, McpConfigFile, McpServer, McpServerSpec, McpSseServer, McpStdioServer,
75 McpStreamableHttpServer, SystemInstructions,
76 },
77 content::{Audio, Content, ContentPrimitive, Document, Image, Video},
78 error::Error,
79 hooks::{HookPoint, HookResult, Hooks},
80 policies::{AskUserHandler, PolicyDecision, PolicyRule, PolicySet},
81 runtime::BackendLogLevel,
82 streaming::{ChatResponseHandle, ChatResult, ResponseEvent, StreamChunk},
83 tools::{
84 AvailableTool, RustTool, ToolContext, ToolDefinition, ToolError, ToolOutput,
85 ToolRegistry, ToolSource,
86 },
87 triggers::{TriggerConfig, TriggerEntry},
88 types::{ConversationMessage, MessageRole, Step, UsageMetadata},
89 };
90}
91
92use std::sync::Arc;
93
94/// Load environment variables from a `.env` file into the process environment.
95///
96/// 1. Walks upward from `CARGO_MANIFEST_DIR` (if set) or the current working
97/// directory to find the nearest `.env` file.
98/// 2. Parses each `KEY=VALUE` line (skipping blanks and `#`-comments).
99/// 3. For every key that is **not** already present in the process
100/// environment, calls [`std::env::set_var`] to inject it.
101/// 4. Returns a [`HashMap`](std::collections::HashMap) of the newly-set
102/// key/value pairs (keys that were already set are omitted).
103///
104/// Results are cached via [`OnceLock`](std::sync::OnceLock) — the file is
105/// read and environment variables are set at most once. Subsequent calls
106/// return a clone of the cached map without re-reading the file or
107/// modifying the environment.
108///
109/// # Safety
110///
111/// This function calls [`std::env::set_var`], which is **not** thread-safe.
112/// It **must** be called during single-threaded startup, before any
113/// additional threads are spawned (including the Tokio runtime). Calling it
114/// after threads exist is undefined behaviour.
115///
116/// # Example
117///
118/// ```
119/// let new_vars = agy_bridge::load_dotenv();
120/// // OnceLock-cached: safe to call multiple times, only loads .env once.
121/// // NOLINT: example code in documentation — `let _ =` demonstrates the return value exists
122/// let _ = new_vars.len();
123/// ```
124pub fn load_dotenv() -> &'static std::collections::HashMap<String, String> {
125 use std::sync::OnceLock;
126
127 static CACHED: OnceLock<std::collections::HashMap<String, String>> = OnceLock::new();
128
129 CACHED.get_or_init(|| {
130 let start = std::env::var_os("CARGO_MANIFEST_DIR").map_or_else(
131 || {
132 std::env::current_dir().unwrap_or_else(|e| {
133 tracing::debug!("load_dotenv: current_dir() failed: {e}, using fallback \".\"");
134 std::path::PathBuf::from(".")
135 })
136 },
137 std::path::PathBuf::from,
138 );
139
140 let mut dir = start.as_path();
141 loop {
142 let candidate = dir.join(".env");
143 if candidate.is_file() {
144 let mut env_map = std::collections::HashMap::new();
145 match std::fs::read_to_string(&candidate) {
146 Ok(contents) => {
147 for line in contents.lines() {
148 if let Some((k, v)) = parse_dotenv_line(line)
149 && std::env::var_os(k).is_none()
150 {
151 // SAFETY: Called inside the OnceLock closure during
152 // single-threaded initialization, before any threads
153 // are spawned. set_var is not thread-safe, but here
154 // we are the only thread.
155 unsafe {
156 std::env::set_var(k, v);
157 }
158 env_map.insert(k.to_owned(), v.to_owned());
159 }
160 }
161 }
162 Err(e) => {
163 tracing::warn!(error = %e, "Failed to read .env file at {}", candidate.display());
164 }
165 }
166 return env_map;
167 }
168 match dir.parent() {
169 Some(parent) => dir = parent,
170 None => return std::collections::HashMap::new(),
171 }
172 }
173 })
174}
175
176/// Parse a single line from a `.env` file.
177///
178/// Returns `Some((key, value))` for valid `KEY=VALUE` lines, stripping
179/// surrounding whitespace and quotes (single or double) from the value.
180/// Returns `None` for blank lines, comments, or lines without `=`.
181///
182/// This is factored out of [`load_dotenv`] for testability.
183pub(crate) fn parse_dotenv_line(line: &str) -> Option<(&str, &str)> {
184 let line = line.trim();
185 if line.is_empty() || line.starts_with('#') {
186 return None;
187 }
188 let (k, v) = line.split_once('=')?;
189 let k = k.trim();
190 if k.is_empty() {
191 return None;
192 }
193 let v = v.trim();
194 // Strip surrounding quotes (single or double)
195 let v = v
196 .strip_prefix('"')
197 .and_then(|s| s.strip_suffix('"'))
198 .or_else(|| v.strip_prefix('\'').and_then(|s| s.strip_suffix('\'')))
199 .unwrap_or(v);
200 Some((k, v))
201}
202
203/// Convenience alias for an agent backed by the bridge's runtime.
204///
205/// This hides the generic `Runtime` parameter so consumers never see the
206/// underlying Python bridge type.
207pub type Agent = agent::AgentHandle<runtime::PythonRuntime>;
208
209/// Primary entry point for the Antigravity bridge.
210///
211/// Wraps the runtime and provides a clean Rust API for creating agents.
212///
213/// # Example
214///
215/// ```rust
216/// # use agy_bridge::AgyBridge;
217/// # use agy_bridge::config::AgentConfig;
218/// # #[tokio::main]
219/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
220/// # agy_bridge::load_dotenv();
221/// // Zero-config:
222/// // let bridge = AgyBridge::builder().build()?;
223///
224/// // With custom settings:
225/// let bridge = AgyBridge::builder().channel_capacity(128).build()?;
226///
227/// // Create an agent (simple):
228/// // let agent = bridge.agent(AgentConfig::default()).await?;
229/// # let manifest_dir = std::path::PathBuf::from(std::env::var("CARGO_MANIFEST_DIR")?);
230/// # let project_root = manifest_dir.parent().unwrap().parent().unwrap();
231/// # let agent = bridge.agent(
232/// # AgentConfig::builder()
233/// # .system_instructions("Reply with 'Hello!' and nothing else. Never use tools.")
234/// # .capabilities(agy_bridge::config::CapabilitiesConfig::custom_tools_only())
235/// # .workspaces(vec![project_root])
236/// # .build()
237/// # ).await?;
238///
239/// // Create an agent with tools and hooks:
240/// // let agent = bridge.agent(config)
241/// // .tools(registry)
242/// // .hooks(hooks)
243/// // .await?;
244///
245/// let answer = agent.chat("Hello!").await?.text().await?;
246/// # Ok(())
247/// # }
248/// ```
249pub struct AgyBridge {
250 runtime: Arc<runtime::PythonRuntime>,
251}
252
253/// Builder for constructing an [`AgyBridge`] instance.
254///
255/// Created via [`AgyBridge::builder()`]. All settings have sensible defaults;
256/// call [`.build()`](Self::build) to finalise.
257///
258/// # Example
259///
260/// ```
261/// # use agy_bridge::AgyBridge;
262/// let bridge = AgyBridge::builder().channel_capacity(128).build()?;
263/// # Ok::<(), agy_bridge::error::Error>(())
264/// ```
265pub struct AgyBridgeBuilder {
266 config: runtime::RuntimeConfig,
267}
268
269impl AgyBridgeBuilder {
270 /// Set the mpsc channel buffer size for the command channel.
271 #[must_use]
272 pub fn channel_capacity(mut self, capacity: usize) -> Self {
273 self.config.channel_capacity = capacity;
274 self
275 }
276
277 /// Set the timeout for joining the Python thread on shutdown.
278 #[must_use]
279 pub fn shutdown_timeout(mut self, timeout: std::time::Duration) -> Self {
280 self.config.shutdown_timeout = timeout;
281 self
282 }
283
284 /// Set the delay between successive chat commands to prevent burst requests.
285 #[must_use]
286 pub fn inter_agent_delay(mut self, delay: std::time::Duration) -> Self {
287 self.config.inter_agent_delay = delay;
288 self
289 }
290
291 /// Set the backend runtime log verbosity.
292 ///
293 /// Defaults to [`BackendLogLevel::Warn`]. Set to [`BackendLogLevel::Info`]
294 /// or [`BackendLogLevel::Debug`] for verbose protocol-level diagnostics.
295 #[must_use]
296 pub fn backend_log_level(mut self, level: runtime::BackendLogLevel) -> Self {
297 self.config.backend_log_level = level;
298 self
299 }
300
301 /// Replace the entire runtime configuration at once.
302 ///
303 /// Useful when you already have a [`RuntimeConfig`] struct. Individual
304 /// setters called *after* this will override the corresponding fields.
305 #[must_use]
306 pub fn runtime_config(mut self, config: runtime::RuntimeConfig) -> Self {
307 self.config = config;
308 self
309 }
310
311 /// Set the maximum number of consecutive model-quality errors before
312 /// aborting a stream. Set to `0` to disable entirely (pure SDK pass-through).
313 ///
314 /// Defaults to `3` — enough to catch deterministically-bad model output
315 /// without cutting off transient hiccups.
316 #[must_use]
317 pub fn max_consecutive_model_errors(mut self, limit: u32) -> Self {
318 self.config.max_consecutive_model_errors = Some(limit);
319 self
320 }
321
322 /// Set the maximum number of consecutive thinking-only/empty steps before
323 /// aborting a stream. Set to `0` to disable entirely (pure SDK pass-through).
324 ///
325 /// Defaults to `500` — a generous ceiling to avoid false positives on
326 /// legitimate long chains of thought.
327 #[must_use]
328 pub fn max_consecutive_empty_steps(mut self, limit: u32) -> Self {
329 self.config.max_consecutive_empty_steps = Some(limit);
330 self
331 }
332
333 /// Set the per-channel buffer size for streaming response channels.
334 ///
335 /// Each chat call creates ~7 channels of this size. Defaults to `256` —
336 /// large enough to avoid backpressure under normal workloads.
337 #[must_use]
338 pub fn streaming_channel_buffer(mut self, size: usize) -> Self {
339 self.config.streaming_channel_buffer = Some(size);
340 self
341 }
342
343 /// Build the [`AgyBridge`], starting the Python runtime.
344 ///
345 /// # Errors
346 ///
347 /// Returns [`error::Error`] if the Python runtime cannot be started
348 /// (e.g. missing Antigravity SDK installation).
349 pub fn build(self) -> Result<AgyBridge, error::Error> {
350 Ok(AgyBridge {
351 runtime: Arc::new(runtime::PythonRuntime::new(self.config)?),
352 })
353 }
354}
355
356impl AgyBridge {
357 /// Create a new builder for configuring and constructing an [`AgyBridge`].
358 ///
359 /// # Example
360 ///
361 /// ```
362 /// # use agy_bridge::AgyBridge;
363 /// let bridge = AgyBridge::builder().build()?;
364 /// # Ok::<(), agy_bridge::error::Error>(())
365 /// ```
366 #[must_use]
367 pub fn builder() -> AgyBridgeBuilder {
368 AgyBridgeBuilder {
369 config: runtime::RuntimeConfig::default(),
370 }
371 }
372
373 /// Begin building a new agent on this bridge.
374 ///
375 /// Returns an [`AgentBuilder`] that can be directly `.await`ed for the
376 /// simple case, or chained with [`.tools()`](AgentBuilder::tools) and
377 /// [`.hooks()`](AgentBuilder::hooks) before awaiting.
378 ///
379 /// # Examples
380 ///
381 /// ```rust
382 /// # use agy_bridge::{AgyBridge, config::AgentConfig};
383 /// # #[tokio::main]
384 /// # async fn main() -> Result<(), agy_bridge::error::Error> {
385 /// # agy_bridge::load_dotenv();
386 /// # let bridge = AgyBridge::builder().build()?;
387 /// // Simple — no tools or hooks:
388 /// let agent = bridge.agent(AgentConfig::default()).await?;
389 ///
390 /// // With tools:
391 /// // let agent = bridge.agent(config).tools(registry).await?;
392 ///
393 /// // With tools and hooks:
394 /// // let agent = bridge.agent(config).tools(registry).hooks(hooks).await?;
395 /// # Ok(())
396 /// # }
397 /// ```
398 #[must_use]
399 pub fn agent(&self, config: config::AgentConfig) -> AgentBuilder<'_> {
400 AgentBuilder {
401 bridge: self,
402 config,
403 registry: None,
404 hooks: None,
405 policy_handler: None,
406 }
407 }
408
409 /// Convenience shorthand for `self.agent(AgentConfig::default())`.
410 ///
411 /// Creates an agent builder with default configuration. Chain
412 /// [`.tools()`](AgentBuilder::tools) or [`.hooks()`](AgentBuilder::hooks)
413 /// before awaiting, or `.await` directly for a bare agent.
414 ///
415 /// # Examples
416 ///
417 /// ```rust
418 /// # use agy_bridge::AgyBridge;
419 /// # #[tokio::main]
420 /// # async fn main() -> Result<(), agy_bridge::error::Error> {
421 /// # agy_bridge::load_dotenv();
422 /// # let bridge = AgyBridge::builder().build()?;
423 /// let agent = bridge.default_agent().await?;
424 /// # Ok(())
425 /// # }
426 /// ```
427 #[must_use]
428 pub fn default_agent(&self) -> AgentBuilder<'_> {
429 self.agent(config::AgentConfig::default())
430 }
431
432 /// Return the number of agents currently live on this bridge.
433 ///
434 /// Counts agents that have been created but not yet shut down or dropped.
435 /// Because a bridge owns a single runtime with a single agent registry,
436 /// this reflects exactly the agents belonging to *this* bridge — it is
437 /// unaffected by agents on other [`AgyBridge`] instances.
438 ///
439 /// Useful for observability and for asserting clean teardown: once every
440 /// agent has been shut down or dropped, the count returns to zero.
441 ///
442 /// # Errors
443 ///
444 /// Returns [`error::Error`] if the runtime thread has exited.
445 pub async fn active_agent_count(&self) -> Result<usize, error::Error> {
446 self.runtime.active_agent_count().await
447 }
448}
449
450/// Builder for creating an [`Agent`] on an [`AgyBridge`].
451///
452/// Obtained from [`AgyBridge::agent()`]. Implements [`IntoFuture`] so you can
453/// `.await` it directly, or chain optional [`.tools()`](Self::tools) /
454/// [`.hooks()`](Self::hooks) calls before awaiting.
455pub struct AgentBuilder<'a> {
456 bridge: &'a AgyBridge,
457 config: config::AgentConfig,
458 registry: Option<tools::ToolRegistry>,
459 hooks: Option<hooks::Hooks>,
460 policy_handler: Option<Arc<dyn policies::AskUserHandler>>,
461}
462
463impl AgentBuilder<'_> {
464 /// Attach a [`ToolRegistry`] containing custom
465 /// Rust tools for the agent.
466 ///
467 /// The registry's tool definitions are automatically merged into the
468 /// agent configuration.
469 ///
470 /// # Errors (at build time)
471 ///
472 /// Returns [`error::Error::InvalidConfig`] if `config.tools` is
473 /// already non-empty — pass tools via the registry **or** via
474 /// `config.tools`, not both.
475 #[must_use]
476 pub fn tools(mut self, registry: tools::ToolRegistry) -> Self {
477 self.registry = Some(registry);
478 self
479 }
480
481 /// Attach [`Hooks`] for lifecycle event
482 /// callbacks (pre/post turn, tool-call gating, etc.).
483 #[must_use]
484 pub fn hooks(mut self, hooks: hooks::Hooks) -> Self {
485 self.hooks = Some(hooks);
486 self
487 }
488
489 /// Attach a custom [`AskUserHandler`] to manage interactive tool-call confirmations.
490 #[must_use]
491 pub fn policy_handler(mut self, handler: impl policies::AskUserHandler + 'static) -> Self {
492 self.policy_handler = Some(Arc::new(handler));
493 self
494 }
495
496 /// Set a pre-existing conversation ID to resume.
497 #[must_use]
498 pub fn conversation_id(mut self, id: impl Into<String>) -> Self {
499 self.config.conversation_id = Some(id.into());
500 self
501 }
502
503 /// Set the model backend (e.g. `"gemini-3.5-flash"`).
504 #[must_use]
505 pub fn model(mut self, model: impl Into<String>) -> Self {
506 self.config.model = model.into();
507 self
508 }
509
510 /// Set system instructions for the agent.
511 #[must_use]
512 pub fn system_instructions(
513 mut self,
514 instructions: impl Into<config::SystemInstructions>,
515 ) -> Self {
516 self.config.system_instructions = Some(instructions.into());
517 self
518 }
519
520 /// Append workspace directories the agent is allowed to access and modify.
521 #[must_use]
522 pub fn workspaces(
523 mut self,
524 workspaces: impl IntoIterator<Item = impl Into<std::path::PathBuf>>,
525 ) -> Self {
526 self.config
527 .workspaces
528 .extend(workspaces.into_iter().map(Into::into));
529 self
530 }
531
532 /// Append policy rules to govern tool execution.
533 #[must_use]
534 pub fn policies(
535 mut self,
536 policies: impl IntoIterator<Item = impl Into<policies::PolicyRule>>,
537 ) -> Self {
538 self.config
539 .policies
540 .extend(policies.into_iter().map(Into::into));
541 self
542 }
543
544 /// Append triggers that autonomously wake the agent.
545 #[must_use]
546 pub fn triggers(
547 mut self,
548 triggers: impl IntoIterator<Item = impl Into<triggers::TriggerEntry>>,
549 ) -> Self {
550 self.config
551 .triggers
552 .extend(triggers.into_iter().map(Into::into));
553 self
554 }
555
556 /// Append MCP servers for the agent.
557 #[must_use]
558 pub fn mcp_servers(
559 mut self,
560 servers: impl IntoIterator<Item = impl Into<config::McpServer>>,
561 ) -> Self {
562 self.config
563 .mcp_servers
564 .extend(servers.into_iter().map(Into::into));
565 self
566 }
567
568 /// Append paths for agent skills.
569 #[must_use]
570 pub fn skills(
571 mut self,
572 skills: impl IntoIterator<Item = impl Into<std::path::PathBuf>>,
573 ) -> Self {
574 self.config
575 .skills
576 .extend(skills.into_iter().map(Into::into));
577 self
578 }
579
580 /// Validate configuration and create the agent.
581 ///
582 /// Prefer using `.await` directly on the builder (via [`IntoFuture`])
583 /// instead of calling this method explicitly.
584 ///
585 /// # Errors
586 ///
587 /// Returns [`error::Error::InvalidConfig`] if:
588 /// - `config.tools` is non-empty **and** a `ToolRegistry` was provided.
589 /// - The capabilities configuration is self-contradictory (e.g. both
590 /// `enabled_tools` and `disabled_tools` specified).
591 ///
592 /// Returns other [`error::Error`] variants if agent creation fails.
593 pub async fn build(mut self) -> Result<Agent, error::Error> {
594 // Validate capabilities.
595 if let Some(ref caps) = self.config.capabilities {
596 caps.validate().map_err(|msg| error::Error::InvalidConfig {
597 message: msg.to_string(),
598 })?;
599 }
600
601 // Handle tool registry.
602 let arc_registry = if let Some(registry) = self.registry {
603 if !self.config.tools.is_empty() {
604 return Err(error::Error::InvalidConfig {
605 message: "config.tools is non-empty and a ToolRegistry was also provided; \
606 pass tools via the registry or via config.tools, not both"
607 .to_string(),
608 });
609 }
610 self.config.tools = registry.definitions();
611 Some(Arc::new(registry))
612 } else {
613 None
614 };
615
616 // Handle hooks.
617 let arc_hooks = if let Some(hooks) = self.hooks {
618 if !self.config.hooks.is_empty() {
619 return Err(error::Error::InvalidConfig {
620 message: "config.hooks is non-empty and a Hooks instance was also provided; \
621 configure hooks via Hooks or config.hooks, not both"
622 .to_string(),
623 });
624 }
625 self.config.hooks = hooks.entries();
626 Some(Arc::new(hooks))
627 } else {
628 None
629 };
630
631 // Handle policy handler.
632 let arc_policy = self.policy_handler;
633
634 agent::AgentHandle::new(
635 Arc::clone(&self.bridge.runtime),
636 self.config,
637 arc_registry,
638 arc_hooks,
639 arc_policy,
640 )
641 .await
642 }
643}
644
645impl<'a> std::future::IntoFuture for AgentBuilder<'a> {
646 type Output = Result<Agent, error::Error>;
647 type IntoFuture =
648 std::pin::Pin<Box<dyn std::future::Future<Output = Self::Output> + Send + 'a>>;
649
650 fn into_future(self) -> Self::IntoFuture {
651 Box::pin(self.build())
652 }
653}
654
655#[cfg(test)]
656mod tests {
657 use super::*;
658
659 // ── parse_dotenv_line regression tests ────────────────────────────
660
661 #[test]
662 fn dotenv_strips_double_quotes() {
663 let (k, v) = parse_dotenv_line(r#"API_KEY="my-secret""#).unwrap();
664 assert_eq!(k, "API_KEY");
665 assert_eq!(v, "my-secret");
666 }
667
668 #[test]
669 fn dotenv_strips_single_quotes() {
670 let (k, v) = parse_dotenv_line("TOKEN='abc123'").unwrap();
671 assert_eq!(k, "TOKEN");
672 assert_eq!(v, "abc123");
673 }
674
675 #[test]
676 fn dotenv_unquoted_value_unchanged() {
677 let (k, v) = parse_dotenv_line("FOO=bar").unwrap();
678 assert_eq!(k, "FOO");
679 assert_eq!(v, "bar");
680 }
681
682 #[test]
683 fn dotenv_mismatched_quotes_preserved() {
684 // Opening double quote but closing single quote → not stripped.
685 let (k, v) = parse_dotenv_line(r#"KEY="value'"#).unwrap();
686 assert_eq!(k, "KEY");
687 assert_eq!(v, r#""value'"#);
688 }
689
690 #[test]
691 fn dotenv_empty_quoted_value() {
692 let (k, v) = parse_dotenv_line(r#"EMPTY="""#).unwrap();
693 assert_eq!(k, "EMPTY");
694 assert_eq!(v, "");
695 }
696
697 #[test]
698 fn dotenv_whitespace_around_key_value() {
699 let (k, v) = parse_dotenv_line(" MY_VAR = \"hello world\" ").unwrap();
700 assert_eq!(k, "MY_VAR");
701 assert_eq!(v, "hello world");
702 }
703
704 #[test]
705 fn dotenv_comment_line_is_none() {
706 assert!(parse_dotenv_line("# this is a comment").is_none());
707 }
708
709 #[test]
710 fn dotenv_blank_line_is_none() {
711 assert!(parse_dotenv_line(" ").is_none());
712 }
713
714 #[test]
715 fn dotenv_empty_key_is_none() {
716 assert!(parse_dotenv_line("=value").is_none());
717 }
718
719 #[test]
720 fn dotenv_no_equals_is_none() {
721 assert!(parse_dotenv_line("JUSTKEY").is_none());
722 }
723
724 #[test]
725 fn dotenv_value_with_internal_equals() {
726 let (k, v) = parse_dotenv_line("DSN=postgres://host:5432/db?opt=1").unwrap();
727 assert_eq!(k, "DSN");
728 assert_eq!(v, "postgres://host:5432/db?opt=1");
729 }
730
731 #[test]
732 fn dotenv_value_with_embedded_quotes_not_stripped() {
733 // Quotes in the middle are not stripped — only surrounding ones.
734 let (k, v) = parse_dotenv_line(r#"MSG=say "hello""#).unwrap();
735 assert_eq!(k, "MSG");
736 assert_eq!(v, r#"say "hello""#);
737 }
738
739 #[test]
740 fn test_load_dotenv_returns_static_reference_identity() {
741 let map1 = load_dotenv();
742 let map2 = load_dotenv();
743 assert!(std::ptr::eq(map1, map2));
744 }
745}