yek 0.25.5

A tool to serialize a repository into chunks of text files
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
use std::{
    fmt, io,
    path::{Path, PathBuf},
};

/// Custom error types for better error handling and user feedback
#[derive(Debug)]
pub enum YekError {
    /// File system related errors
    FileSystem {
        operation: String,
        path: PathBuf,
        source: io::Error,
    },

    /// Git operation errors
    Git {
        operation: String,
        repository: PathBuf,
        source: git2::Error,
    },

    /// Configuration errors
    Configuration {
        field: String,
        value: String,
        reason: String,
    },

    /// Processing errors
    Processing {
        stage: String,
        file: Option<PathBuf>,
        reason: String,
    },

    /// Memory errors
    Memory {
        operation: String,
        requested: usize,
        available: Option<usize>,
    },

    /// Path traversal/security errors
    Security {
        violation: String,
        path: PathBuf,
        attempted_by: String,
    },

    /// Validation errors
    Validation {
        field: String,
        value: String,
        constraint: String,
    },

    /// Tokenization errors
    Tokenization {
        content_type: String,
        size: usize,
        reason: String,
    },

    /// User input errors
    UserInput {
        input_type: String,
        value: String,
        suggestion: String,
    },
}

impl fmt::Display for YekError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            YekError::FileSystem {
                operation,
                path,
                source,
            } => {
                write!(
                    f,
                    "File system error during '{}' on '{}': {}",
                    operation,
                    path.display(),
                    source
                )
            }
            YekError::Git {
                operation,
                repository,
                source,
            } => {
                write!(
                    f,
                    "Git error during '{}' in repository '{}': {}",
                    operation,
                    repository.display(),
                    source
                )
            }
            YekError::Configuration {
                field,
                value,
                reason,
            } => {
                write!(
                    f,
                    "Configuration error for field '{}' with value '{}': {}",
                    field, value, reason
                )
            }
            YekError::Processing {
                stage,
                file,
                reason,
            } => {
                if let Some(file_path) = file {
                    write!(
                        f,
                        "Processing error in stage '{}' for file '{}': {}",
                        stage,
                        file_path.display(),
                        reason
                    )
                } else {
                    write!(f, "Processing error in stage '{}': {}", stage, reason)
                }
            }
            YekError::Memory {
                operation,
                requested,
                available,
            } => match available {
                Some(avail) => write!(
                    f,
                    "Memory error during '{}' - requested: {} bytes, available: {} bytes",
                    operation, requested, avail
                ),
                None => write!(
                    f,
                    "Memory error during '{}' - requested: {} bytes",
                    operation, requested
                ),
            },
            YekError::Security {
                violation,
                path,
                attempted_by,
            } => {
                write!(
                    f,
                    "Security violation '{}' for path '{}' attempted by: {}",
                    violation,
                    path.display(),
                    attempted_by
                )
            }
            YekError::Validation {
                field,
                value,
                constraint,
            } => {
                write!(
                    f,
                    "Validation error for field '{}' with value '{}': violates constraint '{}'",
                    field, value, constraint
                )
            }
            YekError::Tokenization {
                content_type,
                size,
                reason,
            } => {
                write!(
                    f,
                    "Tokenization error for {} content (size: {}): {}",
                    content_type, size, reason
                )
            }
            YekError::UserInput {
                input_type,
                value,
                suggestion,
            } => {
                write!(
                    f,
                    "Invalid {} input '{}': {}",
                    input_type, value, suggestion
                )
            }
        }
    }
}

impl std::error::Error for YekError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            YekError::FileSystem { source, .. } => Some(source),
            YekError::Git { source, .. } => Some(source),
            _ => None,
        }
    }
}

/// Error context for better debugging and user feedback
#[derive(Debug, Clone)]
pub struct ErrorContext {
    pub operation: String,
    pub file: Option<PathBuf>,
    pub line: Option<u32>,
    pub column: Option<u32>,
    pub additional_info: Vec<(String, String)>,
}

impl ErrorContext {
    pub fn new(operation: impl Into<String>) -> Self {
        Self {
            operation: operation.into(),
            file: None,
            line: None,
            column: None,
            additional_info: Vec::new(),
        }
    }

    pub fn with_file(mut self, file: impl Into<PathBuf>) -> Self {
        self.file = Some(file.into());
        self
    }

    pub fn with_location(mut self, line: u32, column: u32) -> Self {
        self.line = Some(line);
        self.column = Some(column);
        self
    }

