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
// Copyright Kitware, Inc.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use derive_builder::Builder;
use git_checks_core::impl_prelude::*;
use lazy_static::lazy_static;
use regex::Regex;

/// A check which denies paths which look like merge conflict resolution paths.
///
/// Sometimes after a merge, the files written to assist in resolving the conflict will be added
/// accidentally.
#[derive(Builder, Debug, Clone, Copy)]
#[builder(field(private))]
pub struct RejectConflictPaths {
    /// Require that the base file exist for the check to enforce paths.
    ///
    /// If the base exists, then the conflict path patterns will always fire. However, this misses
    /// the case where the base file was deleted and the conflict files left behind. Passing `true`
    /// here rejects any path matching the conflict patterns.
    ///
    /// Configuration: Optional
    /// Default: `true`
    #[builder(default = "true")]
    require_base_exist: bool,
}

lazy_static! {
    static ref CONFLICT_FILE_PATH: Regex = Regex::new(
        "^(?P<base>.*)\
         (?P<kind>_(BACKUP|BASE|LOCAL|REMOTE))\
         (?P<pid>_[0-9]+)\
         (?P<ext>(\\..*)?)$",
    )
    .unwrap();
}
const ORIG_SUFFIX: &str = ".orig";

impl RejectConflictPaths {
    /// Create a new builder.
    pub fn builder() -> RejectConflictPathsBuilder {
        RejectConflictPathsBuilder::default()
    }

    fn check_conflict_path_name(
        self,
        ctx: &CheckGitContext,
        path: &str,
    ) -> Result<bool, CommitError> {
        if let Some(file_path) = CONFLICT_FILE_PATH.captures(path) {
            if !self.require_base_exist {
                return Ok(true);
            }

            let base = file_path
                .name("base")
                .expect("the conflict file path regex should have a 'base' group");
            let ext = file_path
                .name("ext")
                .expect("the conflict file path regex should have a 'ext' group");

            let basepath = format!("{}{}", base.as_str(), ext.as_str());
            Self::check_for_path(ctx, &basepath)
        } else {
            Ok(false)
        }
    }

    fn check_orig_path_name(self, ctx: &CheckGitContext, path: &str) -> Result<bool, CommitError> {
        if path.ends_with(ORIG_SUFFIX) {
            if !self.require_base_exist {
                return Ok(true);
            }

            let basepath = path.trim_end_matches(ORIG_SUFFIX);
            Self::check_for_path(ctx, basepath)
        } else {
            Ok(false)
        }
    }

    fn check_for_path(ctx: &CheckGitContext, path: &str) -> Result<bool, CommitError> {
        let cat_file = ctx
            .git()
            .arg("cat-file")
            .arg("-e")
            .arg(format!(":{}", path))
            .output()
            .map_err(|err| GitError::subcommand("cat-file -e", err))?;
        Ok(cat_file.status.success())
    }
}

impl Default for RejectConflictPaths {
    fn default() -> Self {
        RejectConflictPaths {
            require_base_exist: true,
        }
    }
}

impl ContentCheck for RejectConflictPaths {
    fn name(&self) -> &str {
        "reject-conflict-paths"
    }

    fn check(
        &self,
        ctx: &CheckGitContext,
        content: &dyn Content,
    ) -> Result<CheckResult, Box<dyn Error>> {
        let mut result = CheckResult::new();

        for diff in content.diffs() {
            match diff.status {
                StatusChange::Added | StatusChange::Modified(_) => (),
                _ => continue,
            }

            if self.check_conflict_path_name(ctx, diff.name.as_str())? {
                result.add_error(format!(
                    "{}it appears as though `{}` is a merge conflict resolution file and cannot \
                     be added.",
                    commit_prefix_str(content, "not allowed;"),
                    diff.name,
                ));
            }

            if self.check_orig_path_name(ctx, diff.name.as_str())? {
                result.add_error(format!(
                    "{}it appears as though `{}` is a merge conflict backup file and cannot be \
                     added.",
                    commit_prefix_str(content, "not allowed;"),
                    diff.name,
                ));
            }
        }

        Ok(result)
    }
}

#[cfg(feature = "config")]
pub(crate) mod config {
    use git_checks_config::{register_checks, CommitCheckConfig, IntoCheck, TopicCheckConfig};
    use serde::Deserialize;
    #[cfg(test)]
    use serde_json::json;

