smart-patcher 0.7.0

Patcher based on rules
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
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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
use difference_rs::Changeset;
use serde::{Deserialize, Serialize};
use std::fs::{self, File};
use std::io::Read;
use std::path::{Path, PathBuf};
use walkdir::WalkDir;

use crate::utils::RegexIR;
use crate::utils::is_verbose;

use crate::interactive::lua as lua_exec;
use crate::interactive::rhai as rhai_exec;
use crate::interactive::sh as sh_exec;

#[derive(Deserialize, Serialize, PartialEq, Default, Clone)]
/// Patch file structure,
///
/// Each `*.patch` file may contain several individual patches.
pub struct PatchFile {
  /// List of individual patches.
  pub patches: Vec<Patch>,
}

#[derive(Deserialize, Serialize, Debug, PartialEq, Default, Clone)]
/// Patch definition.
pub struct Patch {
  /// Rules to define patchable files.
  #[serde(default, skip_serializing_if = "Vec::is_empty")]
  pub files: Vec<FilePath>,
  /// Decode file content by decoder before patching.
  ///
  /// Useful on patching non-plain text or even non-text files.
  #[serde(skip_serializing_if = "Option::is_none")]
  pub decoder: Option<DecodeBy>,
  /// Encode file content by encoder after patching.
  ///
  /// Useful on patching non-plain text or even non-text files.
  #[serde(skip_serializing_if = "Option::is_none")]
  pub encoder: Option<EncodeBy>,
  /// List of rules to define patch area and cursor position.
  ///
  /// Allows to patch only defined content area.
  #[serde(default, skip_serializing_if = "Vec::is_empty")]
  pub patch_area: Vec<AreaRule>,
  /// Replaces some content inside patch area.
  #[serde(skip_serializing_if = "Option::is_none")]
  pub replace: Option<Replacer>,
  /// Inserts some content at cursor position.
  #[serde(skip_serializing_if = "Option::is_none")]
  pub insert: Option<String>,
}

#[derive(Deserialize, Serialize, Debug, PartialEq, Clone)]
#[serde(rename_all = "snake_case")]
/// Rule for patch area and cursor position definition.
pub enum AreaRule {
  /// Select given file to patch only if it contains some expression.
  Contains(RegexIR),
  /// Select given file to patch only if it doesn't contain some expression.
  NotContains(RegexIR),
  /// Crops patch area to the beginning of some expression and sets cursor to the end.
  Before(RegexIR),
  /// Crops patch area to the ending of some expression and sets cursor to the beginning.
  After(RegexIR),
  /// Explicitly sets cursor to the beginning.
  CursorAtBegin,
  /// Explicitly sets cursor to the end.
  CursorAtEnd,
  /// Find patch area by Lua script.
  FindByLua(PathBuf),
  /// Find patch area by Rhai script.
  FindByRhai(PathBuf),
  /// Find patch area by shell script.
  FindBySh(PathBuf),
}

/// Decoder definition.
#[derive(Deserialize, Serialize, Debug, PartialEq, Clone)]
#[serde(rename_all = "snake_case")]
pub enum DecodeBy {
  /// Decode file content by Lua script.
  Lua(PathBuf),
  /// Decode file content by Rhai script.
  Rhai(PathBuf),
  /// Decode file content by shell script.
  Sh(PathBuf),
}

/// Encoder definition.
#[derive(Deserialize, Serialize, Debug, PartialEq, Clone)]
#[serde(rename_all = "snake_case")]
pub enum EncodeBy {
  /// Encode file content by Lua script.
  Lua(PathBuf),
  /// Encode file content by Rhai script.
  Rhai(PathBuf),
  /// Encode file content by shell script.
  Sh(PathBuf),
}

