splice 2.6.4

Span-safe refactoring kernel for 7 languages with Magellan code graph integration
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
//! Context extraction for span surroundings.
//!
//! Provides line-based context extraction using ropey for efficient
//! UTF-8 aware line/column calculations.

use crate::error::{Result, SpliceError};
use std::path::Path;

use crate::output::SpanContext;

/// Resolve context counts from -A/-B/-C flags following grep convention.
///
/// The grep convention is: -C (context both) sets the default for both sides,
/// but -A (after) and -B (before) can override -C if larger. This allows:
/// - `-C 3` for 3 lines before and after (default grep behavior)
/// - `-A 5 -B 2` for 5 lines after, 2 lines before (asymmetric)
/// - `-C 10 -A 5` for max(10, 5)=10 before, max(10, 0)=10 after
///
/// # Arguments
///
/// * `context_before` - Value from -B flag (lines before)
/// * `context_after` - Value from -A flag (lines after)
/// * `context_both` - Value from -C flag (lines on both sides)
///
/// # Returns
///
/// * `(before, after)` - Resolved context line counts for before and after
///
/// # Examples
///
/// ```
/// use splice::context::resolve_context_counts;
///
/// // -C 3 (default grep behavior)
/// let (before, after) = resolve_context_counts(0, 0, 3);
/// assert_eq!(before, 3);
/// assert_eq!(after, 3);
///
/// // -A 5 -B 2 (asymmetric)
/// let (before, after) = resolve_context_counts(2, 5, 0);
/// assert_eq!(before, 2);
/// assert_eq!(after, 5);
///
/// // -C 10 -A 5 (C overrides A when larger)
/// let (before, after) = resolve_context_counts(0, 5, 10);
/// assert_eq!(before, 10);
/// assert_eq!(after, 10);
/// ```
pub fn resolve_context_counts(
    context_before: usize,
    context_after: usize,
    context_both: usize,
) -> (usize, usize) {
    let before = context_before.max(context_both);
    let after = context_after.max(context_both);
    (before, after)
}

/// Extract context lines for a byte span with asymmetric before/after counts.
///
/// Given a file path and byte range, extracts lines before, within, and after
/// the span. Allows different amounts of context before vs after the match.
/// Uses UTF-8 byte offsets consistent with span coordinates.
///
/// # Arguments
///
/// * `path` - File path to read
/// * `byte_start` - Start byte offset (must be <= byte_end)
/// * `byte_end` - End byte offset (must be <= file size)
/// * `context_before` - Number of context lines before (default: 0)
/// * `context_after` - Number of context lines after (default: 0)
///
/// # Returns
///
/// * `Ok(SpanContext)` - Extracted context with before/selected/after arrays
/// * `Err(SpliceError)` - If file cannot be read or span is invalid
///
/// # Examples
///
/// ```no_run
/// use splice::context::extract_context_asymmetric;
/// use std::path::Path;
///
/// // 5 lines before, 2 lines after
/// let context = extract_context_asymmetric(Path::new("src/main.rs"), 100, 200, 5, 2)?;
/// println!("Before: {} lines, After: {} lines", context.before.len(), context.after.len());
/// # Ok::<(), splice::error::SpliceError>(())
/// ```
pub fn extract_context_asymmetric(
    path: &Path,
    byte_start: usize,
    byte_end: usize,
    context_before: usize,
    context_after: usize,
) -> Result<SpanContext> {
    use ropey::Rope;

    // Validate byte range
    if byte_start > byte_end {
        return Err(SpliceError::InvalidSpan {
            file: path.to_path_buf(),
            start: byte_start,
            end: byte_end,
            file_size: 0, // Will be updated after read
        });
    }

    // Read file
    let contents = std::fs::read(path).map_err(|e| SpliceError::IoContext {
        context: format!(
            "Failed to read file for context extraction: {}",
            path.display()
        ),
        source: e,
    })?;

    let file_size = contents.len();

    // Validate end is within file
    if byte_end > file_size {
        return Err(SpliceError::InvalidSpan {
            file: path.to_path_buf(),
            start: byte_start,
            end: byte_end,
            file_size,
        });
    }

    // Handle empty file case
    if file_size == 0 {
        return Ok(SpanContext {
            before: vec![],
            selected: vec![],
            after: vec![],
        });
    }

    // Create Rope for efficient line operations (UTF-8 aware)
    let rope =
        Rope::from_str(
            std::str::from_utf8(&contents).map_err(|e| SpliceError::InvalidUtf8 {
                file: path.to_path_buf(),
                source: e,
            })?,
        );

    // Convert byte offsets to line numbers (0-based)
    let start_line = rope.byte_to_line(byte_start);
    let end_line = rope.byte_to_line(byte_end.saturating_sub(1));

    // Calculate context boundaries with asymmetric values
    let context_start = start_line.saturating_sub(context_before);
    let context_end = (end_line + context_after + 1).min(rope.len_lines());

    // Extract before lines
    let before: Vec<String> = (context_start..start_line)
        .map(|i| rope.line(i).to_string())
        .collect();

    // Extract selected lines (the span itself)
    let selected: Vec<String> = (start_line..=end_line)
        .map(|i| rope.line(i).to_string())
        .collect();

    // Extract after lines (filter out empty trailing line from ropey behavior)
    let after: Vec<String> = (end_line + 1..context_end)
        .map(|i| rope.line(i).to_string())
        .filter(|line| !line.is_empty())
        .collect();

    Ok(SpanContext {
        before,
        selected,
        after,
    })
}

