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
//! Progress tracking for indexing operations
//!
//! Provides real-time progress feedback during scan and indexing operations
//! with smart TTY detection and throttling to avoid output flooding.
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Mutex;
use std::time::{Duration, Instant};
/// Output mode for progress tracking
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutputMode {
/// Minimal, compact output (default)
Minimal,
/// Detailed, verbose output
Verbose,
/// JSON output for programmatic consumption (VSCode extension)
Json,
}
/// Tracks and displays progress for indexing operations
///
/// Thread-safe progress tracker that can be shared across threads.
/// Uses atomic counters for file/chunk counts and throttling to
/// prevent output flooding.
pub struct ProgressTracker {
mode: OutputMode,
is_tty: bool,
start_time: Instant,
total_files: Mutex<Option<usize>>,
total_chunks: Mutex<Option<usize>>,
processed_files: AtomicUsize,
processed_chunks: AtomicUsize,
last_update: Mutex<Option<Instant>>,
last_percentage: AtomicUsize,
}
impl ProgressTracker {
/// Create a new progress tracker
///
/// # Arguments
/// * `mode` - Output mode (Minimal or Verbose)
///
/// # Examples
/// ```
/// use maproom::progress::{ProgressTracker, OutputMode};
///
/// let tracker = ProgressTracker::new(OutputMode::Minimal);
/// ```
pub fn new(mode: OutputMode) -> Self {
// Detect if stdout is a TTY
let is_tty = atty::is(atty::Stream::Stdout);
Self {
mode,
is_tty,
start_time: Instant::now(),
total_files: Mutex::new(None),
total_chunks: Mutex::new(None),
processed_files: AtomicUsize::new(0),
processed_chunks: AtomicUsize::new(0),
last_update: Mutex::new(None),
last_percentage: AtomicUsize::new(0),
}
}
/// Set total file and chunk counts
///
/// # Arguments
/// * `files` - Total number of files to process
/// * `chunks` - Optional total number of chunks (embeddings)
pub fn set_totals(&self, files: usize, chunks: Option<usize>) {
if let Ok(mut total_files) = self.total_files.lock() {
*total_files = Some(files);
}
if let Ok(mut total_chunks) = self.total_chunks.lock() {
*total_chunks = chunks;
}
}
/// Update the count of processed files
///
/// # Arguments
/// * `count` - New count of processed files
pub fn update_files(&self, count: usize) {
self.processed_files.store(count, Ordering::Relaxed);
}
/// Update the count of processed chunks
///
/// # Arguments
/// * `count` - New count of processed chunks
pub fn update_chunks(&self, count: usize) {
self.processed_chunks.store(count, Ordering::Relaxed);
}
/// Check if progress should be printed
///
/// Returns true if more than 200ms has elapsed since last print,
/// preventing output flooding.
///
/// The first call always returns true to allow initial progress display.
pub fn should_print(&self) -> bool {
if let Ok(mut last) = self.last_update.lock() {
let now = Instant::now();
match *last {
None => {
// First call - allow print
*last = Some(now);
true
}
Some(last_time) => {
// Subsequent calls - check throttle
if now.duration_since(last_time) > Duration::from_millis(200) {
*last = Some(now);
true
} else {
false
}
}
}
} else {
false
}
}
/// Print current progress
///
/// Format depends on TTY status and output mode:
/// - Json: Outputs NDJSON progress events
/// - TTY: Overwrites line with \r
/// - Non-TTY: Prints new line every 10% progress
pub fn print_progress(&self) {
let files_processed = self.processed_files.load(Ordering::Relaxed);
let chunks_processed = self.processed_chunks.load(Ordering::Relaxed);
let total_files = self.total_files.lock().ok().and_then(|t| *t);
let total_chunks = self.total_chunks.lock().ok().and_then(|t| *t);
// JSON mode: emit progress event
if self.mode == OutputMode::Json {
if let Some(total) = total_files {
let elapsed = self.start_time.elapsed().as_millis() as u64;
let percent = if total > 0 {
(files_processed as f64 / total as f64) * 100.0
} else {
0.0
};
// Emit JSON progress event
println!(
r#"{{"type":"progress","files":{},"complete":{},"percent":{:.1},"elapsed":{}}}"#,
total, files_processed, percent, elapsed
);
}
return;
}
if self.is_tty {
// TTY mode: overwrite line
let mut output = String::new();
if let Some(total) = total_files {
if total > 0 {
let pct = self.percentage_files();
output.push_str(&format!(
"Processing: {}/{} files ({}%)",
files_processed, total, pct
));
}
}
if let Some(total) = total_chunks {
if total > 0 {
let pct = self.percentage_chunks();
if !output.is_empty() {
output.push_str(" | ");
}
output.push_str(&format!(
"Embeddings: {}/{} ({}%)",
chunks_processed, total, pct
));
}
}
if !output.is_empty() {
print!("\r{}", output);
// Flush to ensure immediate display
use std::io::Write;
let _ = std::io::stdout().flush();
}
} else {
// Non-TTY mode: print every 10% progress
let current_pct = self.percentage_files();
let last_pct = self.last_percentage.load(Ordering::Relaxed);
if current_pct >= last_pct + 10 {
self.last_percentage.store(current_pct, Ordering::Relaxed);
if let Some(total) = total_files {
if total > 0 {
println!(
"Progress: {}% complete ({}/{} files)",
current_pct, files_processed, total
);
}
}
}
}
}
/// Print final timing summary
///
/// Prints completion message with total elapsed time.
/// In JSON mode, emits a complete event.
pub fn finish(&self) {
let elapsed = self.start_time.elapsed();
let total_files = self.total_files.lock().ok().and_then(|t| *t).unwrap_or(0);
// JSON mode: emit complete event
if self.mode == OutputMode::Json {
let duration_ms = elapsed.as_millis() as u64;
let timestamp = chrono::Utc::now().to_rfc3339();
println!(
r#"{{"type":"complete","files":{},"duration":{},"elapsed":{},"timestamp":"{}"}}"#,
total_files, duration_ms, duration_ms, timestamp
);
return;
}
if self.is_tty {
// Clear the progress line
print!("\r");
use std::io::Write;
let _ = std::io::stdout().flush();
}
println!("\n✅ Completed in {:.1}s", elapsed.as_secs_f64());
}
/// Calculate percentage of files processed
fn percentage_files(&self) -> usize {
if let Ok(total_files) = self.total_files.lock() {
if let Some(total) = *total_files {
if total > 0 {
let processed = self.processed_files.load(Ordering::Relaxed);
return (processed * 100) / total;
}
}
}
0
}
/// Calculate percentage of chunks processed
fn percentage_chunks(&self) -> usize {
if let Ok(total_chunks) = self.total_chunks.lock() {
if let Some(total) = *total_chunks {
if total > 0 {
let processed = self.processed_chunks.load(Ordering::Relaxed);
return (processed * 100) / total;
}
}
}
0
}
/// Get the current count of processed files
///
/// Returns the number of files that have been processed so far.
/// This can be used for statistics collection after scanning completes.
///
/// # Example
/// ```
/// use maproom::progress::{ProgressTracker, OutputMode};
///
/// let tracker = ProgressTracker::new(OutputMode::Minimal);
/// tracker.update_files(42);
/// assert_eq!(tracker.files_processed(), 42);
/// ```
pub fn files_processed(&self) -> usize {
self.processed_files.load(Ordering::Relaxed)
}
/// Get the current count of processed chunks
///
/// Returns the number of code chunks that have been processed so far.
/// This can be used for statistics collection after scanning completes.
///
/// # Example
/// ```
/// use maproom::progress::{ProgressTracker, OutputMode};
///
/// let tracker = ProgressTracker::new(OutputMode::Minimal);
/// tracker.update_chunks(100);
/// assert_eq!(tracker.chunks_processed(), 100);
/// ```
pub fn chunks_processed(&self) -> usize {
self.processed_chunks.load(Ordering::Relaxed)
}
/// Check if the tracker is in JSON output mode
///
/// Returns true if the tracker was created with OutputMode::Json,
/// which is used by the VSCode extension for programmatic consumption.
///
/// # Example
/// ```
/// use maproom::progress::{ProgressTracker, OutputMode};
///
/// let json_tracker = ProgressTracker::new(OutputMode::Json);
/// assert!(json_tracker.is_json_mode());
///
/// let normal_tracker = ProgressTracker::new(OutputMode::Minimal);
/// assert!(!normal_tracker.is_json_mode());
/// ```
pub fn is_json_mode(&self) -> bool {
self.mode == OutputMode::Json
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
use std::thread;
#[test]
fn test_new_creates_tracker() {
let tracker = ProgressTracker::new(OutputMode::Minimal);
assert_eq!(tracker.mode, OutputMode::Minimal);
assert_eq!(tracker.processed_files.load(Ordering::Relaxed), 0);
assert_eq!(tracker.processed_chunks.load(Ordering::Relaxed), 0);
}
#[test]
fn test_percentage_calculation() {
let tracker = ProgressTracker::new(OutputMode::Minimal);
tracker.set_totals(100, None);
tracker.update_files(50);
assert_eq!(tracker.percentage_files(), 50);
tracker.update_files(75);
assert_eq!(tracker.percentage_files(), 75);
}
#[test]
fn test_percentage_calculation_edge_cases() {
let tracker = ProgressTracker::new(OutputMode::Minimal);
// Test with 1 file
tracker.set_totals(1, None);
tracker.update_files(1);
assert_eq!(tracker.percentage_files(), 100);
// Test with large numbers
tracker.set_totals(10000, None);
tracker.update_files(3750);
assert_eq!(tracker.percentage_files(), 37);
}
#[test]
fn test_zero_total_safe() {
let tracker = ProgressTracker::new(OutputMode::Minimal);
tracker.set_totals(0, None);
// Should not panic
assert_eq!(tracker.percentage_files(), 0);
}
#[test]
fn test_throttling() {
let tracker = ProgressTracker::new(OutputMode::Minimal);
// First call should return true
let first = tracker.should_print();
assert!(first, "First call to should_print() should return true");
// Immediate second call should return false (throttled)
let second = tracker.should_print();
assert!(!second, "Second immediate call should be throttled");
// Sleep to exceed throttle threshold
std::thread::sleep(Duration::from_millis(300));
// Should allow print now
let third = tracker.should_print();
assert!(
third,
"After sleep, should_print() should return true again"
);
}
#[test]
fn test_throttling_timing() {
let tracker = ProgressTracker::new(OutputMode::Minimal);
// Reset by calling once
tracker.should_print();
// Should be throttled
assert!(!tracker.should_print());
// Wait 250ms (> 200ms threshold)
std::thread::sleep(Duration::from_millis(250));
// Should allow print now
assert!(tracker.should_print());
}
#[test]
fn test_concurrent_updates() {
let tracker = Arc::new(ProgressTracker::new(OutputMode::Minimal));
tracker.set_totals(1000, None);
let handles: Vec<_> = (0..10)
.map(|_| {
let t = Arc::clone(&tracker);
thread::spawn(move || {
for i in 0..100 {
t.update_files((i + 1) * 10);
}
})
})
.collect();
for handle in handles {
handle.join().unwrap();
}
// All threads completed - verify tracker is in valid state
let final_count = tracker.processed_files.load(Ordering::Relaxed);
assert!(final_count <= 1000);
}
#[test]
fn test_output_mode_minimal() {
let tracker = ProgressTracker::new(OutputMode::Minimal);
assert_eq!(tracker.mode, OutputMode::Minimal);
}
#[test]
fn test_output_mode_verbose() {
let tracker = ProgressTracker::new(OutputMode::Verbose);
assert_eq!(tracker.mode, OutputMode::Verbose);
}
#[test]
fn test_set_totals_updates() {
let tracker = ProgressTracker::new(OutputMode::Minimal);
tracker.set_totals(100, Some(500));
{
let files = tracker.total_files.lock().unwrap();
assert_eq!(*files, Some(100));
}
{
let chunks = tracker.total_chunks.lock().unwrap();
assert_eq!(*chunks, Some(500));
}
}
#[test]
fn test_chunks_percentage() {
let tracker = ProgressTracker::new(OutputMode::Minimal);
tracker.set_totals(100, Some(1000));
tracker.update_chunks(250);
assert_eq!(tracker.percentage_chunks(), 25);
}
}