repatch 0.1.1

A regex find-and-replace tool with a `git add --patch`-like interface.
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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::io::Write;
use std::os::unix::ffi::{OsStrExt, OsStringExt};
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::process::Command;
use std::sync::OnceLock;
use std::time::SystemTime;

use bstr::ByteSlice;
use grep_matcher::{Captures, Matcher};
use grep_regex::RegexMatcher;

pub fn ranges(sorted_list: &[u64], padding: u64) -> Vec<std::ops::RangeInclusive<u64>> {
    let mut ranges = Vec::new();
    let padding = std::num::Saturating(padding);

    for x in sorted_list {
        let x = std::num::Saturating(*x);

        let Some(range) = ranges.last_mut() else {
            let start = x - padding;
            let end = x + padding;
            ranges.push(start.0..=end.0);
            continue;
        };

        if range.contains(&(x - padding).0) {
            if *range.end() < (x + padding).0 {
                let end = x + padding;
                *range = *range.start()..=end.0;
            }
            continue;
        }

        let start = x - padding;
        let end = x + padding;
        ranges.push(start.0..=end.0);
    }

    ranges
}

pub fn replace_file<T>(
    path: impl AsRef<Path>,
    modified_at: Option<SystemTime>,
    f: impl FnOnce(&File, &File) -> (bool, T),
) -> Result<T, ReplaceFileError> {
    #[cfg(target_os = "linux")]
    {
        replace_file_linux(path, modified_at, /* allow_fallback= */ true, f)
    }

    #[cfg(not(target_os = "linux"))]
    {
        replace_file_compat(path, modified_at, f)
    }
}

/// A linux-specific variant of [`replace_file`].
#[cfg(target_os = "linux")]
fn replace_file_linux<T>(
    path: impl AsRef<Path>,
    modified_at: Option<SystemTime>,
    allow_fallback: bool,
    f: impl FnOnce(&File, &File) -> (bool, T),
) -> Result<T, ReplaceFileError> {
    use std::ffi::CString;
    use std::fs::OpenOptions;
    use std::os::fd::AsRawFd;
    use std::os::unix::fs::OpenOptionsExt;

    let path = path.as_ref();

    if !path.is_file() {
        return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "not a file").into());
    }

    // TODO: this path may already exist, so choose a better path? (linkat below won't overwrite
    // existing files, so this won't cause us to lose data)
    let tmp_path = {
        let mut ext = path.extension().unwrap_or(OsStr::new("")).to_os_string();
        ext.push(OsStr::new(".asdf123.tmp"));
        path.with_extension(ext)
    };

    let tmp_c_path = CString::new(tmp_path.as_os_str().as_bytes()).unwrap();

    // for paths like "foo", rust will return a parent of "" which is not useful for syscalls so we
    // replace it with "./"
    let mut parent_path = path.parent().unwrap();
    if parent_path == Path::new("") {
        parent_path = Path::new("./");
    }

    // create an unnamed file on the mount for the path
    let new = match OpenOptions::new()
        .write(true)
        .truncate(true)
        .custom_flags(libc::O_TMPFILE)
        .open(parent_path)
    {
        Ok(x) => x,
        // O_TMPFILE is only supported on a few filesystems
        Err(e) if allow_fallback && e.raw_os_error() == Some(libc::EOPNOTSUPP) => {
            return replace_file_compat(path, modified_at, f);
        }
        Err(e) => return Err(e.into()),
    };

    let original = File::open(path)?;

    // copy only the user/group/other read/write/execute permission bits
    #[allow(clippy::useless_conversion)]
    let mask = u32::from(libc::S_IRWXU | libc::S_IRWXG | libc::S_IRWXO);

    // set the permissions after creating the file so that it's not affected by the umask
    new.set_permissions(read_permissions(&original, mask)?)?;

    // the path to the new file in the /proc mount
    let mut procfd_c_path = Vec::new();
    procfd_c_path.extend(b"/proc/self/fd/");
    procfd_c_path.extend(new.as_raw_fd().to_string().as_bytes());
    let procfd_c_path = CString::new(procfd_c_path).unwrap();

    // TODO: use fallocate() to ensure we have approx enough space (the new file might be larger or
    // smaller than the original, but will typically be similar)?

    let (do_replace_file, rv) = f(&original, &new);

    // the user-provided closure asked us to stop
    if !do_replace_file {
        return Ok(rv);
    };

    if let Some(modified_at) = modified_at {
        // the current "modified" time for the file
        let latest_modified = std::fs::metadata(path)?.modified()?;

        // return an error if the file's "modified" timestamps differ
        if latest_modified != modified_at {
            return Err(ReplaceFileError::ModifiedTimeChanged);
        }
    }

    // give the new file a temporary name
    let linkat_rv = unsafe {
        libc::linkat(
            libc::AT_FDCWD,
            procfd_c_path.as_ptr(),
            libc::AT_FDCWD,
            tmp_c_path.as_ptr(),
            libc::AT_SYMLINK_FOLLOW,
        )
    };
    if linkat_rv != 0 {
        // may have failed if a file at `tmp_path` already exists
        return Err(std::io::Error::last_os_error().into());
    }

    // replace the original file at `path` with the new file
    std::fs::rename(&tmp_path, path)?;

    Ok(rv)
}

