sqry-core 6.0.22

Core library for sqry - semantic code search engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
//! Test verbosity configuration and logging setup
//!
//! This module provides utilities for enabling verbose logging in tests.
//! It's designed to be opt-in via environment variables and never panic,
//! ensuring test failures are never caused by logging configuration issues.
//!
//! # Usage
//!
//! ## Unit Tests
//!
//! ```rust,ignore
//! #[cfg(test)]
//! mod tests {
//!     use sqry_core::test_support::verbosity;
//!     use std::sync::Once;
//!
//!     static INIT: Once = Once::new();
//!
//!     fn init_logging() {
//!         INIT.call_once(|| {
//!             verbosity::init(env!("CARGO_PKG_NAME"));
//!         });
//!     }
//!
//!     #[test]
//!     fn my_test() {
//!         init_logging();
//!         log::info!("Test with verbose logging");
//!         // test body...
//!     }
//! }
//! ```
//!
//! ## Integration Tests
//!
//! ```rust,ignore
//! // tests/integration_test.rs
//! use sqry_core::test_support::verbosity;
//! use std::sync::Once;
//!
//! static INIT: Once = Once::new();
//!
//! fn init_logging() {
//!     INIT.call_once(|| {
//!         verbosity::init(env!("CARGO_PKG_NAME"));
//!     });
//! }
//!
//! #[test]
//! fn integration_test() {
//!     init_logging();
//!     log::info!("Integration test with verbose logging");
//!     // test body...
//! }
//! ```
//!
//! # Environment Variables
//!
//! - `SQRY_TEST_VERBOSE`: Enable verbose logging. Accepts:
//!   - `all`: Enable for all crates
//!   - Comma-separated list: `core,cli,plugin`
//!   - Specific crate name: `sqry-core`
//! - `SQRY_TEST_VERBOSE_LEVEL`: Log level override (`trace`, `debug`, `info`, `warn`, `error`)
//! - `SQRY_TEST_VERBOSE_ARTIFACTS`: Enable log file artifacts (creates files in `target/test-artifacts/`)
//!
//! # Examples
//!
//! ```bash
//! # Enable verbose logging for all tests
//! SQRY_TEST_VERBOSE=all cargo test
//!
//! # Enable for specific crates
//! SQRY_TEST_VERBOSE=core,cli cargo test
//!
//! # Enable with trace level
//! SQRY_TEST_VERBOSE=all SQRY_TEST_VERBOSE_LEVEL=trace cargo test
//!
//! # Enable with artifact files
//! SQRY_TEST_VERBOSE=all SQRY_TEST_VERBOSE_ARTIFACTS=1 cargo test
//! ```

use std::env;
use std::sync::atomic::{AtomicBool, Ordering};

/// Global flag to track if logging has been initialized
static INITIALIZED: AtomicBool = AtomicBool::new(false);

/// Initialize test logging for a specific crate
///
/// This function is idempotent and will only initialize logging once per process.
/// It reads environment variables to determine verbosity settings and never panics.
///
/// # Arguments
///
/// * `crate_name` - The name of the crate (typically `env!("CARGO_PKG_NAME")`)
///
/// # Error Handling
///
/// This function NEVER panics. All errors are logged to stderr and execution continues:
/// - Logger already initialized: Silently continues
/// - Invalid environment variable values: Logs warning and continues
/// - Artifact directory creation fails: Logs warning and continues without artifacts
///
/// # Examples
///
/// ```rust,ignore
/// // In test module
/// sqry_core::test_support::verbosity::init(env!("CARGO_PKG_NAME"));
/// ```
pub fn init(crate_name: &str) {
    // Check if already initialized (fast path - no allocation)
    if INITIALIZED.load(Ordering::Relaxed) {
        return;
    }

    // Check if logging should be enabled for this crate
    if !should_enable(crate_name) {
        return;
    }

    // Try to set initialized flag (atomic compare-and-swap)
    if INITIALIZED
        .compare_exchange(false, true, Ordering::SeqCst, Ordering::Relaxed)
        .is_err()
    {
        // Another thread beat us to initialization
        return;
    }

    // Configure env_logger builder
    let mut builder = env_logger::Builder::from_default_env();

    // Determine log level and apply it (only if RUST_LOG is not set)
    // If RUST_LOG is set, env_logger has already configured filters from it
    let level = determine_level();
    if env::var("RUST_LOG").is_err() {
        // RUST_LOG not set - apply our default level
        builder.filter_level(level);
    }
    // If RUST_LOG is set, we don't call filter_level() to preserve user's configuration

    // Set test mode
    builder.is_test(true);

    // Configure artifact writer if requested
    if env::var("SQRY_TEST_VERBOSE_ARTIFACTS").is_ok() {
        if let Some(writer) = super::artifacts::maybe_writer(crate_name) {
            builder.target(env_logger::Target::Pipe(Box::new(writer)));
        } else {
            // Failed to create artifact writer - log warning but continue
            eprintln!(
                "Warning: Failed to create artifact writer for {crate_name}. Continuing without artifacts."
            );
        }
    }

    // Try to initialize logger
    match builder.try_init() {
        Ok(()) => {
            log::info!("sqry test verbose logging enabled for {crate_name} (level: {level})");
        }
        Err(e) => {
            // Logger already initialized (e.g., by another test module)
            // This is expected in some scenarios - just log to stderr
            eprintln!("Info: Test logging already initialized for {crate_name}: {e}");
        }
    }

    // NO PANICS - always returns normally
}