    pub fn with_info(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.additional_info.push((key.into(), value.into()));
        self
    }

    pub fn build(self) -> Self {
        self
    }
}

impl Default for ErrorContext {
    fn default() -> Self {
        Self::new("unknown_operation")
    }
}

/// Error type that combines the main error and its context
#[derive(Debug)]
pub struct YekErrorWithContext {
    pub error: YekError,
    pub context: ErrorContext,
}

impl std::fmt::Display for YekErrorWithContext {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} (context: {:?})", self.error, self.context)
    }
}

impl std::error::Error for YekErrorWithContext {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.error.source()
    }
}

/// Enhanced result type with context
pub type YekResult<T> = std::result::Result<T, Box<YekErrorWithContext>>;

/// Error reporting utilities
pub struct ErrorReporter;

impl ErrorReporter {
    /// Report an error with context to the user
    pub fn report_error(error: &YekError, context: &ErrorContext, verbose: bool) {
        // Always show the main error
        eprintln!("Error: {}", error);

        // Show context information
        if verbose {
            if let Some(ref file) = context.file {
                eprintln!("  File: {}", file.display());
            }
            if let Some(line) = context.line {
                eprintln!("  Line: {}", line);
            }
            if let Some(column) = context.column {
                eprintln!("  Column: {}", column);
            }
            eprintln!("  Operation: {}", context.operation);

            // Show additional info
            for (key, value) in &context.additional_info {
                eprintln!("  {}: {}", key, value);
            }
        }

        // Show suggestions for common errors
        Self::show_suggestions(error, context);
    }

    /// Show helpful suggestions for common errors
    #[allow(clippy::collapsible_match)]
    fn show_suggestions(error: &YekError, _context: &ErrorContext) {
        match error {
            YekError::FileSystem {
                operation, path, ..
            } => {
                if operation.contains("read") {
                    if !path.exists() {
                        eprintln!("Suggestion: Check if the file exists and the path is correct.");
                    } else if let Ok(metadata) = std::fs::metadata(path) {
                        if metadata.permissions().readonly() {
                            eprintln!("Suggestion: Check if the file is readable (permissions).");
                        }
                    }
                }
            }
            YekError::Configuration {
                field,
                value,
                reason,
            } => {
                eprintln!(
                    "Suggestion: Fix the '{}' configuration value '{}' - {}",
                    field, value, reason
                );
            }
            YekError::Memory {
                operation,
                requested: _,
                ..
            } => {
                eprintln!(
                    "Suggestion: Try reducing the '{}' size or use streaming mode.",
                    operation
                );
                eprintln!(
                    "Suggestion: Consider using token mode instead of byte mode for large files."
                );
            }
            YekError::Security { violation: _, .. } => {
                eprintln!("Suggestion: This appears to be a security violation. Please check your input paths.");
            }
            YekError::Validation {
                field, constraint, ..
            } => {
                eprintln!(
                    "Suggestion: The '{}' field violates the constraint '{}'.",
                    field, constraint
                );
            }
            _ => {}
        }
    }

    /// Create a user-friendly error message
    pub fn user_friendly_message(error: &YekError) -> String {
        match error {
            YekError::FileSystem {
                operation, path, ..
            } => {
                format!("Failed to {} file '{}'", operation, path.display())
            }
            YekError::Git {
                operation,
                repository,
                ..
            } => {
                format!(
                    "Git operation '{}' failed in repository '{}'",
                    operation,
                    repository.display()
                )
            }
            YekError::Configuration { field, reason, .. } => {
                format!("Configuration issue with '{}': {}", field, reason)
            }
            YekError::Processing {
                stage,
                file,
                reason,
            } => {
                if let Some(file_path) = file {
                    format!(
                        "Processing failed in '{}' stage for '{}': {}",
                        stage,
                        file_path.display(),
                        reason
                    )
                } else {
                    format!("Processing failed in '{}' stage: {}", stage, reason)
                }
            }
            YekError::Memory {
                operation,
                requested,
                ..
            } => {
                format!(
                    "Insufficient memory for '{}' (requested: {} bytes)",
                    operation, requested
                )
            }
            YekError::Security {
                violation, path, ..
            } => {
                format!(
                    "Security violation '{}' for path '{}'",
                    violation,
                    path.display()
                )
            }
            YekError::Validation {
                field, constraint, ..
            } => {
                format!(
                    "Validation failed for '{}': violates '{}'",
                    field, constraint
                )
            }
            YekError::Tokenization {
                content_type,
                size,
                reason,
            } => {
                format!(
                    "Failed to process {} content ({}): {}",
                    content_type, size, reason
                )
            }
            YekError::UserInput {
                input_type,
                suggestion,
                ..
            } => {
                format!("Invalid {}: {}", input_type, suggestion)
            }
        }
    }
}

