mit-lint 3.4.0

Lints for commits parsed with mit-commit.
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
use mit_commit::CommitMessage;
use std::collections::HashSet;

use crate::model::{Code, Problem, ProblemBuilder};

/// Canonical lint ID
pub const CONFIG: &str = "not-conventional-commit";

/// Advice on how to correct the problem
pub const HELP_MESSAGE: &str =
    "It's important to follow the conventional commit style when creating your commit message. By \
using this style we can automatically calculate the version of software using deployment \
pipelines, and also generate changelogs and other useful information without human interaction.

You can fix it by following style

<type>[optional scope]: <description>

[optional body]

[optional footer(s)]";
/// Description of the problem
pub const ERROR: &str = "Your commit message isn't in conventional style";

/// Configuration for conventional commit linting
#[derive(Default)]
pub struct ConventionalCommitConfig {
    /// Allowed commit types (None means any alphanumeric type is allowed)
    pub allowed_types: Option<HashSet<String>>,
    /// Allowed commit scopes (None means any word character is allowed)
    pub allowed_scopes: Option<HashSet<String>>,
}

impl ConventionalCommitConfig {
    /// Create a new configuration with custom allowed types and scopes
    ///
    /// # Arguments
    ///
    /// * `allowed_types` - Optional set of allowed commit types (None means any alphanumeric type is allowed)
    /// * `allowed_scopes` - Optional set of allowed commit scopes (None means any word character is allowed)
    ///
    /// # Returns
    ///
    /// A new `ConventionalCommitConfig` with the specified allowed types and scopes
    #[allow(dead_code)]
    pub const fn new(
        allowed_types: Option<HashSet<String>>,
        allowed_scopes: Option<HashSet<String>>,
    ) -> Self {
        Self {
            allowed_types,
            allowed_scopes,
        }
    }
}

/// Parse a conventional commit subject line
///
/// Returns (type, scope, `breaking_change`, description) if successful
fn parse_conventional_commit(subject: &str) -> Option<(String, Option<String>, bool, String)> {
    // Find the colon that separates type/scope from description
    let colon_pos = subject.find(':')?;

    // Extract the description (must have a space after the colon)
    if subject.len() <= colon_pos + 1 || subject.chars().nth(colon_pos + 1) != Some(' ') {
        return None;
    }
    // Extract the description (can be empty)
    let description = subject[colon_pos + 2..].to_string();

    // Parse the type, scope, and breaking change indicator
    let type_scope_part = &subject[..colon_pos];

    // Check for breaking change indicator
    let (type_scope_part, breaking_change) = type_scope_part
        .strip_suffix('!')
        .map_or((type_scope_part, false), |stripped| (stripped, true));

    // Check for scope in parentheses
    let (commit_type, scope) = if let (Some(open_paren), Some(close_paren)) =
        (type_scope_part.find('('), type_scope_part.find(')'))
    {
        if open_paren > 0 && close_paren > open_paren && close_paren == type_scope_part.len() - 1 {
            let commit_type = type_scope_part[..open_paren].to_string();
            let scope = type_scope_part[open_paren + 1..close_paren].to_string();
            (commit_type, Some(scope))
        } else {
            return None; // Malformed scope
        }
    } else {
        (type_scope_part.to_string(), None)
    };

    // Validate type is alphanumeric
    if !commit_type.chars().all(|c| c.is_ascii_alphanumeric()) || commit_type.is_empty() {
        return None;
    }

    // Validate scope is alphanumeric if present
    if let Some(scope) = &scope {
        if !scope.chars().all(char::is_alphanumeric) || scope.is_empty() {
            return None;
        }
    }

    Some((commit_type, scope, breaking_change, description))
}

/// Checks if the commit message follows the conventional commit format
///
/// # Arguments
///
/// * `commit_message` - The commit message to check
///
/// # Returns
///
/// * `Some(Problem)` - If the commit message does not follow the conventional commit format
/// * `None` - If the commit message follows the conventional commit format
///
/// # Examples
///
/// ```rust
/// use mit_commit::CommitMessage;
/// use mit_lint::Lint::NotConventionalCommit;
///
/// // This should pass
/// let passing = CommitMessage::from("feat: add new feature");
/// assert!(NotConventionalCommit.lint(&passing).is_none());
///
/// // This should fail
/// let failing = CommitMessage::from("Add new feature");
/// assert!(NotConventionalCommit.lint(&failing).is_some());
/// ```
///
/// # Errors
///
/// This function will never return an error, only an Option<Problem>
pub fn lint(commit_message: &CommitMessage<'_>) -> Option<Problem> {
    lint_with_config(commit_message, &ConventionalCommitConfig::default())
}