    use crate::RejectConflictPaths;

    /// Configuration for the `CheckEndOfLine` check.
    ///
    /// No configuration available.
    ///
    /// This check is registered as a commit check with the name `"check_end_of_line"` and a topic
    /// check with the name `"check_end_of_line/topic"`.
    #[derive(Deserialize, Debug)]
    pub struct RejectConflictPathsConfig {
        #[serde(default)]
        require_base_exist: Option<bool>,
    }

    impl IntoCheck for RejectConflictPathsConfig {
        type Check = RejectConflictPaths;

        fn into_check(self) -> Self::Check {
            let mut builder = RejectConflictPaths::builder();

            if let Some(require_base_exist) = self.require_base_exist {
                builder.require_base_exist(require_base_exist);
            }

            builder
                .build()
                .expect("configuration mismatch for `RejectConflictPaths`")
        }
    }

    register_checks! {
        RejectConflictPathsConfig {
            "reject_conflict_paths" => CommitCheckConfig,
            "reject_conflict_paths/topic" => TopicCheckConfig,
        },
    }

    #[test]
    fn test_reject_conflict_paths_config_empty() {
        let json = json!({});
        let check: RejectConflictPathsConfig = serde_json::from_value(json).unwrap();

        assert_eq!(check.require_base_exist, None);

        let check = check.into_check();

        assert!(check.require_base_exist);
    }

    #[test]
    fn test_reject_conflict_paths_config_all_fields() {
        let json = json!({
            "require_base_exist": false,
        });
        let check: RejectConflictPathsConfig = serde_json::from_value(json).unwrap();

        assert_eq!(check.require_base_exist, Some(false));

        let check = check.into_check();

        assert!(!check.require_base_exist);
    }
}

#[cfg(test)]
mod tests {
    use git_checks_core::{Check, TopicCheck};

    use crate::test::*;
    use crate::RejectConflictPaths;

    const MERGE_CONFLICT_NO_BASE: &str = "52710df4a433731545ef99440edeb431b3160fc6";
    const MERGE_CONFLICT_ORIG_NO_BASE: &str = "672a6a32b045bec6f93b9b1b5252611f40437a07";
    const DELETE_CONFLICT_NO_BASE: &str = "7ed69370ce3ba45bca9c4565d142b81685088247";

    const MERGE_CONFLICT_NO_EXT: &str = "f31b2e2cb75083d174097db7054cbc9e5836bad7";
    const MERGE_CONFLICT_WITH_EXT: &str = "59f02bdb6c404c8f7cfb32700645c149148c089b";
    const MERGE_CONFLICT_TWO_EXT: &str = "e9421eadfcac3c67a090444ef2ac859e86a8a2e0";
    const MERGE_CONFLICT_ORIG_EXT: &str = "4abcf323b81c757e668ce1936f475b085d6852e8";

    const MERGE_CONFLICT_NO_EXT_FIXED: &str = "63c923b5be729f672eddcd4b1e979a7d3d22606f";
    const MERGE_CONFLICT_WITH_EXT_FIXED: &str = "8fcdd0d920ef47d0294229fdad4b3abd3ebdc43b";
    const MERGE_CONFLICT_TWO_EXT_FIXED: &str = "0bf291f1f8a320abfb63776c56e1d1497231e24e";
    const MERGE_CONFLICT_ORIG_EXT_FIXED: &str = "e1fd80490cd7f6556120aad6309d8fb95818b6ef";

    #[test]
    fn test_reject_conflict_paths_builder_default() {
        assert!(RejectConflictPaths::builder().build().is_ok());
    }

    #[test]
    fn test_reject_conflict_paths_name_commit() {
        let check = RejectConflictPaths::default();
        assert_eq!(Check::name(&check), "reject-conflict-paths");
    }

    #[test]
    fn test_reject_conflict_paths_name_topic() {
        let check = RejectConflictPaths::default();
        assert_eq!(TopicCheck::name(&check), "reject-conflict-paths");
    }

    #[test]
    fn test_reject_conflict_paths_no_base() {
        let check = RejectConflictPaths::default();
        run_check_ok(
            "test_reject_conflict_paths_no_base",
            MERGE_CONFLICT_NO_BASE,
            check,
        );
    }

