lintje 0.11.3

Lintje is an opinionated linter for Git.
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
use crate::config::ValidationContext;
use crate::issue::Issue;
use crate::rule::{rule_by_name, Rule};

#[derive(Debug)]
pub struct Commit {
    pub long_sha: Option<String>,
    pub short_sha: Option<String>,
    pub email: Option<String>,
    pub subject: String,
    pub message: String,
    pub trailers: String,
    pub file_changes: Vec<String>,
    pub issues: Vec<Issue>,
    pub ignored_rules: Vec<Rule>,
    pub checked_rules: Vec<Rule>,
}

impl Commit {
    pub fn new(
        long_sha: Option<String>,
        email: Option<String>,
        subject: &str,
        message: String,
        trailers: String,
        file_changes: Vec<String>,
    ) -> Self {
        // Get first 7 characters of the commit SHA to get the short SHA.
        let short_sha = match &long_sha {
            Some(long) => match long.get(0..7) {
                Some(sha) => Some(sha.to_string()),
                None => {
                    debug!("Could not determine abbreviated SHA from SHA");
                    None
                }
            },
            None => None,
        };
        let ignored_rules = Self::find_ignored_rules(&message, &trailers);
        Self {
            long_sha,
            short_sha,
            email,
            subject: subject.trim_end().to_string(),
            message,
            trailers,
            file_changes,
            ignored_rules,
            issues: Vec::<Issue>::new(),
            checked_rules: Vec::<Rule>::new(),
        }
    }

    pub fn has_changes(&self) -> bool {
        !self.file_changes.is_empty()
    }

    fn find_ignored_rules(message: &str, trailers: &str) -> Vec<Rule> {
        let mut ignored = vec![];
        ignored.append(&mut Self::find_ignored_rules_for(message));
        ignored.append(&mut Self::find_ignored_rules_for(trailers));
        ignored
    }

    fn find_ignored_rules_for(string: &str) -> Vec<Rule> {
        let disable_prefix = "lintje:disable ";
        let mut ignored = vec![];
        for line in string.lines() {
            if let Some(name) = line.strip_prefix(disable_prefix) {
                match rule_by_name(name) {
                    Some(rule) => ignored.push(rule),
                    None => warn!("Attempted to ignore unknown rule: {}", name),
                }
            }
        }
        ignored
    }

    fn rule_ignored(&self, rule: &Rule) -> bool {
        self.ignored_rules.contains(rule)
    }

    pub fn is_valid(&self) -> bool {
        self.issues.is_empty()
    }

    pub fn validate(&mut self, context: &ValidationContext) {
        self.validate_rule(Rule::MergeCommit);
        self.validate_rule(Rule::RebaseCommit);

        // If a commit has a MergeCommit or RebaseCommit issue, other rules are skipped,
        // because the commit itself will need to be rebased into other commits. So the format
        // of the commit won't matter.
        if !self.has_issue(&Rule::MergeCommit) && !self.has_issue(&Rule::RebaseCommit) {
            self.validate_rule(Rule::SubjectCliche);
            self.validate_rule(Rule::SubjectLength);
            self.validate_rule(Rule::SubjectMood);
            self.validate_rule(Rule::SubjectWhitespace);
            self.validate_rule(Rule::SubjectPrefix);
            self.validate_rule(Rule::SubjectCapitalization);
            self.validate_rule(Rule::SubjectBuildTag);
            self.validate_rule(Rule::SubjectPunctuation);
            self.validate_rule(Rule::SubjectTicketNumber);
            self.validate_rule(Rule::MessageTicketNumber);
            self.validate_rule(Rule::MessageEmptyFirstLine);
            self.validate_rule(Rule::MessagePresence);
            self.validate_rule(Rule::MessageLineLength);
            self.validate_rule(Rule::MessageTrailerLine);
            self.validate_rule(Rule::MessageSkipBuildTag);
            if context.changesets {
                self.validate_rule(Rule::DiffChangeset);
            }
        }
        self.validate_rule(Rule::DiffPresence);
    }

    fn validate_rule(&mut self, rule: Rule) {
        if !self.rule_ignored(&rule) {
            match rule.validate_commit(self) {
                Some(mut issues) => {
                    self.issues.append(&mut issues);
                }
                None => {
                    debug!(
                        "No issues found for commit '{}' in rule '{}'",
                        self.long_sha.as_ref().unwrap_or(&"".to_string()),
                        rule
                    );
                }
            }
        }
        self.checked_rules.push(rule);
    }