/// Utilities for safe operations with error handling
pub mod safe_ops {
    use super::*;
    use std::sync::{Arc, Mutex};

    /// Safely read a file with comprehensive error handling
    pub fn safe_read_file(
        path: &Path,
        context: &ErrorContext,
        max_size: Option<usize>,
    ) -> YekResult<Vec<u8>> {
        // Check if file exists
        if !path.exists() {
            return Err(Box::new(YekErrorWithContext {
                error: YekError::FileSystem {
                    operation: "read".to_string(),
                    path: path.to_path_buf(),
                    source: io::Error::new(io::ErrorKind::NotFound, "File not found"),
                },
                context: context.clone(),
            }));
        }

        // Check if it's actually a file
        if !path.is_file() {
            return Err(Box::new(YekErrorWithContext {
                error: YekError::FileSystem {
                    operation: "read".to_string(),
                    path: path.to_path_buf(),
                    source: io::Error::new(io::ErrorKind::InvalidInput, "Path is not a file"),
                },
                context: context.clone(),
            }));
        }

        // Read file content
        match std::fs::read(path) {
            Ok(content) => {
                // Check size limits
                if let Some(max_size) = max_size {
                    if content.len() > max_size {
                        return Err(Box::new(YekErrorWithContext {
                            error: YekError::Memory {
                                operation: "file reading".to_string(),
                                requested: content.len(),
                                available: Some(max_size),
                            },
                            context: context.clone(),
                        }));
                    }
                }
                Ok(content)
            }
            Err(source) => Err(Box::new(YekErrorWithContext {
                error: YekError::FileSystem {
                    operation: "read".to_string(),
                    path: path.to_path_buf(),
                    source,
                },
                context: context.clone(),
            })),
        }
    }

    /// Safely validate UTF-8 content with fallback
    pub fn safe_validate_utf8(bytes: &[u8], _context: &ErrorContext) -> YekResult<String> {
        match String::from_utf8(bytes.to_vec()) {
            Ok(content) => Ok(content),
            Err(_utf8_err) => {
                // Try to recover by replacing invalid sequences
                let recovered = String::from_utf8_lossy(bytes);
                if recovered.contains('\u{FFFD}') {
                    // Contains replacement characters, report as warning
                    eprintln!("Warning: File contains invalid UTF-8 sequences, replaced with � characters");
                }
                Ok(recovered.to_string())
            }
        }
    }

    /// Safely check path traversal attempts
    pub fn safe_validate_path(
        input_path: &Path,
        base_path: &Path,
        context: &ErrorContext,
    ) -> YekResult<PathBuf> {
        // Normalize the path
        let normalized = std::fs::canonicalize(input_path).map_err(|source| {
            Box::new(YekErrorWithContext {
                error: YekError::FileSystem {
                    operation: "canonicalize".to_string(),
                    path: input_path.to_path_buf(),
                    source,
                },
                context: context.clone(),
            })
        })?;

        // Check for path traversal attempts
        if let Ok(_relative) = normalized.strip_prefix(base_path) {
            // Path is within base directory, safe
            Ok(normalized)
        } else {
            // Path tries to escape base directory, potential security issue
            Err(Box::new(YekErrorWithContext {
                error: YekError::Security {
                    violation: "Path traversal attempt".to_string(),
                    path: normalized,
                    attempted_by: context.operation.clone(),
                },
                context: context.clone(),
            }))
        }
    }

    /// Safely handle mutex operations with poison error recovery
    pub fn safe_mutex_access<T, F, R>(
        mutex: &Arc<Mutex<T>>,
        operation: F,
        context: &ErrorContext,
    ) -> YekResult<R>
    where
        F: FnOnce(&mut T) -> R,
        T: fmt::Debug,
    {
        match mutex.lock() {
            Ok(mut guard) => Ok(operation(&mut guard)),
            Err(poison_err) => {
                // Mutex was poisoned, try to recover
                eprintln!(
                    "Warning: Mutex was poisoned, attempting recovery for operation: {}",
                    context.operation
                );

                // Try to recover the mutex
                let mut guard = poison_err.into_inner();
                Ok(operation(&mut guard))
            }
        }
    }
}