/// Replacer definition.
#[derive(Deserialize, Serialize, Debug, PartialEq, Clone)]
#[serde(rename_all = "snake_case")]
pub enum Replacer {
  /// Replaces one text by another.
  FromTo(String, String),
  /// Replaces a text by the environment variable.
  FromToVar(String, String),
  /// Replaces all non-overlapping matches in the haystack with the replacement provided.
  ///
  /// See [Regex::replace_all](https://docs.rs/regex/latest/regex/struct.Regex.html#method.replace_all).
  RegexTo(RegexIR, String),
  /// Transforms patch area by Lua script.
  ByLua(PathBuf),
  /// Transforms patch area by Rhai script.
  ByRhai(PathBuf),
  /// Transforms patch area by shell script.
  BySh(PathBuf),
}

#[derive(Deserialize, Serialize, Debug, PartialEq, Clone)]
#[serde(rename_all = "snake_case")]
/// File path definition.
pub enum FilePath {
  /// Just given path (relative or absolute).
  Just(PathBuf),
  /// Regular expression rule to find files.
  ///
  /// See [Regex::is_match](https://docs.rs/regex/latest/regex/struct.Regex.html#method.is_match).
  Re(RegexIR),
}

enum CursorType {
  Start,
  End,
}

#[derive(Clone, Copy)]
enum CallType {
  Test,
  Patch,
}

impl PatchFile {
  fn find_for_file(
    &self,
    patch_dir: &Path,
    filepath: &Path,
    cntr: &mut usize,
    call_type: CallType,
  ) -> anyhow::Result<()> {
    for patch in &self.patches {
      if self.should_process_file(filepath, &patch.files) {
        if is_verbose() {
          println!("> File: {filepath:?}");
        }
        let Ok(content) = PatchFile::read(filepath, patch_dir, &patch.decoder) else { continue };
        match PatchFile::apply_patch(content.clone(), patch_dir, patch, cntr) {
          Ok(Some(res)) => {
            if is_verbose() {
              println!("> Applied with patch: {patch:?}");
            }
            match call_type {
              CallType::Patch => PatchFile::write(filepath, patch_dir, &patch.encoder, &res)?,
              CallType::Test => {
                let diffs = Changeset::new(&content, &res, "");
                println!("=========== DIFF ===========");
                println!("{diffs}");
                println!("=========== DIFF ===========");
              }
            }
          }
          Ok(None) if is_verbose() => {
            println!("> Ignored with patch: {patch:?}");
          }
          _ => {}
        }
      }
    }

    Ok(())
  }

  fn find_for_folder(&self, root: &Path, patch_dir: &Path, call_type: CallType) -> anyhow::Result<usize> {
    let mut cntr = 0;

    if root.is_dir() {
      for entry in WalkDir::new(root).into_iter().filter_map(|e| e.ok()) {
        let path = entry.path();
        if !path.is_file() {
          continue;
        }
        self.find_for_file(patch_dir, path, &mut cntr, call_type)?;
      }
    } else {
      self.find_for_file(patch_dir, root, &mut cntr, call_type)?;
    }

    Ok(cntr)
  }

  /// Runs all patches and returns number of patches applications.
  pub fn patch(&self, root: &Path, patch_dir: &Path) -> anyhow::Result<usize> {
    self.find_for_folder(root, patch_dir, CallType::Patch)
  }

  /// Tests patch file and returns number of possible patches applications.
  pub fn test(&self, root: &Path, patch_dir: &Path) -> anyhow::Result<usize> {
    self.find_for_folder(root, patch_dir, CallType::Test)
  }

  fn should_process_file(&self, path: &Path, file_patterns: &[FilePath]) -> bool {
    if file_patterns.is_empty() {
      return true;
    }

    let path_str = path.to_string_lossy();

    file_patterns.iter().any(|pattern| match pattern {
      FilePath::Just(exact_path) => path.ends_with(exact_path),
      FilePath::Re(regex) => regex.inner().is_match(&path_str),
    })
  }

  fn read(path: &Path, _patch_dir: &Path, decoder: &Option<DecodeBy>) -> anyhow::Result<String> {
    match decoder {
      None => {
        let mut content = String::new();
        File::open(path)?.read_to_string(&mut content)?;
        Ok(content)
      }
      Some(DecodeBy::Sh(script)) => Ok(sh_exec::decode_by(_patch_dir, script, path.canonicalize()?)?),
      Some(DecodeBy::Lua(script)) => {
        let mut content = vec![];
        File::open(path)?.read_to_end(&mut content)?;
        Ok(lua_exec::decode_by(_patch_dir, script, &content)?)
      }
      Some(DecodeBy::Rhai(script)) => {
        let mut content = vec![];
        File::open(path)?.read_to_end(&mut content)?;
        Ok(rhai_exec::decode_by(_patch_dir, script, &content)?)
      }
    }
  }