/// Check if verbose logging should be enabled for the given crate
///
/// Reads `SQRY_TEST_VERBOSE` environment variable and matches against:
/// - `all`: Matches any crate
/// - Comma-separated list: Matches if crate name (or short name) is in list
/// - Empty/unset: Returns false
///
/// # Examples
///
/// ```rust,ignore
/// // SQRY_TEST_VERBOSE=all
/// assert!(should_enable("sqry-core")); // true
///
/// // SQRY_TEST_VERBOSE=core,cli
/// assert!(should_enable("sqry-core"));  // true
/// assert!(!should_enable("sqry-plugin")); // false
///
/// // SQRY_TEST_VERBOSE not set
/// assert!(!should_enable("sqry-core")); // false
/// ```
pub fn should_enable(crate_name: &str) -> bool {
    let Ok(verbose) = env::var("SQRY_TEST_VERBOSE") else {
        return false;
    };

    if verbose.trim().is_empty() {
        return false;
    }

    // Handle "all" case
    if verbose.trim().eq_ignore_ascii_case("all") {
        return true;
    }

    // Extract short name from crate name (sqry-core -> core)
    let short_name = crate_name.strip_prefix("sqry-").unwrap_or(crate_name);

    // Check comma-separated list
    verbose.split(',').map(str::trim).any(|target| {
        target.eq_ignore_ascii_case(crate_name) || target.eq_ignore_ascii_case(short_name)
    })
}