/// Extract context lines for a byte span with separate before/after context.
///
/// Given a file path and byte range, extracts lines before, within, and after
/// the span. Uses UTF-8 byte offsets consistent with span coordinates.
///
/// This is a convenience alias for [`extract_context_asymmetric`] with more
/// descriptive parameter names.
///
/// # Arguments
///
/// * `path` - File path to read
/// * `byte_start` - Start byte offset (must be <= byte_end)
/// * `byte_end` - End byte offset (must be <= file size)
/// * `context_lines_before` - Number of context lines before (default: 0)
/// * `context_lines_after` - Number of context lines after (default: 0)
///
/// # Returns
///
/// * `Ok(SpanContext)` - Extracted context with before/selected/after arrays
/// * `Err(SpliceError)` - If file cannot be read or span is invalid
///
/// # Examples
///
/// ```no_run
/// use splice::context::extract_context_with_before_after;
/// use std::path::Path;
///
/// let context = extract_context_with_before_after(Path::new("src/main.rs"), 100, 200, 2, 5)?;
/// println!("Before: {} lines, After: {} lines", context.before.len(), context.after.len());
/// # Ok::<(), splice::error::SpliceError>(())
/// ```
pub fn extract_context_with_before_after(
    path: &Path,
    byte_start: usize,
    byte_end: usize,
    context_lines_before: usize,
    context_lines_after: usize,
) -> Result<SpanContext> {
    extract_context_asymmetric(
        path,
        byte_start,
        byte_end,
        context_lines_before,
        context_lines_after,
    )
}