    pub fn has_issue(&self, rule: &Rule) -> bool {
        self.issues.iter().any(|issue| &issue.rule == rule)
    }
}

impl std::fmt::Display for Commit {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let trailers = if self.trailers.is_empty() {
            "".to_string()
        } else {
            self.trailers.to_string() + "\n"
        };
        write!(
            f,
            "SHA: {}\n\
            Author: {}\n\
            Subject: {}\n\
            Message: {}\n\
            \n\
            ---\n\
            Trailers:\n\
            {}\
            \n\
            ---\n\
            File changes:\n\
            {}\n\
            \n\
            ---\n\
            Checked rules: {}\n\
            Ignored rules: {}\n\
            Issues: {}\n",
            self.long_sha.as_ref().unwrap_or(&"".to_string()),
            self.email.as_ref().unwrap_or(&"".to_string()),
            self.subject,
            self.message,
            trailers,
            self.file_changes.join("\n"),
            self.checked_rules
                .iter()
                .map(|r| format!("{}", r))
                .collect::<Vec<String>>()
                .join(", "),
            self.ignored_rules
                .iter()
                .map(|r| format!("{}", r))
                .collect::<Vec<String>>()
                .join(", "),
            self.issues
                .iter()
                .map(|i| format!("{}", i.rule))
                .collect::<Vec<String>>()
                .join(", "),
        )
    }
}

#[cfg(test)]
mod tests {
    use super::Commit;
    use crate::config::ValidationContext;
    use crate::rule::Rule;
    use crate::test::*;

    fn default_context() -> ValidationContext {
        ValidationContext { changesets: false }
    }