/// Determine the log level from environment variables
///
/// Checks (in order):
/// 1. `RUST_LOG` (if set, use its level)
/// 2. `SQRY_TEST_VERBOSE_LEVEL` (override level)
/// 3. Default to `info`
///
/// # Supported Values
///
/// - `trace`, `debug`, `info`, `warn`, `error`, `off`
/// - Case-insensitive
///
/// # Error Handling
///
/// Invalid values log a warning and default to `info`.
#[must_use]
pub fn determine_level() -> log::LevelFilter {
    // If RUST_LOG is set, respect it (don't override explicit user configuration)
    if env::var("RUST_LOG").is_ok() {
        // env_logger will parse RUST_LOG, so we just return a permissive filter
        return log::LevelFilter::Trace;
    }

    // Check for explicit level override
    let Ok(level_str) = env::var("SQRY_TEST_VERBOSE_LEVEL") else {
        return log::LevelFilter::Info;
    };

    // Parse level string
    match level_str.trim().to_lowercase().as_str() {
        "trace" => log::LevelFilter::Trace,
        "debug" => log::LevelFilter::Debug,
        "info" => log::LevelFilter::Info,
        "warn" => log::LevelFilter::Warn,
        "error" => log::LevelFilter::Error,
        "off" => log::LevelFilter::Off,
        invalid => {
            eprintln!(
                "Warning: Invalid SQRY_TEST_VERBOSE_LEVEL '{invalid}'. Valid values: trace, debug, info, warn, error, off. Defaulting to 'info'."
            );
            log::LevelFilter::Info
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::env;
    use std::sync::Mutex;

    // Mutex to ensure environment variable tests don't run concurrently
    static ENV_MUTEX: Mutex<()> = Mutex::new(());

    #[test]
    fn test_should_enable_with_all() {
        let _lock = ENV_MUTEX.lock().unwrap();
        unsafe {
            env::set_var("SQRY_TEST_VERBOSE", "all");
        }
        assert!(should_enable("sqry-core"));
        assert!(should_enable("sqry-cli"));
        assert!(should_enable("any-crate"));
        unsafe {
            env::remove_var("SQRY_TEST_VERBOSE");
        }
    }

    #[test]
    fn test_should_enable_with_comma_list() {
        let _lock = ENV_MUTEX.lock().unwrap();
        unsafe {
            env::set_var("SQRY_TEST_VERBOSE", "core,cli");
        }

        // Should match full name
        assert!(should_enable("sqry-core"));
        assert!(should_enable("sqry-cli"));

        // Should not match other crates
        assert!(!should_enable("sqry-plugin"));
        assert!(!should_enable("sqry-mcp"));

        unsafe {
            env::remove_var("SQRY_TEST_VERBOSE");
        }
    }

    #[test]
    fn test_should_enable_with_short_names() {
        let _lock = ENV_MUTEX.lock().unwrap();
        unsafe {
            env::set_var("SQRY_TEST_VERBOSE", "core");
        }

        // Should match both full and short name
        assert!(should_enable("sqry-core"));

        unsafe {
            env::remove_var("SQRY_TEST_VERBOSE");
        }
    }

    #[test]
    fn test_should_enable_case_insensitive() {
        let _lock = ENV_MUTEX.lock().unwrap();
        unsafe {
            env::set_var("SQRY_TEST_VERBOSE", "CORE,CLI");
        }
        assert!(should_enable("sqry-core"));
        assert!(should_enable("sqry-cli"));
        unsafe {
            env::remove_var("SQRY_TEST_VERBOSE");
        }
    }

    #[test]
    fn test_should_enable_disabled_by_default() {
        let _lock = ENV_MUTEX.lock().unwrap();
        unsafe {
            env::remove_var("SQRY_TEST_VERBOSE");
        }
        assert!(!should_enable("sqry-core"));
    }

    #[test]
    fn test_should_enable_with_whitespace() {
        let _lock = ENV_MUTEX.lock().unwrap();
        unsafe {
            env::set_var("SQRY_TEST_VERBOSE", " core , cli ");
        }
        assert!(should_enable("sqry-core"));
        assert!(should_enable("sqry-cli"));
        unsafe {
            env::remove_var("SQRY_TEST_VERBOSE");
        }
    }

    #[test]
    fn test_determine_level_defaults_to_info() {
        let _lock = ENV_MUTEX.lock().unwrap();
        unsafe {
            env::remove_var("RUST_LOG");
        }
        unsafe {
            env::remove_var("SQRY_TEST_VERBOSE_LEVEL");
        }
        assert_eq!(determine_level(), log::LevelFilter::Info);
    }

    #[test]
    fn test_determine_level_respects_rust_log() {
        let _lock = ENV_MUTEX.lock().unwrap();
        unsafe {
            env::set_var("RUST_LOG", "debug");
        }
        // Should return Trace to allow env_logger to parse RUST_LOG
        assert_eq!(determine_level(), log::LevelFilter::Trace);
        unsafe {
            env::remove_var("RUST_LOG");
        }
    }

    #[test]
    fn test_determine_level_with_override() {
        let _lock = ENV_MUTEX.lock().unwrap();
        unsafe {
            env::remove_var("RUST_LOG");
        }

        unsafe {
            env::set_var("SQRY_TEST_VERBOSE_LEVEL", "trace");
        }
        assert_eq!(determine_level(), log::LevelFilter::Trace);

        unsafe {
            env::set_var("SQRY_TEST_VERBOSE_LEVEL", "debug");
        }
        assert_eq!(determine_level(), log::LevelFilter::Debug);

        unsafe {
            env::set_var("SQRY_TEST_VERBOSE_LEVEL", "warn");
        }
        assert_eq!(determine_level(), log::LevelFilter::Warn);

        unsafe {
            env::set_var("SQRY_TEST_VERBOSE_LEVEL", "error");
        }
        assert_eq!(determine_level(), log::LevelFilter::Error);

        unsafe {
            env::set_var("SQRY_TEST_VERBOSE_LEVEL", "off");
        }
        assert_eq!(determine_level(), log::LevelFilter::Off);

        unsafe {
            env::remove_var("SQRY_TEST_VERBOSE_LEVEL");
        }
    }

    #[test]
    fn test_determine_level_case_insensitive() {
        let _lock = ENV_MUTEX.lock().unwrap();
        unsafe {
            env::remove_var("RUST_LOG");
        }

        unsafe {
            env::set_var("SQRY_TEST_VERBOSE_LEVEL", "DEBUG");
        }
        assert_eq!(determine_level(), log::LevelFilter::Debug);

        unsafe {
            env::set_var("SQRY_TEST_VERBOSE_LEVEL", "TrAcE");
        }
        assert_eq!(determine_level(), log::LevelFilter::Trace);

        unsafe {
            env::remove_var("SQRY_TEST_VERBOSE_LEVEL");
        }
    }

    #[test]
    fn test_determine_level_invalid_value_defaults_to_info() {
        let _lock = ENV_MUTEX.lock().unwrap();
        unsafe {
            env::remove_var("RUST_LOG");
        }
        unsafe {
            env::set_var("SQRY_TEST_VERBOSE_LEVEL", "invalid");
        }
        assert_eq!(determine_level(), log::LevelFilter::Info);
        unsafe {
            env::remove_var("SQRY_TEST_VERBOSE_LEVEL");
        }
    }

    #[test]
    fn test_init_is_idempotent() {
        let _lock = ENV_MUTEX.lock().unwrap();
        unsafe {
            env::set_var("SQRY_TEST_VERBOSE", "all");
        }

        // First call should succeed
        init("test-crate");

        // Second call should not panic
        init("test-crate");
        init("test-crate");

        unsafe {
            env::remove_var("SQRY_TEST_VERBOSE");
        }
    }

    #[test]
    fn test_init_with_invalid_crate_does_not_panic() {
        let _lock = ENV_MUTEX.lock().unwrap();
        unsafe {
            env::set_var("SQRY_TEST_VERBOSE", "other-crate");
        }

        // Should not panic even with non-matching crate
        init("sqry-core");

        unsafe {
            env::remove_var("SQRY_TEST_VERBOSE");
        }
    }
}