  fn write(path: &Path, _patch_dir: &Path, encoder: &Option<EncodeBy>, content: &str) -> anyhow::Result<()> {
    match encoder {
      None => {
        fs::write(path, content)?;
        Ok(())
      }
      Some(EncodeBy::Sh(script)) => {
        sh_exec::encode_by(_patch_dir, script, content, path.canonicalize()?)?;
        Ok(())
      }
      Some(EncodeBy::Lua(script)) => {
        let content = lua_exec::encode_by(_patch_dir, script, content)?;
        fs::write(path, content)?;
        Ok(())
      }
      Some(EncodeBy::Rhai(script)) => {
        let content = rhai_exec::encode_by(_patch_dir, script, content)?;
        fs::write(path, content)?;
        Ok(())
      }
    }
  }

  fn apply_patch(content: String, patch_dir: &Path, patch: &Patch, cntr: &mut usize) -> anyhow::Result<Option<String>> {
    if let Some((range, cursor)) = PatchFile::find_section(&content, patch_dir, &patch.patch_area)? {
      let before = &content[..range.start];
      let after = &content[range.end..];

      if is_verbose() { println!(">> Section was found (content[{}..{}]).", range.start, range.end); }

      let mut middle = content[range.start..range.end].to_owned();
      if !middle.is_empty()
        && let Some(replacer) = &patch.replace
      {
        match replacer {
          Replacer::FromTo(from, to) => {
            middle = middle.replace(from, to);
            if is_verbose() { println!(">> Replaced by `from_to` rule."); }
          }
          Replacer::FromToVar(from, to_env_var) => {
            let to = std::env::var(to_env_var)?;
            middle = middle.replace(from, &to);
            if is_verbose() { println!(">> Replaced by `from_to_var` rule."); }
          }
          Replacer::RegexTo(from_re, to) => {
            middle = from_re.replace_all(&middle, to.as_str()).to_string();
            if is_verbose() { println!(">> Replaced by `regex_to` rule."); }
          }
          Replacer::BySh(path) => {
            middle = sh_exec::replace_by(patch_dir, path, &middle)?;
            if is_verbose() { println!(">> Replaced by `by_sh` rule."); }
          }
          Replacer::ByLua(path) => {
            middle = lua_exec::replace_by(patch_dir, path, &middle)?;
            if is_verbose() { println!(">> Replaced by `by_lua` rule."); }
          }
          Replacer::ByRhai(path) => {
            middle = rhai_exec::replace_by(patch_dir, path, &middle)?;
            if is_verbose() { println!(">> Replaced by `by_rhai` rule."); }
          }
        }
      }
      if let Some(insert) = &patch.insert {
        if middle.is_empty() {
          middle = insert.to_owned();
        } else {
          middle = match cursor {
            CursorType::Start => insert.to_owned() + middle.as_str(),
            CursorType::End => middle + insert.as_str(),
          }
        }
      }

      let res = format!("{before}{middle}{after}");

      #[cfg(test)]
      {
        println!("{}", content);
        println!("{}", res);
      }

      if !res.as_str().eq(content.as_str()) {
        *cntr += 1;
      }
      return Ok(Some(res));
    }

    if is_verbose() {
      println!(">> Section wasn't found.");
    }

    Ok(None)
  }