    #[test]
    fn test_reject_conflict_paths_no_base_topic() {
        let check = RejectConflictPaths::default();
        run_topic_check_ok(
            "test_reject_conflict_paths_no_base_topic",
            MERGE_CONFLICT_NO_BASE,
            check,
        );
    }

    #[test]
    fn test_reject_conflict_paths_no_base_require() {
        let check = RejectConflictPaths::builder()
            .require_base_exist(false)
            .build()
            .unwrap();
        let result = run_check(
            "test_reject_conflict_paths_no_base_require",
            MERGE_CONFLICT_NO_BASE,
            check,
        );
        test_result_errors(result, &[
            "commit 52710df4a433731545ef99440edeb431b3160fc6 not allowed; it appears as though \
             `no_base_BACKUP_12345.ext` is a merge conflict resolution file and cannot be added.",
            "commit 52710df4a433731545ef99440edeb431b3160fc6 not allowed; it appears as though \
             `no_base_BASE_12345.ext` is a merge conflict resolution file and cannot be added.",
            "commit 52710df4a433731545ef99440edeb431b3160fc6 not allowed; it appears as though \
             `no_base_LOCAL_12345.ext` is a merge conflict resolution file and cannot be added.",
            "commit 52710df4a433731545ef99440edeb431b3160fc6 not allowed; it appears as though \
             `no_base_REMOTE_12345.ext` is a merge conflict resolution file and cannot be added.",
        ]);
    }

    #[test]
    fn test_reject_conflict_paths_no_base_require_topic() {
        let check = RejectConflictPaths::builder()
            .require_base_exist(false)
            .build()
            .unwrap();
        let result = run_topic_check(
            "test_reject_conflict_paths_no_base_require_topic",
            MERGE_CONFLICT_NO_BASE,
            check,
        );
        test_result_errors(result, &[
            "it appears as though `no_base_BACKUP_12345.ext` is a merge conflict resolution file \
             and cannot be added.",
            "it appears as though `no_base_BASE_12345.ext` is a merge conflict resolution file \
             and cannot be added.",
            "it appears as though `no_base_LOCAL_12345.ext` is a merge conflict resolution file \
             and cannot be added.",
            "it appears as though `no_base_REMOTE_12345.ext` is a merge conflict resolution file \
             and cannot be added.",
        ]);
    }

    #[test]
    fn test_reject_conflict_paths_orig_no_base() {
        let check = RejectConflictPaths::default();
        run_check_ok(
            "test_reject_conflict_paths_orig_no_base",
            MERGE_CONFLICT_ORIG_NO_BASE,
            check,
        );
    }

    #[test]
    fn test_reject_conflict_paths_orig_no_base_topic() {
        let check = RejectConflictPaths::default();
        run_topic_check_ok(
            "test_reject_conflict_paths_orig_no_base_topic",
            MERGE_CONFLICT_ORIG_NO_BASE,
            check,
        );
    }

    #[test]
    fn test_reject_conflict_paths_delete_file() {
        let check = RejectConflictPaths::builder()
            .require_base_exist(false)
            .build()
            .unwrap();
        let conf = make_check_conf(&check);

        let result = test_check_base(
            "test_reject_conflict_paths_delete_file",
            DELETE_CONFLICT_NO_BASE,
            MERGE_CONFLICT_NO_BASE,
            &conf,
        );
        test_result_ok(result);
    }

    #[test]
    fn test_reject_conflict_paths_delete_file_topic() {
        let check = RejectConflictPaths::builder()
            .require_base_exist(false)
            .build()
            .unwrap();
        run_topic_check_ok(
            "test_reject_conflict_paths_delete_file_topic",
            DELETE_CONFLICT_NO_BASE,
            check,
        );
    }

    #[test]
    fn test_reject_conflict_paths_orig_no_base_require() {
        let check = RejectConflictPaths::builder()
            .require_base_exist(false)
            .build()
            .unwrap();
        let result = run_check(
            "test_reject_conflict_paths_orig_no_base_require",
            MERGE_CONFLICT_ORIG_NO_BASE,
            check,
        );
        test_result_errors(result, &[
            "commit 672a6a32b045bec6f93b9b1b5252611f40437a07 not allowed; it appears as though \
             `orig_file_valid.orig` is a merge conflict backup file and cannot be added.",
        ]);
    }