/// A platform-agnostic variant of [`replace_file`].
fn replace_file_compat<T>(
    path: impl AsRef<Path>,
    modified_at: Option<SystemTime>,
    f: impl FnOnce(&File, &File) -> (bool, T),
) -> Result<T, ReplaceFileError> {
    let path = path.as_ref();

    if !path.is_file() {
        return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "not a file").into());
    }

    // copy only the user/group/other read/write/execute permission bits
    #[allow(clippy::useless_conversion)]
    let mask = u32::from(libc::S_IRWXU | libc::S_IRWXG | libc::S_IRWXO);

    let original = File::open(path)?;
    let original_permissions = read_permissions(&original, mask)?;

    let mut prefix = OsString::new();
    prefix.push(".");
    prefix.push(path.file_name().unwrap());
    prefix.push(".");

    let mut new = tempfile::Builder::new();
    let new = new
        .prefix(&prefix)
        .suffix(".tmp")
        // even though we set the permissions below, we should also set them here to avoid
        // temporarily creating a file that's more permissive than the original
        .permissions(original_permissions.clone())
        // create it in the same directory since you can't rename a file across filesystems
        .tempfile_in(path.parent().unwrap())?;

    // set the permissions after creating the file so that it's not affected by the umask
    new.as_file().set_permissions(original_permissions)?;

    // TODO: use fallocate() to ensure we have approx enough space (the new file might be larger or
    // smaller than the original, but will typically be similar)?

    let (do_replace_file, rv) = f(&original, new.as_file());

    // the user-provided closure asked us to stop
    if !do_replace_file {
        return Ok(rv);
    };

    if let Some(modified_at) = modified_at {
        // the current "modified" time for the file
        let latest_modified = std::fs::metadata(path)?.modified()?;

        // return an error if the file's "modified" timestamps differ
        if latest_modified != modified_at {
            return Err(ReplaceFileError::ModifiedTimeChanged);
        }
    }

    // replace the original file at `path` with the new file
    new.persist(path).map_err(|e| e.error)?;

    Ok(rv)
}

#[derive(Debug)]
pub enum ReplaceFileError {
    Io(std::io::Error),
    ModifiedTimeChanged,
}

impl From<std::io::Error> for ReplaceFileError {
    fn from(e: std::io::Error) -> Self {
        Self::Io(e)
    }
}

impl std::fmt::Display for ReplaceFileError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Io(e) => write!(f, "{e}"),
            Self::ModifiedTimeChanged => {
                write!(f, r#"the file's "modified" timestamp unexpectedly changed"#)
            }
        }
    }
}

impl std::error::Error for ReplaceFileError {}

/// Returns the file permissions without any file type bits. Also applies an additional bitmask to
/// the returned mode.
fn read_permissions(file: &File, mask: u32) -> std::io::Result<std::fs::Permissions> {
    // `std::fs::Metadata::permissions()` contains everything in the `st_mode` stat field, which
    // also contains the file type which we mask out
    #[allow(clippy::useless_conversion)]
    let file_type_mask = u32::from(libc::S_IFMT);

    let mode = file.metadata()?.permissions().mode() & !file_type_mask;
    let mode = mode & mask;
    Ok(std::fs::Permissions::from_mode(mode))
}

pub fn editor_cmd() -> impl Iterator<Item = impl AsRef<OsStr>> + Clone {
    static EDITOR_CMD: OnceLock<Vec<OsString>> = OnceLock::new();

    // this is roughly what `sudo -e` does when parsing env variables
    fn split_whitespace(bytes: &[u8]) -> Vec<OsString> {
        bytes
            .fields()
            .map(|x| OsString::from_vec(x.to_vec()))
            .collect()
    }

    // returns `None` if `name` isn't set or if empty
    fn env_var(name: &str) -> Option<Vec<OsString>> {
        if let Some(cmd) = std::env::var_os(name) {
            let cmd = split_whitespace(cmd.as_bytes());
            if !cmd.is_empty() {
                return Some(cmd);
            }
        }
        None
    }

    let cmd = EDITOR_CMD.get_or_init(|| {
        if let Some(cmd) = env_var("VISUAL") {
            return cmd;
        }

        if let Some(cmd) = env_var("EDITOR") {
            return cmd;
        }

        if let Some(cmd) = env_var("GIT_EDITOR") {
            return cmd;
        }

        if let Ok(output) = Command::new("git")
            .arg("config")
            .arg("--null")
            .arg("core.editor")
            .output()
        {
            if output.status.success() {
                let mut output = output.stdout;
                // the last byte should be a nul
                assert!(matches!(output.pop(), Some(0) | None));

                if !output.is_empty() {
                    let cmd = split_whitespace(&output);
                    if !cmd.is_empty() {
                        return cmd;
                    }
                }
            }
        }

        // if we can't find an editor, choose the best editor
        [OsString::from_vec(b"vim".to_vec())].to_vec()
    });

    assert!(!cmd.is_empty());

    cmd.iter()
}