  fn find_section(
    content: &str,
    _patch_dir: &Path,
    rules: &[AreaRule],
  ) -> anyhow::Result<Option<(std::ops::Range<usize>, CursorType)>> {
    let mut current_pos = 0;
    let mut start_pos = None;
    let mut end_pos = None;
    let mut cursor = CursorType::Start;

    for rule in rules {
      match &rule {
        AreaRule::Contains(regex) => {
          if !regex.inner().is_match(&content[current_pos..]) {
            return Ok(None);
          }
        }
        AreaRule::NotContains(regex) => {
          if regex.inner().is_match(&content[current_pos..]) {
            return Ok(None);
          }
        }
        AreaRule::Before(regex) => {
          cursor = CursorType::End;

          if let Some(mat) = regex.inner().find(&content[current_pos..]) {
            end_pos = Some(current_pos + mat.start());
          } else {
            return Ok(None);
          }
        }
        AreaRule::After(regex) => {
          cursor = CursorType::Start;

          if let Some(mat) = regex.inner().find(&content[current_pos..]) {
            start_pos = Some(current_pos + mat.end());
            current_pos += mat.end();
          } else {
            return Ok(None);
          }
        }
        AreaRule::CursorAtBegin => {
          cursor = CursorType::Start;
        }
        AreaRule::CursorAtEnd => {
          cursor = CursorType::End;
        }
        AreaRule::FindBySh(path) => {
          let (new_start, new_end, cursor_at_end) = sh_exec::find_by(_patch_dir, path, content, start_pos, end_pos)?;

          if new_start.is_some() {
            start_pos = new_start;
          }
          if new_end.is_some() {
            end_pos = new_end;
          }

          if cursor_at_end {
            cursor = CursorType::End;
          } else {
            cursor = CursorType::Start;
          }
        }
        AreaRule::FindByLua(path) => {
          let (new_start, new_end, cursor_at_end) = lua_exec::find_by(_patch_dir, path, content, start_pos, end_pos)?;

          if start_pos.is_none() && new_start != 0 {
            start_pos = Some(new_start);
          }
          if end_pos.is_none() && new_end != content.len() {
            end_pos = Some(new_end);
          }

          if cursor_at_end {
            cursor = CursorType::End;
          } else {
            cursor = CursorType::Start;
          }
        }
        AreaRule::FindByRhai(path) => {
          let (new_start, new_end, cursor_at_end) = rhai_exec::find_by(_patch_dir, path, content, start_pos, end_pos)?;

          if start_pos.is_none() && new_start != 0 {
            start_pos = Some(new_start);
          }
          if end_pos.is_none() && new_end != content.len() {
            end_pos = Some(new_end);
          }

          if cursor_at_end {
            cursor = CursorType::End;
          } else {
            cursor = CursorType::Start;
          }
        }
      }
    }

    let range = match (start_pos, end_pos) {
      (Some(start), Some(end)) if start <= end => Some(start..end),
      (Some(start), None) => Some(start..content.len()),
      (None, Some(end)) => Some(0..end),
      _ => Some(0..content.len()),
    };

    if let Some(range) = range {
      Ok(Some((range, cursor)))
    } else {
      Ok(None)
    }
  }
}

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

  #[test]
  fn find_v1() -> anyhow::Result<()> {
    let patch = Patch {
      files: vec![],
      patch_area: vec![AreaRule::After(RegexIR::new("media")?)],
      replace: Some(Replacer::FromTo(String::from("ttt"), String::from("yyy"))),
      insert: None,
      decoder: None,
      encoder: None,
    };

    let content = String::from("ttt is a new media: there is only ttt");
    let mut cntr = 0;
    let res = PatchFile::apply_patch(content, &PathBuf::from("."), &patch, &mut cntr)?;
    assert_eq!(res, Some(String::from("ttt is a new media: there is only yyy")));
    assert_eq!(cntr, 1);

    Ok(())
  }

  #[test]
  fn find_v2() -> anyhow::Result<()> {
    let patch = Patch {
      files: vec![],
      patch_area: vec![AreaRule::After(RegexIR::new("media")?)],
      replace: None,
      insert: Some(String::from(" v2")),
      decoder: None,
      encoder: None,
    };

    let content = String::from("ttt is a new media: there is only ttt");
    let mut cntr = 0;
    let res = PatchFile::apply_patch(content, &PathBuf::from("."), &patch, &mut cntr)?;
    assert_eq!(res, Some(String::from("ttt is a new media v2: there is only ttt")));
    assert_eq!(cntr, 1);

    Ok(())
  }

  #[test]
  fn find_v3() -> anyhow::Result<()> {
    let patch = Patch {
      files: vec![],
      patch_area: vec![AreaRule::Before(RegexIR::new("media")?)],
      replace: None,
      insert: Some(String::from("v2 ")),
      decoder: None,
      encoder: None,
    };

    let content = String::from("ttt is a new media: there is only ttt");
    let mut cntr = 0;
    let res = PatchFile::apply_patch(content, &PathBuf::from("."), &patch, &mut cntr)?;
    assert_eq!(res, Some(String::from("ttt is a new v2 media: there is only ttt")));
    assert_eq!(cntr, 1);

    Ok(())
  }

  #[test]
  fn find_v4() -> anyhow::Result<()> {
    let patch = Patch {
      files: vec![],
      patch_area: vec![
        AreaRule::Before(RegexIR::new(": there")?),
        AreaRule::After(RegexIR::new("new ")?),
        AreaRule::FindBySh(PathBuf::from("tests/test_v4.py")),
      ],
      replace: None,
      insert: Some(String::from(" v2")),
      decoder: None,
      encoder: None,
    };

    let content = String::from("ttt is a new media: there is only ttt");
    let mut cntr = 0;
    let res = PatchFile::apply_patch(content, &PathBuf::from("."), &patch, &mut cntr)?;
    assert_eq!(res, Some(String::from("ttt is a new media v2: there is only ttt")));
    assert_eq!(cntr, 1);

    Ok(())
  }

  #[test]
  fn find_v5() -> anyhow::Result<()> {
    let patch = Patch {
      files: vec![FilePath::Just(PathBuf::from("test_v5.docx"))],
      patch_area: vec![],
      replace: Some(Replacer::FromTo("game".to_string(), "rock".to_string())),
      insert: None,
      decoder: Some(DecodeBy::Sh(PathBuf::from("tests/test_v5.py"))),
      encoder: Some(EncodeBy::Sh(PathBuf::from("tests/test_v5.py"))),
    };

    let pf = PatchFile { patches: vec![patch] };
    let cntr = pf.patch(&PathBuf::from("tests"), &PathBuf::from("."))?;

    assert_eq!(cntr, 1);

    Ok(())
  }

  #[test]
  fn find_v6() -> anyhow::Result<()> {
    let patch = Patch {
      files: vec![],
      patch_area: vec![
        AreaRule::Before(RegexIR::new(": there")?),
        AreaRule::After(RegexIR::new("new ")?),
        AreaRule::FindByLua(PathBuf::from("tests/test_v6.lua")),
      ],
      replace: None,
      insert: Some(String::from(" v2")),
      decoder: None,
      encoder: None,
    };

    let content = String::from("ttt is a new media: there is only ttt");
    let mut cntr = 0;
    let res = PatchFile::apply_patch(content, &PathBuf::from("."), &patch, &mut cntr)?;
    assert_eq!(res, Some(String::from("ttt is a new media v2: there is only ttt")));
    assert_eq!(cntr, 1);

    Ok(())
  }

  #[test]
  fn find_v7() -> anyhow::Result<()> {
    let patch = Patch {
      files: vec![],
      patch_area: vec![
        AreaRule::Before(RegexIR::new(": there")?),
        AreaRule::After(RegexIR::new("new ")?),
        AreaRule::FindByRhai(PathBuf::from("tests/test_v7.rhai")),
      ],
      replace: None,
      insert: Some(String::from(" v2")),
      decoder: None,
      encoder: None,
    };

    let content = String::from("ttt is a new media: there is only ttt");
    let mut cntr = 0;
    let res = PatchFile::apply_patch(content, &PathBuf::from("."), &patch, &mut cntr)?;
    assert_eq!(res, Some(String::from("ttt is a new media v2: there is only ttt")));
    assert_eq!(cntr, 1);

    Ok(())
  }

  #[test]
  fn find_v8() -> anyhow::Result<()> {
    let patch = Patch {
      files: vec![],
      patch_area: vec![],
      replace: Some(Replacer::BySh(PathBuf::from("tests/test_v8.py"))),
      insert: None,
      decoder: None,
      encoder: None,
    };

    let content = String::from("This is my number: +18235123154");
    let mut cntr = 0;
    let res = PatchFile::apply_patch(content, &PathBuf::from("."), &patch, &mut cntr)?;
    assert_eq!(res, Some(String::from("This is my number: +28235223254")));
    assert_eq!(cntr, 1);

    Ok(())
  }

  #[test]
  fn find_v9() -> anyhow::Result<()> {
    let patch = Patch {
      files: vec![],
      patch_area: vec![],
      replace: Some(Replacer::BySh(PathBuf::from("tests/test_v9.py"))),
      insert: None,
      decoder: None,
      encoder: None,
    };

    let content = String::from("This is my project name: {1}");
    let mut cntr = 0;
    let res = PatchFile::apply_patch(content, &PathBuf::from("."), &patch, &mut cntr)?;
    assert_eq!(res, Some(String::from("This is my project name: smart-patcher")));
    assert_eq!(cntr, 1);

    Ok(())
  }

  #[test]
  fn find_v10() -> anyhow::Result<()> {
    let patch = Patch {
      files: vec![],
      patch_area: vec![
        AreaRule::Before(RegexIR::new(": there")?),
        AreaRule::After(RegexIR::new("new ")?),
        AreaRule::CursorAtEnd,
      ],
      replace: None,
      insert: Some(String::from(" v2")),
      decoder: None,
      encoder: None,
    };

    let content = String::from("ttt is a new media: there is only ttt");
    let mut cntr = 0;
    let res = PatchFile::apply_patch(content, &PathBuf::from("."), &patch, &mut cntr)?;
    assert_eq!(res, Some(String::from("ttt is a new media v2: there is only ttt")));
    assert_eq!(cntr, 1);

    Ok(())
  }
}