    #[test]
    fn test_reject_conflict_paths_orig_no_base_require_topic() {
        let check = RejectConflictPaths::builder()
            .require_base_exist(false)
            .build()
            .unwrap();
        let result = run_topic_check(
            "test_reject_conflict_paths_orig_no_base_require_topic",
            MERGE_CONFLICT_ORIG_NO_BASE,
            check,
        );
        test_result_errors(
            result,
            &[
                "it appears as though `orig_file_valid.orig` is a merge conflict backup file and \
                 cannot be added.",
            ],
        );
    }

    #[test]
    fn test_reject_conflict_paths_no_ext() {
        let check = RejectConflictPaths::default();
        let result = run_check(
            "test_reject_conflict_paths_no_ext",
            MERGE_CONFLICT_NO_EXT,
            check,
        );
        test_result_errors(result, &[
            "commit f31b2e2cb75083d174097db7054cbc9e5836bad7 not allowed; it appears as though \
             `no_ext_BACKUP_12345` is a merge conflict resolution file and cannot be added.",
            "commit f31b2e2cb75083d174097db7054cbc9e5836bad7 not allowed; it appears as though \
             `no_ext_BASE_12345` is a merge conflict resolution file and cannot be added.",
            "commit f31b2e2cb75083d174097db7054cbc9e5836bad7 not allowed; it appears as though \
             `no_ext_LOCAL_12345` is a merge conflict resolution file and cannot be added.",
            "commit f31b2e2cb75083d174097db7054cbc9e5836bad7 not allowed; it appears as though \
             `no_ext_REMOTE_12345` is a merge conflict resolution file and cannot be added.",
        ]);
    }

    #[test]
    fn test_reject_conflict_paths_no_ext_topic() {
        let check = RejectConflictPaths::default();
        let result = run_topic_check(
            "test_reject_conflict_paths_no_ext_topic",
            MERGE_CONFLICT_NO_EXT,
            check,
        );
        test_result_errors(result, &[
            "it appears as though `no_ext_BACKUP_12345` is a merge conflict resolution file and \
             cannot be added.",
            "it appears as though `no_ext_BASE_12345` is a merge conflict resolution file and \
             cannot be added.",
            "it appears as though `no_ext_LOCAL_12345` is a merge conflict resolution file and \
             cannot be added.",
            "it appears as though `no_ext_REMOTE_12345` is a merge conflict resolution file and \
             cannot be added.",
        ]);
    }

    #[test]
    fn test_reject_conflict_paths_no_ext_topic_fixed() {
        let check = RejectConflictPaths::default();
        run_topic_check_ok(
            "test_reject_conflict_paths_no_ext_topic_fixed",
            MERGE_CONFLICT_NO_EXT_FIXED,
            check,
        );
    }

    #[test]
    fn test_reject_conflict_paths_with_ext() {
        let check = RejectConflictPaths::default();
        let result = run_check(
            "test_reject_conflict_paths_with_ext",
            MERGE_CONFLICT_WITH_EXT,
            check,
        );
        test_result_errors(result, &[
            "commit 59f02bdb6c404c8f7cfb32700645c149148c089b not allowed; it appears as though \
             `conflict_with_BACKUP_12345.ext` is a merge conflict resolution file and cannot be \
             added.",
            "commit 59f02bdb6c404c8f7cfb32700645c149148c089b not allowed; it appears as though \
             `conflict_with_BASE_12345.ext` is a merge conflict resolution file and cannot be \
             added.",
            "commit 59f02bdb6c404c8f7cfb32700645c149148c089b not allowed; it appears as though \
             `conflict_with_LOCAL_12345.ext` is a merge conflict resolution file and cannot be \
             added.",
            "commit 59f02bdb6c404c8f7cfb32700645c149148c089b not allowed; it appears as though \
             `conflict_with_REMOTE_12345.ext` is a merge conflict resolution file and cannot be \
             added.",
        ]);
    }

    #[test]
    fn test_reject_conflict_paths_with_ext_topic() {
        let check = RejectConflictPaths::default();
        let result = run_topic_check(
            "test_reject_conflict_paths_with_ext_topic",
            MERGE_CONFLICT_WITH_EXT,
            check,
        );
        test_result_errors(result, &[
            "it appears as though `conflict_with_BACKUP_12345.ext` is a merge conflict resolution \
             file and cannot be added.",
            "it appears as though `conflict_with_BASE_12345.ext` is a merge conflict resolution \
             file and cannot be added.",
            "it appears as though `conflict_with_LOCAL_12345.ext` is a merge conflict resolution \
             file and cannot be added.",
            "it appears as though `conflict_with_REMOTE_12345.ext` is a merge conflict resolution \
             file and cannot be added.",
        ]);
    }