fn lint_with_config(
    commit_message: &CommitMessage<'_>,
    config: &ConventionalCommitConfig,
) -> Option<Problem> {
    Some(commit_message)
        .filter(|commit| has_problem(commit, config))
        .map(create_problem)
}

fn has_problem(commit_message: &CommitMessage<'_>, config: &ConventionalCommitConfig) -> bool {
    let subject: String = commit_message.get_subject().into();

    // Parse the subject line
    match parse_conventional_commit(&subject) {
        None => true, // Not a conventional commit format
        Some((commit_type, scope, _, _)) => {
            // If allowed_types is Some, check if the type is allowed
            if let Some(allowed_types) = &config.allowed_types {
                if !allowed_types.contains(&commit_type) {
                    return true;
                }
            }

            // If allowed_scopes is Some and a scope is present, check if the scope is allowed
            if let Some(allowed_scopes) = &config.allowed_scopes {
                if let Some(scope) = scope {
                    if !allowed_scopes.contains(&scope) {
                        return true;
                    }
                }
            }

            false
        }
    }
}

fn create_problem(commit_message: &CommitMessage) -> Problem {
    // Create a problem with appropriate labels
    let commit_text = String::from(commit_message.clone());
    let first_line_length = commit_text.lines().next().map(str::len).unwrap_or_default();

    ProblemBuilder::new(
        ERROR,
        HELP_MESSAGE,
        Code::NotConventionalCommit,
        commit_message,
    )
    .with_label("Not conventional", 0, first_line_length)
    .with_url("https://www.conventionalcommits.org/")
    .build()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::Code;
    use mit_commit::Trailer;
    use quickcheck::TestResult;

    // Examples from https://www.conventionalcommits.org/en/v1.0.0/

    #[test]
    fn commit_message_with_description_and_breaking_change_footer() {
        test_subject_not_separate_from_body(
            "feat: allow provided config object to extend other configs

BREAKING CHANGE: `extends` key in config file is now used for extending other \
 config files
",
            None,
        );
    }

    #[test]
    fn commit_message_with_bang_to_draw_attention_to_breaking_change() {
        test_subject_not_separate_from_body(
            "refactor!: drop support for Node 6
",
            None,
        );
    }

    #[test]
    fn commit_message_with_both_bang_and_breaking_change_footer() {
        test_subject_not_separate_from_body(
            "refactor!: drop support for Node 6

BREAKING CHANGE: refactor to use JavaScript features not available in Node 6.
",
            None,
        );
    }

    #[test]
    fn commit_message_with_no_body() {
        test_subject_not_separate_from_body(
            "docs: correct spelling of CHANGELOG
",
            None,
        );
    }

    #[test]
    fn commit_message_with_scope() {
        test_subject_not_separate_from_body(
            "feat(lang): add polish language
",
            None,
        );
    }

    #[test]
    fn commit_message_with_multi_paragraph_body_and_multiple_footers() {
        test_subject_not_separate_from_body(
            "fix: correct minor typos in code

see the issue for details

on typos fixed.

Reviewed-by: Z
Refs #133
",
            None,
        );
    }

    #[test]
    fn revert_example() {
        test_subject_not_separate_from_body(
            "revert: let us never again speak of the noodle incident

Refs: 676104e, a215868
",
            None,
        );
    }

    #[test]
    fn non_conventional() {
        let message = "An example commit

This is an example commit
";
        test_subject_not_separate_from_body(
            message,
            Some(&Problem::new(
                ERROR.into(),
                HELP_MESSAGE.into(),
                Code::NotConventionalCommit,
                &message.into(),
                Some(vec![("Not conventional".to_string(), 0_usize, 17_usize)]),
                Some("https://www.conventionalcommits.org/".parse().unwrap()),
            )),
        );
    }

    #[test]
    fn missing_bracket() {
        let message = "fix(example: An example commit

This is an example commit
";
        test_subject_not_separate_from_body(
            message,
            Some(Problem::new(
                ERROR.into(),
                HELP_MESSAGE.into(),
                Code::NotConventionalCommit,
                &message.into(),
                Some(vec![("Not conventional".to_string(), 0_usize, 30_usize)]),
                Some("https://www.conventionalcommits.org/".parse().unwrap()),
            ))
            .as_ref(),
        );
    }

    #[test]
    fn missing_space() {
        let message = "fix(example):An example commit

This is an example commit
";
        test_subject_not_separate_from_body(
            message,
            Some(Problem::new(
                ERROR.into(),
                HELP_MESSAGE.into(),
                Code::NotConventionalCommit,
                &message.into(),
                Some(vec![("Not conventional".to_string(), 0_usize, 30_usize)]),
                Some("https://www.conventionalcommits.org/".parse().unwrap()),
            ))
            .as_ref(),
        );
    }

    fn test_subject_not_separate_from_body(message: &str, expected: Option<&Problem>) {
        let actual = &lint(&CommitMessage::from(message));
        assert_eq!(
            actual.as_ref(),
            expected,
            "Message {message:?} should have returned {expected:?}, found {actual:?}"
        );
    }

    use std::option::Option::None;

    use miette::{GraphicalReportHandler, GraphicalTheme, Report};

    #[test]
    fn formatting() {
        let message = "An example commit

This is an example commit
";
        let problem = lint(&CommitMessage::from(message.to_string()));
        let actual = fmt_report(&Report::new(problem.unwrap()));
        let expected = "NotConventionalCommit (https://www.conventionalcommits.org/)\n\n  x Your commit message isn't in conventional style\n   ,-[1:1]\n 1 | An example commit\n   : ^^^^^^^^|^^^^^^^^\n   :         `-- Not conventional\n 2 | \n   `----\n  help: It's important to follow the conventional commit style when creating\n        your commit message. By using this style we can automatically\n        calculate the version of software using deployment pipelines, and also\n        generate changelogs and other useful information without human\n        interaction.\n        \n        You can fix it by following style\n        \n        <type>[optional scope]: <description>\n        \n        [optional body]\n        \n        [optional footer(s)]\n"
        .to_string();
        assert_eq!(
            actual, expected,
            "Message {message:?} should have returned {expected:?}, found {actual:?}"
        );
    }

    fn fmt_report(diag: &Report) -> String {
        let mut out = String::new();
        GraphicalReportHandler::new_themed(GraphicalTheme::none())
            .with_width(80)
            .with_links(false)
            .render_report(&mut out, diag.as_ref())
            .unwrap();
        out
    }

    #[allow(clippy::needless_pass_by_value)]
    #[quickcheck]
    fn fail_check(commit: String) -> TestResult {
        let has_non_alpha_type = commit
            .chars()
            .position(|x| x == ':')
            .is_some_and(|x| commit.chars().take(x).any(|x| !x.is_ascii_alphanumeric()));
        if has_non_alpha_type {
            return TestResult::discard();
        }
        let message = CommitMessage::from(format!("{commit}\n# comment"));
        let result = lint(&message);
        TestResult::from_bool(result.is_some())
    }

    #[allow(clippy::needless_pass_by_value)]
    #[quickcheck]
    fn success_check(
        type_slug: String,
        scope: Option<String>,
        description: String,
        body: Option<String>,
        bc_break: Option<String>,
    ) -> TestResult {
        if type_slug.starts_with('#')
            || type_slug.is_empty()
            || type_slug.chars().any(|x| !x.is_ascii_alphanumeric())
        {
            return TestResult::discard();
        }
        if let Some(scope) = scope.clone() {
            if scope.is_empty() || scope.chars().any(|x| !x.is_alphanumeric()) {
                return TestResult::discard();
            }
        }

        let mut commit: CommitMessage<'_> = CommitMessage::default().with_subject(
            format!(
                "{}{}{}: {}",
                type_slug,
                scope.map(|x| format!("({x})")).unwrap_or_default(),
                bc_break
                    .clone()
                    .map(|_| "!".to_string())
                    .unwrap_or_default(),
                description
            )
            .into(),
        );

        let body_contents = body.clone().unwrap_or_default();

        if body.is_some() {
            commit = commit.with_body_contents(&body_contents);
        }

        if let Some(_bc_contents) = bc_break {
            commit = commit.add_trailer(Trailer::new("BC BREAK".into(), "bc_contents".into()));
        }

        let result = lint(&commit);
        TestResult::from_bool(result.is_none())
    }

    // Tests for custom configurations with allowed_types and allowed_scopes
    #[test]
    fn test_lint_with_config_allowed_types() {
        use std::collections::HashSet;

        // Create a config that only allows "feat" type
        let mut allowed_types = HashSet::new();
        allowed_types.insert("feat".to_string());
        let config = ConventionalCommitConfig::new(Some(allowed_types), None);

        // Test with allowed type
        let commit_allowed = CommitMessage::from("feat: add new feature");
        assert!(lint_with_config(&commit_allowed, &config).is_none());

        // Test with disallowed type
        let commit_disallowed = CommitMessage::from("fix: fix a bug");
        assert!(lint_with_config(&commit_disallowed, &config).is_some());
    }

    #[test]
    fn test_lint_with_config_allowed_scopes() {
        use std::collections::HashSet;

        // Create a config that only allows "ui" scope
        let mut allowed_scopes = HashSet::new();
        allowed_scopes.insert("ui".to_string());
        let config = ConventionalCommitConfig::new(None, Some(allowed_scopes));

        // Test with allowed scope
        let commit_allowed = CommitMessage::from("feat(ui): add new UI feature");
        assert!(lint_with_config(&commit_allowed, &config).is_none());

        // Test with disallowed scope
        let commit_disallowed = CommitMessage::from("feat(api): add new API feature");
        assert!(lint_with_config(&commit_disallowed, &config).is_some());
    }

    // Tests for edge cases in parse_conventional_commit
    #[test]
    fn test_parse_conventional_commit_colon_position() {
        // Test with no space after colon (should fail)
        assert!(parse_conventional_commit("feat:no-space").is_none());

        // Test with space after colon (should pass)
        assert!(parse_conventional_commit("feat: with-space").is_some());

        // Test with colon at the end (should fail)
        assert!(parse_conventional_commit("feat:").is_none());

        // Test with colon at the end followed by a space (should pass)
        // This specifically tests the case that failed in the quickcheck test
        assert!(parse_conventional_commit("feat: ").is_some());

        // Test with colon at position 0 (should fail because the commit type is empty)
        assert!(parse_conventional_commit(": description").is_none());

        // Test with colon at a high position (should pass if followed by space and description)
        let long_type = "a".repeat(100);
        let commit_message = format!("{long_type}(scope): description");
        assert!(parse_conventional_commit(&commit_message).is_some());
    }

    #[test]
    fn test_parse_conventional_commit_scope_parsing() {
        // Test with valid scope
        let result = parse_conventional_commit("feat(ui): add feature");
        assert!(result.is_some());
        let (commit_type, scope, _, _) = result.unwrap();
        assert_eq!(commit_type, "feat");
        assert_eq!(scope, Some("ui".to_string()));

        // Test with malformed scope (open paren at beginning)
        assert!(parse_conventional_commit("(ui): add feature").is_none());

        // Test with malformed scope (close paren not at end)
        assert!(parse_conventional_commit("feat(ui)extra: add feature").is_none());

        // Test with malformed scope (open paren after close paren)
        assert!(parse_conventional_commit("feat)(: add feature").is_none());
    }

    #[test]
    fn test_parse_conventional_commit_scope_validation() {
        // Test with empty scope (should fail)
        assert!(parse_conventional_commit("feat(): add feature").is_none());

        // Test with non-alphanumeric scope (should fail)
        assert!(parse_conventional_commit("feat(ui-component): add feature").is_none());

        // Test with alphanumeric scope (should pass)
        assert!(parse_conventional_commit("feat(ui123): add feature").is_some());
    }

    #[test]
    fn test_quickcheck_failing_case() {
        // Test the specific case that failed in QuickCheck: ("0", None, "", None, None)
        let commit = CommitMessage::from("0: ");
        assert!(lint(&commit).is_none());
    }
}