/// Extract context lines for a byte span.
///
/// Given a file path and byte range, extracts lines before, within, and after
/// the span. Uses UTF-8 byte offsets consistent with span coordinates.
///
/// # Arguments
///
/// * `path` - File path to read
/// * `byte_start` - Start byte offset (must be <= byte_end)
/// * `byte_end` - End byte offset (must be <= file size)
/// * `context_lines` - Number of context lines before/after (default: 3)
///
/// # Returns
///
/// * `Ok(SpanContext)` - Extracted context with before/selected/after arrays
/// * `Err(SpliceError)` - If file cannot be read or span is invalid
///
/// # Examples
///
/// ```no_run
/// use splice::context::extract_context;
/// use std::path::Path;
///
/// let context = extract_context(Path::new("src/main.rs"), 100, 200, 3)?;
/// println!("Before: {} lines", context.before.len());
/// # Ok::<(), splice::error::SpliceError>(())
/// ```
pub fn extract_context(
    path: &Path,
    byte_start: usize,
    byte_end: usize,
    context_lines: usize,
) -> Result<SpanContext> {
    // Delegate to asymmetric version with symmetric context
    extract_context_asymmetric(path, byte_start, byte_end, context_lines, context_lines)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    #[test]
    fn test_extract_context_basic() {
        let mut file = NamedTempFile::new().unwrap();
        writeln!(file, "line 1").unwrap();
        writeln!(file, "line 2").unwrap();
        writeln!(file, "line 3").unwrap();
        writeln!(file, "line 4").unwrap();
        writeln!(file, "line 5").unwrap();

        // Context for lines 2-3
        // "line 1\n" = 7 bytes, "line 2\n" = 7 bytes, "line 3\n" = 7 bytes
        // Bytes 7-20 covers "line 2\nline 3\n"
        let context = extract_context(file.path(), 7, 20, 1).unwrap();

        assert_eq!(context.before.len(), 1); // "line 1"
        assert_eq!(context.selected.len(), 2); // "line 2", "line 3"
        assert_eq!(context.after.len(), 1); // "line 4"
    }

    #[test]
    fn test_extract_context_zero_context() {
        let mut file = NamedTempFile::new().unwrap();
        writeln!(file, "line 1").unwrap();
        writeln!(file, "line 2").unwrap();
        writeln!(file, "line 3").unwrap();

        // "line 1\n" = bytes 0-6, "line 2\n" = bytes 7-13
        let context = extract_context(file.path(), 7, 13, 0).unwrap();

        assert_eq!(context.before.len(), 0);
        assert_eq!(context.selected.len(), 1);
        assert_eq!(context.after.len(), 0);
    }

    #[test]
    fn test_extract_context_start_of_file() {
        let mut file = NamedTempFile::new().unwrap();
        writeln!(file, "line 1").unwrap();
        writeln!(file, "line 2").unwrap();
        writeln!(file, "line 3").unwrap();

        // "line 1\nline 2\n" = bytes 0-13
        let context = extract_context(file.path(), 0, 13, 2).unwrap();

        assert_eq!(context.before.len(), 0); // No lines before start
        assert_eq!(context.selected.len(), 2);
        assert_eq!(context.after.len(), 1); // "line 3"
    }

    #[test]
    fn test_extract_context_end_of_file() {
        let mut file = NamedTempFile::new().unwrap();
        writeln!(file, "line 1").unwrap();
        writeln!(file, "line 2").unwrap();
        writeln!(file, "line 3").unwrap();

        // "line 1\nline 2\n" = bytes 0-13, "line 3\n" = bytes 14-20
        let context = extract_context(file.path(), 14, 20, 2).unwrap();

        assert_eq!(context.before.len(), 2); // "line 1", "line 2"
        assert_eq!(context.selected.len(), 1); // "line 3"
        assert_eq!(context.after.len(), 0); // No lines after end
    }

    #[test]
    fn test_extract_context_utf8_multibyte() {
        let mut file = NamedTempFile::new().unwrap();
        // Use emoji (multi-byte UTF-8)
        writeln!(file, "line 🦀 1").unwrap();
        writeln!(file, "line 🚀 2").unwrap();
        writeln!(file, "line ⭐ 3").unwrap();

        let contents = std::fs::read(file.path()).unwrap();
        // Find the start of "line 🚀 2"
        let rocket_line_start = contents.iter().position(|&b| b == b'2').unwrap();
        // Find the newline after "line 🚀 2"
        let rocket_line_end = contents
            .iter()
            .skip(rocket_line_start)
            .position(|&b| b == b'\n')
            .unwrap()
            + rocket_line_start;

        // Context should still work with multi-byte characters
        let context = extract_context(file.path(), rocket_line_start, rocket_line_end, 1).unwrap();

        assert_eq!(context.selected.len(), 1);
        assert!(context.selected[0].contains("🚀"));
    }

    #[test]
    fn test_extract_context_invalid_span() {
        let mut file = NamedTempFile::new().unwrap();
        writeln!(file, "line 1").unwrap();

        // start > end
        let result = extract_context(file.path(), 10, 5, 1);
        assert!(result.is_err());

        // end beyond file size
        let result = extract_context(file.path(), 0, 1000, 1);
        assert!(result.is_err());
    }

    #[test]
    fn test_extract_context_empty_file() {
        let file = NamedTempFile::new().unwrap();
        let result = extract_context(file.path(), 0, 0, 1);
        assert!(result.is_ok());
        // Empty file should return empty context
        let context = result.unwrap();
        assert_eq!(context.before.len(), 0);
        assert_eq!(context.selected.len(), 0);
        assert_eq!(context.after.len(), 0);
    }

    #[test]
    fn test_extract_context_large_context_request() {
        let mut file = NamedTempFile::new().unwrap();
        writeln!(file, "line 1").unwrap();
        writeln!(file, "line 2").unwrap();
        writeln!(file, "line 3").unwrap();

        // Request more context lines than exist (bytes 7-13 is "line 2\n")
        let context = extract_context(file.path(), 7, 13, 100).unwrap();

        // Should saturate at file boundaries
        assert_eq!(context.before.len(), 1); // Only "line 1"
        assert_eq!(context.selected.len(), 1);
        assert_eq!(context.after.len(), 1); // Only "line 3"
    }

    #[test]
    fn test_extract_context_asymmetric_basic() {
        let mut file = NamedTempFile::new().unwrap();
        writeln!(file, "line 1").unwrap();
        writeln!(file, "line 2").unwrap();
        writeln!(file, "line 3").unwrap();
        writeln!(file, "line 4").unwrap();
        writeln!(file, "line 5").unwrap();
        writeln!(file, "line 6").unwrap();
        writeln!(file, "line 7").unwrap();

        // Context for line 3-4
        // Each line is 7 bytes: "line N\n" = 6 + 1
        // line 1: 0-6, line 2: 7-13, line 3: 14-20, line 4: 21-27
        // Request 2 lines before, 1 line after
        let context = extract_context_asymmetric(file.path(), 14, 28, 2, 1).unwrap();

        assert_eq!(context.before.len(), 2); // "line 1", "line 2"
        assert_eq!(context.selected.len(), 2); // "line 3", "line 4"
        assert_eq!(context.after.len(), 1); // "line 5"
    }

    #[test]
    fn test_extract_context_asymmetric_zero_before() {
        let mut file = NamedTempFile::new().unwrap();
        writeln!(file, "line 1").unwrap();
        writeln!(file, "line 2").unwrap();
        writeln!(file, "line 3").unwrap();
        writeln!(file, "line 4").unwrap();

        // Each line is 7 bytes
        // line 2: 7-13, Request 0 before, 2 after
        let context = extract_context_asymmetric(file.path(), 7, 14, 0, 2).unwrap();

        assert_eq!(context.before.len(), 0);
        assert_eq!(context.selected.len(), 1);
        assert_eq!(context.after.len(), 2); // "line 3", "line 4"
    }

    #[test]
    fn test_extract_context_asymmetric_zero_after() {
        let mut file = NamedTempFile::new().unwrap();
        writeln!(file, "line 1").unwrap();
        writeln!(file, "line 2").unwrap();
        writeln!(file, "line 3").unwrap();
        writeln!(file, "line 4").unwrap();

        // Each line is 7 bytes
        // line 3: 14-20, Request 2 before, 0 after
        let context = extract_context_asymmetric(file.path(), 14, 21, 2, 0).unwrap();

        assert_eq!(context.before.len(), 2); // "line 1", "line 2"
        assert_eq!(context.selected.len(), 1);
        assert_eq!(context.after.len(), 0);
    }
}