    #[test]
    fn test_reject_conflict_paths_with_ext_topic_fixed() {
        let check = RejectConflictPaths::default();
        run_topic_check_ok(
            "test_reject_conflict_paths_with_ext_topic_fixed",
            MERGE_CONFLICT_WITH_EXT_FIXED,
            check,
        );
    }

    #[test]
    fn test_reject_conflict_paths_two_ext() {
        let check = RejectConflictPaths::default();
        let result = run_check(
            "test_reject_conflict_paths_two_ext",
            MERGE_CONFLICT_TWO_EXT,
            check,
        );
        test_result_errors(result, &[
            "commit e9421eadfcac3c67a090444ef2ac859e86a8a2e0 not allowed; it appears as though \
             `conflict_with.two_BACKUP_12345.ext` is a merge conflict resolution file and cannot \
             be added.",
            "commit e9421eadfcac3c67a090444ef2ac859e86a8a2e0 not allowed; it appears as though \
             `conflict_with.two_BASE_12345.ext` is a merge conflict resolution file and cannot be \
             added.",
            "commit e9421eadfcac3c67a090444ef2ac859e86a8a2e0 not allowed; it appears as though \
             `conflict_with.two_LOCAL_12345.ext` is a merge conflict resolution file and cannot be \
             added.",
            "commit e9421eadfcac3c67a090444ef2ac859e86a8a2e0 not allowed; it appears as though \
             `conflict_with.two_REMOTE_12345.ext` is a merge conflict resolution file and cannot \
             be added.",
        ]);
    }

    #[test]
    fn test_reject_conflict_paths_two_ext_topic() {
        let check = RejectConflictPaths::default();
        let result = run_topic_check(
            "test_reject_conflict_paths_two_ext_topic",
            MERGE_CONFLICT_TWO_EXT,
            check,
        );
        test_result_errors(
            result,
            &[
                "it appears as though `conflict_with.two_BACKUP_12345.ext` is a merge conflict \
                 resolution file and cannot be added.",
                "it appears as though `conflict_with.two_BASE_12345.ext` is a merge conflict \
                 resolution file and cannot be added.",
                "it appears as though `conflict_with.two_LOCAL_12345.ext` is a merge conflict \
                 resolution file and cannot be added.",
                "it appears as though `conflict_with.two_REMOTE_12345.ext` is a merge conflict \
                 resolution file and cannot be added.",
            ],
        );
    }

    #[test]
    fn test_reject_conflict_paths_two_ext_topic_fixed() {
        let check = RejectConflictPaths::default();
        run_topic_check_ok(
            "test_reject_conflict_paths_two_ext_topic_fixed",
            MERGE_CONFLICT_TWO_EXT_FIXED,
            check,
        );
    }

    #[test]
    fn test_reject_conflict_paths_orig_ext() {
        let check = RejectConflictPaths::default();
        let result = run_check(
            "test_reject_conflict_paths_orig_ext",
            MERGE_CONFLICT_ORIG_EXT,
            check,
        );
        test_result_errors(result, &[
            "commit 4abcf323b81c757e668ce1936f475b085d6852e8 not allowed; it appears as though \
             `orig_file.ext.orig` is a merge conflict backup file and cannot be added.",
        ]);
    }

    #[test]
    fn test_reject_conflict_paths_orig_ext_topic() {
        let check = RejectConflictPaths::default();
        let result = run_topic_check(
            "test_reject_conflict_paths_orig_ext_topic",
            MERGE_CONFLICT_ORIG_EXT,
            check,
        );
        test_result_errors(result, &[
            "it appears as though `orig_file.ext.orig` is a merge conflict backup file and cannot \
             be added.",
        ]);
    }

    #[test]
    fn test_reject_conflict_paths_orig_ext_topic_fixed() {
        let check = RejectConflictPaths::default();
        run_topic_check_ok(
            "test_reject_conflict_paths_orig_ext_topic_fixed",
            MERGE_CONFLICT_ORIG_EXT_FIXED,
            check,
        );
    }
}