git-checks-core 1.4.0

Checks to run against a topic in git to enforce coding standards.
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
// 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 std::error::Error;
use std::fmt::Debug;

use git_workarea::CommitId;

use crate::commit::{Commit, Content, Topic};
use crate::context::CheckGitContext;

/// The results of a check.
#[derive(Debug, Default, Clone)]
pub struct CheckResult {
    /// The warnings from running checks.
    warnings: Vec<String>,
    /// The alerts from running checks.
    ///
    /// These are meant to be directed towards administrators of the repository.
    alerts: Vec<String>,
    /// The errors from running checks.
    ///
    /// Errors cause the checks to be in a "failed" state.
    errors: Vec<String>,

    /// Whether any messages may be temporary.
    temporary: bool,
    /// Whether errors should be ignored or not.
    allow: bool,
    /// Whether the checks succeeded or not.
    pass: bool,
}

/// The severity of a message.
pub enum Severity {
    /// The message is a warning.
    Warning,
    /// The message is an error.
    Error,
    /// The message should be brought to the attention of project maintainers.
    Alert {
        /// Whether the checks should fail due to the message or not.
        blocking: bool,
    },
}

impl CheckResult {
    /// Create a new results structure.
    pub fn new() -> Self {
        Self {
            warnings: Vec::new(),
            alerts: Vec::new(),
            errors: Vec::new(),

            temporary: false,
            allow: false,
            pass: true,
        }
    }

    /// Add a message to the result.
    pub fn add_message<S>(&mut self, severity: Severity, message: S) -> &mut Self
    where
        S: Into<String>,
    {
        match severity {
            Severity::Warning => &mut self.warnings,
            Severity::Error => {
                self.pass = false;
                &mut self.errors
            },
            Severity::Alert {
                blocking,
            } => {
                if blocking {
                    self.pass = false;
                }
                &mut self.alerts
            },
        }
        .push(message.into());

        self
    }

    /// Adds a warning message to the results.
    pub fn add_warning<S: Into<String>>(&mut self, warning: S) -> &mut Self {
        self.add_message(Severity::Warning, warning.into())
    }

    /// Adds an alert to the results.
    ///
    /// These messages should be brought to the attention of those maintaining the deployment of
    /// the checks.
    pub fn add_alert<S: Into<String>>(&mut self, alert: S, should_block: bool) -> &mut Self {
        self.add_message(
            Severity::Alert {
                blocking: should_block,
            },
            alert.into(),
        )
    }

    /// Adds a error message to the results.
    ///
    /// Also marks the checks as having failed.
    pub fn add_error<S: Into<String>>(&mut self, error: S) -> &mut Self {
        self.add_message(Severity::Error, error.into())
    }

    /// Indicates that there are messages which may be temporary.
    pub fn make_temporary(&mut self) -> &mut Self {
        self.temporary = true;

        self
    }

    /// Allows the checks to pass no matter what.
    pub fn whitelist(&mut self) -> &mut Self {
        self.allow = true;

        self
    }

    /// The warnings from the checks.
    pub fn warnings(&self) -> &Vec<String> {
        &self.warnings
    }

    /// The alerts from the checks.
    pub fn alerts(&self) -> &Vec<String> {
        &self.alerts
    }

    /// The errors from the checks.
    pub fn errors(&self) -> &Vec<String> {
        &self.errors
    }

    /// Whether there are temporary messages or not.
    pub fn temporary(&self) -> bool {
        self.temporary
    }

    /// Whether the checks will allow the commit no matter what.
    pub fn allowed(&self) -> bool {
        self.allow
    }

    /// Whether the checks passed or failed.
    pub fn pass(&self) -> bool {
        self.pass
    }

    /// Combine two results together.
    pub fn combine(self, other: Self) -> Self {
        Self {
            warnings: self.warnings.into_iter().chain(other.warnings).collect(),
            alerts: self.alerts.into_iter().chain(other.alerts).collect(),
            errors: self.errors.into_iter().chain(other.errors).collect(),

            temporary: self.temporary || other.temporary,
            allow: self.allow || other.allow,
            pass: self.pass && other.pass,
        }
    }
}

/// Interface for checks which run for each commit.
pub trait Check: Debug + Send + Sync {
    /// The name of the check.
    fn name(&self) -> &str;

    /// Run the check.
    fn check(&self, ctx: &CheckGitContext, commit: &Commit) -> Result<CheckResult, Box<dyn Error>>;
}

/// Interface for checks which runs once for the entire branch.
///
/// This is intended for checks which do not need to check the content, but instead, look at
/// metadata such as the author or the topology of the branch.
pub trait BranchCheck: Debug + Send + Sync {
    /// The name of the check.
    fn name(&self) -> &str;

    /// Run the check.
    fn check(
        &self,
        ctx: &CheckGitContext,
        commit: &CommitId,
    ) -> Result<CheckResult, Box<dyn Error>>;
}

/// Interface for checks which runs once for the entire branch, but with access to the content.
///
/// These checks are given the content of the entire topic against a base branch to check.
pub trait TopicCheck: Debug + Send + Sync {
    /// The name of the check.
    fn name(&self) -> &str;

    /// Run the check.
    fn check(&self, ctx: &CheckGitContext, topic: &Topic) -> Result<CheckResult, Box<dyn Error>>;
}

/// Interface for checks which check the content of files.
///
/// These checks are not given any metadata, but only information about the content of a commit or
/// topic.
pub trait ContentCheck: Debug + Send + Sync {
    /// The name of the check.
    fn name(&self) -> &str;

    /// Run the check.
    fn check(
        &self,
        ctx: &CheckGitContext,
        content: &dyn Content,
    ) -> Result<CheckResult, Box<dyn Error>>;
}