    #[test]
    fn test_create_short_sha() {
        let long_sha = Some("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_string());
        let with_long_sha = commit_with_sha(long_sha, "Subject".to_string(), "Message".to_string());
        assert_eq!(
            with_long_sha.long_sha,
            Some("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_string())
        );
        assert_eq!(with_long_sha.short_sha, Some("aaaaaaa".to_string()));

        let long_sha = Some("a".to_string());
        let without_long_sha =
            commit_with_sha(long_sha, "Subject".to_string(), "Message".to_string());
        assert_eq!(without_long_sha.long_sha, Some("a".to_string()));
        assert_eq!(without_long_sha.short_sha, None);
    }

    #[test]
    fn trims_subject_end() {
        let commit = commit("This is a subject  ".to_string(), "Message".to_string());
        assert_eq!(commit.subject, "This is a subject");
    }

    #[test]
    fn is_valid() {
        let mut commit = commit("".to_string(), "Intentionally invalid commit".to_string());
        assert!(commit.is_valid());
        commit.validate(&default_context());
        assert!(!commit.is_valid());
    }

    #[test]
    fn check_validated_rules_default() {
        let mut commit = commit("".to_string(), "Intentionally invalid commit".to_string());
        commit.validate(&ValidationContext { changesets: false });
        // Test specific order of rules because they may depend on one another
        assert_eq!(
            commit.checked_rules,
            vec![
                Rule::MergeCommit,
                Rule::RebaseCommit,
                Rule::SubjectCliche,
                Rule::SubjectLength,
                Rule::SubjectMood,
                Rule::SubjectWhitespace,
                Rule::SubjectPrefix,
                Rule::SubjectCapitalization,
                Rule::SubjectBuildTag,
                Rule::SubjectPunctuation,
                Rule::SubjectTicketNumber,
                Rule::MessageTicketNumber,
                Rule::MessageEmptyFirstLine,
                Rule::MessagePresence,
                Rule::MessageLineLength,
                Rule::MessageTrailerLine,
                Rule::MessageSkipBuildTag,
                Rule::DiffPresence
            ]
        );
    }

    #[test]
    fn check_validated_rules_merge_commit() {
        let mut commit = commit(
            "Merge branch 'develop' of github.com/org/repo into develop".to_string(),
            "".to_string(),
        );
        commit.validate(&ValidationContext { changesets: false });
        // Test specific order of rules because they may depend on one another.
        // A lot of rules are skipped for these types of commits because they do not apply.
        assert_eq!(
            commit.checked_rules,
            vec![Rule::MergeCommit, Rule::RebaseCommit, Rule::DiffPresence]
        );
    }

    #[test]
    fn check_validated_rules_fixup_commit() {
        let mut commit = commit("fixup! Some commit".to_string(), "".to_string());
        commit.validate(&ValidationContext { changesets: false });
        // Test specific order of rules because they may depend on one another.
        // A lot of rules are skipped for these types of commits because they do not apply.
        assert_eq!(
            commit.checked_rules,
            vec![Rule::MergeCommit, Rule::RebaseCommit, Rule::DiffPresence]
        );
    }

    #[test]
    fn does_not_validate_changeset_rule_when_changeset_mode_is_false() {
        let mut commit = commit("".to_string(), "Intentionally invalid commit".to_string());
        commit.validate(&ValidationContext { changesets: false });
        assert!(!commit.checked_rules.contains(&Rule::DiffChangeset));
    }

    #[test]
    fn validate_changeset_rule_when_changeset_mode_is_true() {
        let mut commit = commit("".to_string(), "Intentionally invalid commit".to_string());
        commit.validate(&ValidationContext { changesets: true });
        assert!(commit.checked_rules.contains(&Rule::DiffChangeset));
    }

    #[test]
    fn ignored_rule() {
        let mut ignored_rule = commit_with_trailers(
            "".to_string(),
            "...\n\
            lintje:disable SubjectLength\n\
            lintje:disable MessageEmptyFirstLine"
                .to_string(),
            "lintje:disable SubjectCliche\n\
            lintje:disable MessagePresence"
                .to_string(),
        );
        assert_eq!(
            ignored_rule.ignored_rules,
            vec![
                Rule::SubjectLength,
                Rule::MessageEmptyFirstLine,
                Rule::SubjectCliche,
                Rule::MessagePresence
            ]
        );

        ignored_rule.validate(&default_context());
        assert!(!ignored_rule.has_issue(&Rule::SubjectLength));
        assert!(!ignored_rule.has_issue(&Rule::MessageEmptyFirstLine));
    }

    #[test]
    fn display() {
        let mut commit = Commit::new(
            Some("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_string()),
            Some("email@domain.com".to_string()),
            "Subject line",
            "\n\
            Message line 1.\n\
            Message line 2.\n\
            \n\
            Message line 4\n\
            \n\
            lintje:disable RebaseCommit"
                .to_string(),
            "Co-authored-by: Person A <email@domain.com>\nSigned-off-by: Person A <email@domain.com>".to_string(),
            vec!["src/main.rs".to_string(), "README.md".to_string()]
        );
        commit.validate(&ValidationContext { changesets: true });
        let display_commit = format!("{}", commit);
        assert_eq!(
            display_commit,
            "SHA: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n\
            Author: email@domain.com\n\
            Subject: Subject line\n\
            Message: \n\
            Message line 1.\n\
            Message line 2.\n\
            \n\
            Message line 4\n\
            \n\
            lintje:disable RebaseCommit\n\
            \n\
            ---\n\
            Trailers:\n\
            Co-authored-by: Person A <email@domain.com>\n\
            Signed-off-by: Person A <email@domain.com>\n\
            \n\
            ---\n\
            File changes:\n\
            src/main.rs\n\
            README.md\n\
            \n\
            ---\n\
            Checked rules: MergeCommit, RebaseCommit, SubjectCliche, SubjectLength, SubjectMood, SubjectWhitespace, SubjectPrefix, SubjectCapitalization, SubjectBuildTag, SubjectPunctuation, SubjectTicketNumber, MessageTicketNumber, MessageEmptyFirstLine, MessagePresence, MessageLineLength, MessageTrailerLine, MessageSkipBuildTag, DiffChangeset, DiffPresence\n\
            Ignored rules: RebaseCommit\n\
            Issues: MessageTicketNumber, DiffChangeset\n",
            "{}",
            display_commit
        );
    }

    #[test]
    fn display_without_trailers() {
        let commit = Commit::new(
            Some("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_string()),
            Some("email@domain.com".to_string()),
            "Subject line",
            "\n\
            Message line 1.\n\
            Message line 2.\n\
            \n\
            Message line 4"
                .to_string(),
            "".to_string(),
            vec!["src/main.rs".to_string(), "README.md".to_string()],
        );
        let display_commit = format!("{}", commit);
        assert!(
            display_commit.contains(
                "---\n\
                Trailers:\n\
                \n\
                ---\n"
            ),
            "{}",
            display_commit
        );
    }
}