#[cfg(feature = "generate-examples")]
#[allow(dead_code)]
/// Generates some examples for `smart-patcher`.
pub fn generate_examples() -> anyhow::Result<()> {
  use std::io::BufWriter;

  if !PathBuf::from("examples").exists() {
    fs::create_dir("examples")?;
  }

  let patch = Patch {
    files: vec![FilePath::Re(RegexIR::new("\\./tests/.*")?)],
    patch_area: vec![AreaRule::After(RegexIR::new("media")?)],
    replace: Some(Replacer::FromTo(String::from("ttt"), String::from("yyy"))),
    insert: None,
    decoder: None,
    encoder: None,
  };
  let pf = PatchFile { patches: vec![patch] };
  let f = File::create("examples/patch1.json")?;
  let buf = BufWriter::new(f);
  serde_json::to_writer_pretty(buf, &pf)?;

  let patch = Patch {
    files: vec![FilePath::Re(RegexIR::new("\\./tests/.*")?)],
    patch_area: vec![AreaRule::After(RegexIR::new("media")?)],
    replace: None,
    insert: Some(String::from(" v2")),
    decoder: None,
    encoder: None,
  };
  let pf = PatchFile { patches: vec![patch] };
  let f = File::create("examples/patch2.json")?;
  let buf = BufWriter::new(f);
  serde_json::to_writer_pretty(buf, &pf)?;

  let patch = Patch {
    files: vec![FilePath::Re(RegexIR::new("\\./tests/.*")?)],
    patch_area: vec![AreaRule::Before(RegexIR::new("media")?)],
    replace: None,
    insert: Some(String::from("v2 ")),
    decoder: None,
    encoder: None,
  };
  let pf = PatchFile { patches: vec![patch] };
  let f = File::create("examples/patch3.json")?;
  let buf = BufWriter::new(f);
  serde_json::to_writer_pretty(buf, &pf)?;

  let patch = Patch {
    files: vec![FilePath::Re(RegexIR::new("\\./tests/.*")?)],
    patch_area: vec![
      AreaRule::Before(RegexIR::new(": there")?),
      AreaRule::After(RegexIR::new("new ")?),
      AreaRule::FindBySh(PathBuf::from("tests/test_v4.py")),
    ],
    replace: None,
    insert: Some(String::from(" v2")),
    decoder: None,
    encoder: None,
  };
  let pf = PatchFile { patches: vec![patch] };
  let f = File::create("examples/patch4.json")?;
  let buf = BufWriter::new(f);
  serde_json::to_writer_pretty(buf, &pf)?;

  let patch = Patch {
    files: vec![FilePath::Just(PathBuf::from("test_v5.docx"))],
    patch_area: vec![],
    replace: Some(Replacer::FromTo("game".to_string(), "rock".to_string())),
    insert: None,
    decoder: Some(DecodeBy::Sh(PathBuf::from("tests/test_v5.py"))),
    encoder: Some(EncodeBy::Sh(PathBuf::from("tests/test_v5.py"))),
  };
  let pf = PatchFile { patches: vec![patch] };
  let f = File::create("examples/patch5.json")?;
  let buf = BufWriter::new(f);
  serde_json::to_writer_pretty(buf, &pf)?;

  let patch = Patch {
    files: vec![FilePath::Re(RegexIR::new("\\./tests/.*")?)],
    patch_area: vec![
      AreaRule::Before(RegexIR::new(": there")?),
      AreaRule::After(RegexIR::new("new ")?),
      AreaRule::FindByLua(PathBuf::from("tests/test_v6.lua")),
    ],
    replace: None,
    insert: Some(String::from(" v2")),
    decoder: None,
    encoder: None,
  };
  let pf = PatchFile { patches: vec![patch] };
  let f = File::create("examples/patch6.json")?;
  let buf = BufWriter::new(f);
  serde_json::to_writer_pretty(buf, &pf)?;

  let patch = Patch {
    files: vec![FilePath::Re(RegexIR::new("\\./tests/.*")?)],
    patch_area: vec![
      AreaRule::Before(RegexIR::new(": there")?),
      AreaRule::After(RegexIR::new("new ")?),
      AreaRule::FindByRhai(PathBuf::from("tests/test_v7.rhai")),
    ],
    replace: None,
    insert: Some(String::from(" v2")),
    decoder: None,
    encoder: None,
  };
  let pf = PatchFile { patches: vec![patch] };
  let f = File::create("examples/patch7.json")?;
  let buf = BufWriter::new(f);
  serde_json::to_writer_pretty(buf, &pf)?;

  let patch = Patch {
    files: vec![FilePath::Re(RegexIR::new("\\./tests/.*")?)],
    patch_area: vec![],
    replace: Some(Replacer::BySh(PathBuf::from("tests/test_v8.py"))),
    insert: None,
    decoder: None,
    encoder: None,
  };
  let pf = PatchFile { patches: vec![patch] };
  let f = File::create("examples/patch8.json")?;
  let buf = BufWriter::new(f);
  serde_json::to_writer_pretty(buf, &pf)?;

  let patch = Patch {
    files: vec![FilePath::Re(RegexIR::new("\\./tests/.*")?)],
    patch_area: vec![],
    replace: Some(Replacer::BySh(PathBuf::from("tests/test_v9.py"))),
    insert: None,
    decoder: None,
    encoder: None,
  };
  let pf = PatchFile { patches: vec![patch] };
  let f = File::create("examples/patch9.json")?;
  let buf = BufWriter::new(f);
  serde_json::to_writer_pretty(buf, &pf)?;

  let patch = Patch {
    files: vec![FilePath::Re(RegexIR::new("\\./tests/.*")?)],
    patch_area: vec![
      AreaRule::Before(RegexIR::new(": there")?),
      AreaRule::After(RegexIR::new("new ")?),
      AreaRule::CursorAtEnd,
    ],
    replace: None,
    insert: Some(String::from(" v2")),
    decoder: None,
    encoder: None,
  };
  let pf = PatchFile { patches: vec![patch] };
  let f = File::create("examples/patch10.json")?;
  let buf = BufWriter::new(f);
  serde_json::to_writer_pretty(buf, &pf)?;

  Ok(())
}