impl<T> Check for T
where
    T: ContentCheck,
{
    fn name(&self) -> &str {
        self.name()
    }

    fn check(&self, ctx: &CheckGitContext, commit: &Commit) -> Result<CheckResult, Box<dyn Error>> {
        self.check(ctx, commit)
    }
}

impl<T> TopicCheck for T
where
    T: ContentCheck,
{
    fn name(&self) -> &str {
        self.name()
    }

    fn check(&self, ctx: &CheckGitContext, topic: &Topic) -> Result<CheckResult, Box<dyn Error>> {
        self.check(ctx, topic)
    }
}

#[cfg(test)]
mod tests {
    use crate::CheckResult;

    #[test]
    fn test_check_result_add_warning() {
        let mut result = CheckResult::new();
        assert!(result.warnings().is_empty());
        result.add_warning("warning");
        assert!(!result.warnings().is_empty());
    }

    #[test]
    fn test_check_result_add_error() {
        let mut result = CheckResult::new();
        assert!(result.errors().is_empty());
        result.add_error("error");
        assert!(!result.errors().is_empty());
    }

    #[test]
    fn test_check_result_add_alert() {
        let mut result = CheckResult::new();
        assert!(result.alerts().is_empty());
        result.add_alert("error", true);
        assert!(!result.alerts().is_empty());
    }

    #[test]
    fn test_check_result_make_temporary() {
        let mut result = CheckResult::new();
        assert!(!result.temporary());
        result.make_temporary();
        assert!(result.temporary());
    }

    #[test]
    fn test_check_result_whitelist() {
        let mut result = CheckResult::new();
        assert!(!result.allowed());
        result.whitelist();
        assert!(result.allowed());
    }

    #[test]
    fn test_check_result_combine_temporary() {
        let temp_result = {
            let mut result = CheckResult::new();
            result.make_temporary();
            result
        };
        let non_temp_result = CheckResult::new();

        let items = &[
            (&temp_result, &non_temp_result, true),
            (&temp_result, &temp_result, true),
            (&non_temp_result, &non_temp_result, false),
            (&non_temp_result, &temp_result, true),
        ];

        for (l, r, e) in items {
            assert_eq!((**l).clone().combine((**r).clone()).temporary(), *e);
        }
    }

    #[test]
    fn test_check_result_combine_whitelist() {
        let temp_result = {
            let mut result = CheckResult::new();
            result.whitelist();
            result
        };
        let non_temp_result = CheckResult::new();

        let items = &[
            (&temp_result, &non_temp_result, true),
            (&temp_result, &temp_result, true),
            (&non_temp_result, &non_temp_result, false),
            (&non_temp_result, &temp_result, true),
        ];

        for (l, r, e) in items {
            assert_eq!((**l).clone().combine((**r).clone()).allowed(), *e);
        }
    }

    mod mock {
        use std::sync::Mutex;

        use crate::impl_prelude::*;

        #[derive(Debug)]
        pub struct MockCheck {
            checked: Mutex<bool>,
        }

        impl Default for MockCheck {
            fn default() -> Self {
                Self {
                    checked: Mutex::new(false),
                }
            }
        }

        impl Drop for MockCheck {
            fn drop(&mut self) {
                let flag = self.checked.lock().expect("poisoned mock check lock");
                assert!(*flag);
            }
        }

        impl MockCheck {
            fn trip(&self) {
                let mut flag = self.checked.lock().expect("poisoned mock check lock");
                *flag = true;
            }
        }

        impl ContentCheck for MockCheck {
            fn name(&self) -> &str {
                self.trip();
                "mock-check"
            }

            fn check(
                &self,
                _: &CheckGitContext,
                _: &dyn Content,
            ) -> Result<CheckResult, Box<dyn Error>> {
                self.trip();
                Ok(CheckResult::new())
            }
        }
    }

    const TARGET_COMMIT: &str = "27ff3ef5532d76afa046f76f4dd8f588dc3e83c3";
    const SIMPLE_COMMIT: &str = "43adb8173eb6d7a39f98e1ec3351cf27414c9aa1";

    fn test_run_check(conf: &crate::GitCheckConfiguration, name: &str) {
        use std::path::Path;

        use git_workarea::{CommitId, GitContext, Identity};

        let gitdir = Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../.git"));
        if !gitdir.exists() {
            panic!("The tests must be run from a git checkout.");
        }

        let ctx = GitContext::new(gitdir);
        let identity = Identity::new(
            "Rust Git Checks Core Tests",
            "rust-git-checks-core@example.com",
        );
        conf.run_topic(
            &ctx,
            name,
            &CommitId::new(TARGET_COMMIT),
            &CommitId::new(SIMPLE_COMMIT),
            &identity,
        )
        .unwrap();
    }

    #[test]
    fn test_impl_check_for_content_name() {
        use crate::{Check, ContentCheck};

        let check = mock::MockCheck::default();

        assert_eq!(Check::name(&check), ContentCheck::name(&check));
    }

    #[test]
    fn test_impl_check_for_content_check() {
        let check = mock::MockCheck::default();
        let mut conf = crate::GitCheckConfiguration::new();
        conf.add_check(&check);
        test_run_check(&conf, "test_impl_check_for_content_check");
    }

    #[test]
    fn test_impl_topiccheck_for_content_name() {
        use crate::{ContentCheck, TopicCheck};

        let check = mock::MockCheck::default();

        assert_eq!(TopicCheck::name(&check), ContentCheck::name(&check));
    }

    #[test]
    fn test_impl_topiccheck_for_content_check() {
        let check = mock::MockCheck::default();
        let mut conf = crate::GitCheckConfiguration::new();
        conf.add_topic_check(&check);
        test_run_check(&conf, "test_impl_topiccheck_for_content_check");
    }
}