pub fn replace_regex(
    matcher: &RegexMatcher,
    replacement: &[u8],
    haystack: &[u8],
    dest: &mut Vec<u8>,
) -> Result<(), <RegexMatcher as Matcher>::Error> {
    let mut captures = matcher.new_captures().unwrap();
    matcher.replace_with_captures(haystack, &mut captures, dest, |caps, dest| {
        caps.interpolate(
            |name| matcher.capture_index(name),
            haystack,
            replacement,
            dest,
        );
        true
    })
}

pub fn rewrite_patch_line_counts(bytes: &[u8]) -> std::borrow::Cow<[u8]> {
    let result = (|| {
        let mut lines = crate::parse::lines_with_pos(bytes);

        let (header, header_start) = lines.nth(2)?;

        let (range_1, range_2) = crate::parse::patch_block_header(header)?;

        let mut content_start = None;
        let mut line_counts = (0, 0);

        // count the number of + and - lines
        for (line, pos) in lines {
            if content_start.is_none() {
                content_start = Some(pos);
            }

            match line.first() {
                Some(b' ') | None => {
                    line_counts.0 += 1;
                    line_counts.1 += 1;
                }
                Some(b'-') => line_counts.0 += 1,
                Some(b'+') => line_counts.1 += 1,
                _ => return None,
            }
        }

        if (range_1.1, range_2.1) == line_counts {
            // no need to change the patch
            return None;
        }

        let content_start = content_start?;

        // build the new patch
        let mut new_patch = Vec::new();

        // add the header
        new_patch.extend_from_slice(&bytes[..header_start]);

        // write the new line numbers
        writeln!(
            &mut new_patch,
            "@@ -{},{} +{},{} @@",
            range_1.0, line_counts.0, range_2.0, line_counts.1,
        )
        .ok()?;

        // add the patch contents
        new_patch.extend_from_slice(&bytes[content_start..]);

        Some(new_patch)
    })();

    match result {
        Some(x) => std::borrow::Cow::Owned(x),
        None => std::borrow::Cow::Borrowed(bytes),
    }
}

pub fn rewrite_patch_line_start(bytes: &[u8], offset: i128, ansi: bool) -> Option<Vec<u8>> {
    let mut lines = crate::parse::lines_with_pos(bytes);
    let (mut header, header_start) = lines.nth(2)?;
    let (_, content_start) = lines.next()?;

    const ANSI_RESET: &[u8] = b"\x1b[0m";
    const ANSI_HEADER_COLOR: &[u8] = b"\x1b[36m";

    if ansi {
        header = header.strip_prefix(ANSI_RESET)?;
        header = header.strip_prefix(ANSI_HEADER_COLOR)?;
        header = header.strip_suffix(ANSI_RESET)?;
    }

    let (mut pair_1, mut pair_2) = crate::parse::patch_block_header(header)?;

    let (offset, positive_offset) = if offset >= 0 {
        (u64::try_from(offset).ok()?, true)
    } else {
        (u64::try_from(-offset).ok()?, false)
    };

    if positive_offset {
        pair_1.0 = pair_1.0.checked_add(offset)?;
        pair_2.0 = pair_2.0.checked_add(offset)?;
    } else {
        pair_1.0 = pair_1.0.checked_sub(offset)?;
        pair_2.0 = pair_2.0.checked_sub(offset)?;
    }

    // build the new patch
    let mut new_patch = Vec::new();

    // add the header
    new_patch.extend_from_slice(&bytes[..header_start]);

    if ansi {
        new_patch.extend_from_slice(ANSI_RESET);
        new_patch.extend_from_slice(ANSI_HEADER_COLOR);
    }

    // write the new line numbers
    write!(
        &mut new_patch,
        "@@ -{},{} +{},{} @@",
        pair_1.0, pair_1.1, pair_2.0, pair_2.1,
    )
    .ok()?;

    if ansi {
        new_patch.extend_from_slice(ANSI_RESET);
    }

    writeln!(&mut new_patch).unwrap();

    // add the patch contents
    new_patch.extend_from_slice(&bytes[content_start..]);

    Some(new_patch)
}

/// A label you can jump to using `continue`.
///
/// ```
/// let x: u32 = label!('start {
///     let input = todo!();
///     match input {
///         "retry" => continue 'start,
///         "one" => 1,
///         "two" => 2,
///         _ => input.parse().unwrap(),
///     }
/// });
/// ```
macro_rules! label {
    ($label:lifetime: $code:block) => {
        $label: loop {
            let _rv = {
                $code
            };
            #[allow(unreachable_code)]
            {
                break $label _rv;
            }
        }
    };
}
pub(crate) use label;

#[cfg(test)]
mod tests {
    use super::*;

    use std::io::Write;

    #[test]
    fn test_ranges() {
        let list = [1, 2, 10, 12, 35, 38, 55, u64::MAX];
        let padding = 5;
        assert_eq!(
            ranges(&list, padding),
            [0..=17, 30..=43, 50..=60, u64::MAX - 5..=u64::MAX],
        );

        let list = [1, 2, 10, 12, 35, 38, 55, u64::MAX];
        let padding = u64::MAX;
        assert_eq!(ranges(&list, padding), [0..=u64::MAX]);

        let list = [];
        let padding = 5;
        assert_eq!(ranges(&list, padding), []);

        let list = [1, 2, 5, 7, 100];
        let padding = 0;
        assert_eq!(
            ranges(&list, padding),
            [1..=1, 2..=2, 5..=5, 7..=7, 100..=100]
        );

        let list = [1, 2, 5, 7, 100];
        let padding = 1;
        assert_eq!(ranges(&list, padding), [0..=3, 4..=8, 99..=101]);
    }

    // it would be nice to make this helper a generic fn, but it's not possible without HRTBs
    macro_rules! replace_file_tester {
        ($f: ident) => {{
            let mut file = tempfile::Builder::new().tempfile().unwrap();
            file.write_all(b"hello world\n").unwrap();

            $f(file.path(), None, |mut original, mut new| {
                new.write_all(b"foo ").unwrap();
                std::io::copy(&mut original, &mut new).unwrap();
                (true, ())
            })
            .unwrap();

            // `file` doesn't point to the new file located at `file.path()`, so it's confusing to
            // leave the file open
            let file = file.into_temp_path();

            // verify the new file has the correct contents
            assert_eq!(std::fs::read(&file).unwrap(), b"foo hello world\n");

            /////////

            let mut file = tempfile::Builder::new().tempfile().unwrap();
            file.write_all(b"hello world\n").unwrap();

            $f(file.path(), None, |mut original, mut new| {
                new.write_all(b"foo ").unwrap();
                std::io::copy(&mut original, &mut new).unwrap();
                (false, ())
            })
            .unwrap();

            // verify the file has the same contents
            assert_eq!(std::fs::read(file.path()).unwrap(), b"hello world\n");

            /////////

            let mut file = tempfile::Builder::new().tempfile().unwrap();
            file.write_all(b"hello world\n").unwrap();

            // user readable and executable
            #[allow(clippy::useless_conversion)]
            let target_permissions = u32::from(libc::S_IXUSR | libc::S_IRUSR);
            let target_permissions = std::fs::Permissions::from_mode(target_permissions);

            // set the permissions for the file
            file.as_file()
                .set_permissions(target_permissions.clone())
                .unwrap();
            assert_eq!(
                read_permissions(&file.as_file(), u32::MAX).unwrap(),
                target_permissions,
            );

            $f(file.path(), None, |mut original, mut new| {
                new.write_all(b"foo ").unwrap();
                std::io::copy(&mut original, &mut new).unwrap();
                (true, ())
            })
            .unwrap();

            // `file` doesn't point to the new file located at `file.path()`, so it's confusing to
            // leave the file open
            let file = file.into_temp_path();

            // verify the new file has the correct contents
            assert_eq!(std::fs::read(&file).unwrap(), b"foo hello world\n");

            // verify the new file has the same permissions
            assert_eq!(
                read_permissions(&File::open(&file).unwrap(), u32::MAX).unwrap(),
                target_permissions,
            );
        }};
    }

    #[test]
    fn test_replace_file() {
        replace_file_tester!(replace_file);
    }

    #[test]
    fn test_replace_file_compat() {
        replace_file_tester!(replace_file_compat);
    }

    // 'replace_file_linux' only works on certain filesystems, so ignore by default
    #[test]
    #[ignore]
    #[cfg(target_os = "linux")]
    fn test_replace_file_linux() {
        // test it without falling back to the platform-agnostic version, otherwise we might miss
        // valid errors in the linux implementation
        pub fn helper<T>(
            path: impl AsRef<Path>,
            modified_at: Option<SystemTime>,
            f: impl FnOnce(&File, &File) -> (bool, T),
        ) -> Result<T, ReplaceFileError> {
            replace_file_linux(path, modified_at, /* allow_fallback= */ false, f)
        }

        replace_file_tester!(helper);
    }
}