Skip to main content

mit_lint/model/
lint.rs

1use std::{
2    convert::{TryFrom, TryInto},
3    str::FromStr,
4    sync::LazyLock,
5};
6
7use miette::Diagnostic;
8use mit_commit::CommitMessage;
9use quickcheck::{Arbitrary, Gen};
10use strum_macros::EnumIter;
11use thiserror::Error;
12
13use crate::{
14    checks, model,
15    model::{Lints, Problem},
16};
17
18/// The lints that are supported
19#[derive(Debug, Eq, PartialEq, Copy, Clone, Hash, Ord, PartialOrd, EnumIter)]
20pub enum Lint {
21    /// Check for duplicated trailers
22    ///
23    /// # Examples
24    ///
25    /// Passing
26    ///
27    /// ```rust
28    /// use mit_commit::CommitMessage;
29    /// use mit_lint::Lint;
30    ///
31    /// let message: &str = "An example commit
32    ///
33    /// This is an example commit without any duplicate trailers
34    /// "
35    /// .into();
36    /// let actual = Lint::DuplicatedTrailers.lint(&CommitMessage::from(message));
37    /// assert!(actual.is_none(), "Expected None, found {:?}", actual);
38    /// ```
39    ///
40    /// Erring
41    ///
42    /// ```rust
43    /// use mit_commit::CommitMessage;
44    /// use mit_lint::{Code, Lint, Problem};
45    ///
46    /// let message: &str = "An example commit
47    ///
48    /// This is an example commit without any duplicate trailers
49    ///
50    /// Signed-off-by: Billie Thompson <email@example.com>
51    /// Signed-off-by: Billie Thompson <email@example.com>
52    /// Co-authored-by: Billie Thompson <email@example.com>
53    /// Co-authored-by: Billie Thompson <email@example.com>
54    /// "
55    /// .into();
56    /// let expected = Some(Problem::new(
57    ///     "Your commit message has duplicated trailers".into(),
58    ///     "These are normally added accidentally when you\'re rebasing or amending to a \
59    ///      commit, sometimes in the text editor, but often by git hooks.\n\nYou can fix \
60    ///      this by deleting the duplicated \"Co-authored-by\", \"Signed-off-by\" fields"
61    ///         .into(),
62    ///     Code::DuplicatedTrailers,
63    ///     &message.into(),
64    ///     Some(vec![
65    ///         ("Duplicated `Co-authored-by`".to_string(), 231, 51),
66    ///         ("Duplicated `Signed-off-by`".to_string(), 128, 50),
67    ///     ]),
68    ///     Some(
69    ///         "https://git-scm.com/docs/githooks#_commit_msg"
70    ///             .parse()
71    ///             .unwrap(),
72    ///     ),
73    /// ));
74    /// let actual = Lint::DuplicatedTrailers.lint(&CommitMessage::from(message));
75    /// assert_eq!(
76    ///     actual, expected,
77    ///     "Expected {:?}, found {:?}",
78    ///     expected, actual
79    /// );
80    /// ```
81    DuplicatedTrailers,
82    /// Check for a missing pivotal tracker id
83    ///
84    /// # Examples
85    ///
86    /// Passing
87    ///
88    /// ```rust
89    /// use mit_commit::CommitMessage;
90    /// use mit_lint::Lint;
91    ///
92    /// let message: &str = "An example commit [fixes #12345678]
93    /// "
94    /// .into();
95    /// let actual = Lint::PivotalTrackerIdMissing.lint(&CommitMessage::from(message));
96    /// assert!(actual.is_none(), "Expected None, found {:?}", actual);
97    /// ```
98    ///
99    /// Erring
100    ///
101    /// ```rust
102    /// use mit_commit::CommitMessage;
103    /// use mit_lint::{Code, Lint, Problem};
104    ///
105    /// let message: &str = "An example commit
106    ///
107    /// This is an example commit
108    /// "
109    ///
110    /// .into();
111    /// let expected = Some(Problem::new(
112    ///     "Your commit message is missing a Pivotal Tracker ID".into(),
113    ///     "It's important to add the ID because it allows code to be linked back to the stories it was done for, it can provide a chain of custody for code for audit purposes, and it can give future explorers of the codebase insight into the wider organisational need behind the change. We may also use it for automation purposes, like generating changelogs or notification emails.\n\nYou can fix this by adding the Id in one of the styles below to the commit message\n[Delivers #12345678]\n[fixes #12345678]\n[finishes #12345678]\n[#12345884 #12345678]\n[#12345884,#12345678]\n[#12345678],[#12345884]\nThis will address [#12345884]"
114    ///         .into(),
115    ///     Code::PivotalTrackerIdMissing,
116    ///     &message.into(),
117    ///     Some(vec![("No Pivotal Tracker ID".to_string(), 19, 25)]),
118    ///     Some("https://www.pivotaltracker.com/help/api?version=v5#Tracker_Updates_in_SCM_Post_Commit_Hooks".parse().unwrap()),
119    /// ));
120    /// let actual = Lint::PivotalTrackerIdMissing.lint(&CommitMessage::from(message));
121    /// assert_eq!(
122    ///     actual, expected,
123    ///     "Expected {:?}, found {:?}",
124    ///     expected, actual
125    /// );
126    /// ```
127    PivotalTrackerIdMissing,
128    /// Check for a missing jira issue key
129    ///
130    /// # Examples
131    ///
132    /// Passing
133    ///
134    /// ```rust
135    /// use mit_commit::CommitMessage;
136    /// use mit_lint::Lint;
137    ///
138    /// let message: &str = "An example commit
139    ///
140    /// Relates-to: JRA-123
141    /// "
142    /// .into();
143    /// let actual = Lint::JiraIssueKeyMissing.lint(&CommitMessage::from(message));
144    /// assert!(actual.is_none(), "Expected None, found {:?}", actual);
145    /// ```
146    ///
147    /// Erring
148    ///
149    /// ```rust
150    /// use mit_commit::CommitMessage;
151    /// use mit_lint::{Code, Lint, Problem};
152    ///
153    /// let message: &str = "An example commit
154    ///
155    /// This is an example commit
156    /// "
157    ///
158    /// .into();
159    /// let expected = Some(Problem::new(
160    ///     "Your commit message is missing a JIRA Issue Key".into(),
161    ///     "It's important to add the issue key because it allows us to link code back to the motivations for doing it, and in some cases provide an audit trail for compliance purposes.\n\nYou can fix this by adding a key like `JRA-123` to the commit message"
162    ///         .into(),
163    ///     Code::JiraIssueKeyMissing,&message.into(),
164    ///     Some(vec![("No JIRA Issue Key".to_string(), 19, 25)]),
165    ///     Some("https://support.atlassian.com/jira-software-cloud/docs/what-is-an-issue/#Workingwithissues-Projectkeys".parse().unwrap()),
166    /// ));
167    /// let actual = Lint::JiraIssueKeyMissing.lint(&CommitMessage::from(message));
168    /// assert_eq!(
169    ///     actual, expected,
170    ///     "Expected {:?}, found {:?}",
171    ///     expected, actual
172    /// );
173    /// ```
174    JiraIssueKeyMissing,
175    /// Check for a missing github id
176    ///
177    /// # Examples
178    ///
179    /// Passing
180    ///
181    /// ```rust
182    /// use mit_commit::CommitMessage;
183    /// use mit_lint::Lint;
184    ///
185    /// let message: &str = "An example commit
186    ///
187    /// Relates-to: AnOrganisation/git-mit#642
188    /// "
189    /// .into();
190    /// let actual = Lint::GitHubIdMissing.lint(&CommitMessage::from(message));
191    /// assert!(actual.is_none(), "Expected None, found {:?}", actual);
192    /// ```
193    ///
194    /// Erring
195    ///
196    /// ```rust
197    /// use mit_commit::CommitMessage;
198    /// use mit_lint::{Code, Lint, Problem};
199    ///
200    /// let message: &str = "An example commit
201    ///
202    /// This is an example commit
203    /// "
204    ///
205    /// .into();
206    /// let expected = Some(Problem::new(
207    ///      "Your commit message is missing a GitHub ID".into(),
208    ///     "It's important to add the issue ID because it allows us to link code back to the motivations for doing it, and because we can help people exploring the repository link their issues to specific bits of code.\n\nYou can fix this by adding a ID like the following examples:\n\n#642\nGH-642\nAnUser/git-mit#642\nAnOrganisation/git-mit#642\nfixes #642\n\nBe careful just putting '#642' on a line by itself, as '#' is the default comment character"
209    ///         .into(),
210    ///     Code::GitHubIdMissing,&message.into(),Some(vec![("No GitHub ID".to_string(), 19, 25)]),
211    /// Some("https://docs.github.com/en/github/writing-on-github/working-with-advanced-formatting/autolinked-references-and-urls#issues-and-pull-requests".parse().unwrap()),
212    /// ));
213    /// let actual = Lint::GitHubIdMissing.lint(&CommitMessage::from(message));
214    /// assert_eq!(
215    ///     actual, expected,
216    ///     "Expected {:?}, found {:?}",
217    ///     expected, actual
218    /// );
219    /// ```
220    GitHubIdMissing,
221    /// Subject not being separated from the body
222    ///
223    /// # Examples
224    ///
225    /// Passing
226    ///
227    /// ```rust
228    /// use mit_commit::CommitMessage;
229    /// use mit_lint::Lint;
230    ///
231    /// let message: &str = "An example commit
232    ///
233    /// Some Body Content
234    /// "
235    /// .into();
236    /// let actual = Lint::SubjectNotSeparateFromBody.lint(&CommitMessage::from(message));
237    /// assert!(actual.is_none(), "Expected None, found {:?}", actual);
238    /// ```
239    ///
240    /// Erring
241    ///
242    /// ```rust
243    /// use mit_commit::CommitMessage;
244    /// use mit_lint::{Code, Lint, Problem};
245    ///
246    /// let message: &str = "An example commit
247    /// This is an example commit
248    /// "
249    /// .into();
250    /// let expected = Some(Problem::new(
251    ///       "Your commit message is missing a blank line between the subject and the body".into(),
252    ///     "Most tools that render and parse commit messages, expect commit messages to be in the form of subject and body. This includes git itself in tools like git-format-patch. If you don't include this you may see strange behaviour from git and any related tools.\n\nTo fix this separate subject from body with a blank line"
253    ///         .into(),
254    ///     Code::SubjectNotSeparateFromBody,&message.into(),
255    ///     Some(vec![("Missing blank line".to_string(), 18, 25)]),
256    ///     Some("https://git-scm.com/book/en/v2/Distributed-Git-Contributing-to-a-Project#_commit_guidelines".parse().unwrap()),
257    /// ));
258    /// let actual = Lint::SubjectNotSeparateFromBody.lint(&CommitMessage::from(message));
259    /// assert_eq!(
260    ///     actual, expected,
261    ///     "Expected {:?}, found {:?}",
262    ///     expected, actual
263    /// );
264    /// ```
265    SubjectNotSeparateFromBody,
266    /// Check for a long subject line
267    ///
268    /// # Examples
269    ///
270    /// Passing
271    ///
272    /// ```rust
273    /// use mit_commit::CommitMessage;
274    /// use mit_lint::Lint;
275    ///
276    /// let message: &str = "An example commit
277    ///
278    /// Some Body Content
279    /// "
280    /// .into();
281    /// let actual = Lint::SubjectLongerThan72Characters.lint(&CommitMessage::from(message));
282    /// assert!(actual.is_none(), "Expected None, found {:?}", actual);
283    /// ```
284    ///
285    /// Erring
286    ///
287    /// ```
288    /// use mit_commit::CommitMessage;
289    /// use mit_lint::{Code, Lint, Problem};
290    ///
291    /// let message:String = "x".repeat(73).into();
292    /// let expected = Some(Problem::new(
293    ///       "Your subject is longer than 72 characters".into(),
294    ///     "It's important to keep the subject of the commit less than 72 characters because when you look at the git log, that's where it truncates the message. This means that people won't get the entirety of the information in your commit.\n\nPlease keep the subject line 72 characters or under"
295    ///         .into(),
296    ///     Code::SubjectLongerThan72Characters,&message.clone().into(),
297    ///     Some(vec![("Too long".to_string(), 72, 1)]),
298    ///     Some("https://git-scm.com/book/en/v2/Distributed-Git-Contributing-to-a-Project#_commit_guidelines".parse().unwrap()),
299    /// ));
300    /// let actual = Lint::SubjectLongerThan72Characters.lint(&CommitMessage::from(message));
301    /// assert_eq!(
302    ///     actual, expected,
303    ///     "Expected {:?}, found {:?}",
304    ///     expected, actual
305    /// );
306    /// ```
307    SubjectLongerThan72Characters,
308    /// Check for a non-capitalised subject
309    ///
310    /// # Examples
311    ///
312    /// Passing
313    ///
314    /// ```rust
315    /// use mit_commit::CommitMessage;
316    /// use mit_lint::Lint;
317    ///
318    /// let message: &str = "An example commit\n".into();
319    /// let actual = Lint::SubjectNotCapitalized.lint(&CommitMessage::from(message));
320    /// assert!(actual.is_none(), "Expected None, found {:?}", actual);
321    /// ```
322    ///
323    /// Erring
324    ///
325    /// ```rust
326    /// use mit_commit::CommitMessage;
327    /// use mit_lint::{Code, Lint, Problem};
328    ///
329    /// let message: &str =
330    ///     "an example commit\n"
331    /// .into();
332    /// let expected = Some(
333    ///     Problem::new(
334    ///         "Your commit message is missing a capital letter".into(),
335    ///         "The subject line is a title, and as such should be capitalised.\n\nYou can fix this by capitalising the first character in the subject".into(),
336    ///     Code::SubjectNotCapitalized,&message.into(),
337    ///     Some(vec![("Not capitalised".to_string(), 0, 1)]),
338    ///     Some("https://git-scm.com/book/en/v2/Distributed-Git-Contributing-to-a-Project#_commit_guidelines".parse().unwrap()),
339    /// )
340    /// );
341    /// let actual = Lint::SubjectNotCapitalized.lint(&CommitMessage::from(message));
342    /// assert_eq!(
343    ///     actual, expected,
344    ///     "Expected {:?}, found {:?}",
345    ///     expected, actual
346    /// );
347    /// ```
348    SubjectNotCapitalized,
349    /// Check for period at the end of the subject
350    ///
351    /// # Examples
352    ///
353    /// Passing
354    ///
355    /// ```rust
356    /// use mit_commit::CommitMessage;
357    /// use mit_lint::Lint;
358    ///
359    /// let message: &str = "An example commit\n".into();
360    /// let actual = Lint::SubjectEndsWithPeriod.lint(&CommitMessage::from(message));
361    /// assert!(actual.is_none(), "Expected None, found {:?}", actual);
362    /// ```
363    ///
364    /// Erring
365    ///
366    /// ```rust
367    /// use mit_commit::CommitMessage;
368    /// use mit_lint::{Code, Lint, Problem};
369    ///
370    /// let message: &str =
371    ///     "An example commit.\n".into();
372    /// let expected = Some(
373    /// Problem::new(
374    ///     "Your commit message ends with a period".into(),
375    ///     "It's important to keep your commits short, because we only have a limited number of characters to use (72) before the subject line is truncated. Full stops aren't normally in subject lines, and take up an extra character, so we shouldn't use them in commit message subjects.\n\nYou can fix this by removing the period"
376    ///         .into(),
377    ///     Code::SubjectEndsWithPeriod,&message.into(),
378    ///     Some(vec![("Unneeded period".to_string(), 17, 1)]),
379    ///     Some("https://git-scm.com/book/en/v2/Distributed-Git-Contributing-to-a-Project#_commit_guidelines".parse().unwrap()),
380    /// )
381    /// );
382    /// let actual = Lint::SubjectEndsWithPeriod.lint(&CommitMessage::from(message));
383    /// assert_eq!(
384    ///     actual, expected,
385    ///     "Expected {:?}, found {:?}",
386    ///     expected, actual
387    /// );
388    /// ```
389    SubjectEndsWithPeriod,
390    /// Check for a long body line
391    ///
392    /// # Examples
393    ///
394    /// Passing
395    ///
396    /// ```rust
397    /// use mit_commit::CommitMessage;
398    /// use mit_lint::Lint;
399    ///
400    /// let message: &str = "An example commit\n\nSome Body Content\n".into();
401    /// let actual = Lint::BodyWiderThan72Characters.lint(&CommitMessage::from(message));
402    /// assert!(actual.is_none(), "Expected None, found {:?}", actual);
403    /// ```
404    ///
405    /// Erring
406    ///
407    /// ```rust
408    /// use mit_commit::CommitMessage;
409    /// use mit_lint::{Code, Lint, Problem};
410    ///
411    /// let message:String = ["Subject".to_string(), "x".repeat(73).into()].join("\n\n");
412    /// let expected = Some(Problem::new(
413    ///   "Your commit has a body wider than 72 characters".into(),
414    ///     "It's important to keep the body of the commit narrower than 72 characters because when you look at the git log, that's where it truncates the message. This means that people won't get the entirety of the information in your commit.\n\nYou can fix this by making the lines in your body no more than 72 characters"
415    ///         .into(),
416    ///     Code::BodyWiderThan72Characters,&message.clone().into(),
417    ///     Some(vec![("Too long".parse().unwrap(), 81, 1)]),
418    /// Some("https://git-scm.com/book/en/v2/Distributed-Git-Contributing-to-a-Project#_commit_guidelines".parse().unwrap())
419    /// ));
420    /// let actual = Lint::BodyWiderThan72Characters.lint(&CommitMessage::from(message));
421    /// assert_eq!(
422    ///     actual, expected,
423    ///     "Expected {:?}, found {:?}",
424    ///     expected, actual
425    /// );
426    /// ```
427    BodyWiderThan72Characters,
428    /// Check for commits following the conventional standard
429    ///
430    /// # Examples
431    ///
432    /// Passing
433    ///
434    /// ```rust
435    /// use mit_commit::CommitMessage;
436    /// use mit_lint::Lint;
437    ///
438    /// let message: &str = "refactor: An example commit\n\nSome Body Content\n".into();
439    /// let actual = Lint::NotConventionalCommit.lint(&CommitMessage::from(message));
440    /// assert!(actual.is_none(), "Expected None, found {:?}", actual);
441    /// ```
442    ///
443    /// Erring
444    ///
445    /// ```rust
446    /// use mit_commit::CommitMessage;
447    /// use mit_lint::{Code, Lint, Problem};
448    ///
449    /// let message: &str =
450    ///     "An example commit\n\nSome Body Content\n"
451    /// .into();
452    /// let expected = Some(Problem::new(
453    ///       "Your commit message isn't in conventional style".into(),
454    ///      "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.\n\nYou can fix it by following style\n\n<type>[optional scope]: <description>\n\n[optional body]\n\n[optional footer(s)]"
455    ///         .into(),
456    ///     Code::NotConventionalCommit,&message.into(),Some(vec![("Not conventional".to_string(), 0, 17)]),Some("https://www.conventionalcommits.org/".to_string()),
457    /// ));
458    /// let actual = Lint::NotConventionalCommit.lint(&CommitMessage::from(message));
459    /// assert_eq!(
460    ///     actual, expected,
461    ///     "Expected {:?}, found {:?}",
462    ///     expected, actual
463    /// );
464    /// ```
465    NotConventionalCommit,
466    /// Check for commits following the emoji log standard
467    ///
468    /// # Examples
469    ///
470    /// Passing
471    ///
472    /// ```rust
473    /// use mit_commit::CommitMessage;
474    /// use mit_lint::Lint;
475    ///
476    /// let message: &str = "šŸ“– DOC: An example commit\n\nSome Body Content\n".into();
477    /// let actual = Lint::NotEmojiLog.lint(&CommitMessage::from(message));
478    /// assert!(actual.is_none(), "Expected None, found {:?}", actual);
479    /// ```
480    ///
481    /// Erring
482    ///
483    /// ```rust
484    /// use mit_commit::CommitMessage;
485    /// use mit_lint::{Code, Lint, Problem};
486    ///
487    /// let message: &str =
488    ///     "An example commit\n\nSome Body Content\n"
489    /// .into();
490    /// let expected = Some(
491    /// Problem::new(
492    ///        "Your commit message isn't in emoji log style".into(),
493    ///      "It's important to follow the emoji log style when creating your commit message. By using this style we can automatically generate changelogs.\n\nYou can fix it using one of the prefixes:\n\n\nšŸ“¦ NEW:\nšŸ‘Œ IMPROVE:\nšŸ› FIX:\nšŸ“– DOC:\nšŸš€ RELEASE:\nšŸ¤– TEST:\n‼\u{fe0f} BREAKING:"
494    ///         .into(),
495    ///     Code::NotEmojiLog,&message.into(),Some(vec![("Not emoji log".to_string(), 0, 17)]),Some("https://github.com/ahmadawais/Emoji-Log".to_string()),
496    /// ));
497    /// let actual = Lint::NotEmojiLog.lint(&CommitMessage::from(message));
498    /// assert_eq!(
499    ///     actual, expected,
500    ///     "Expected {:?}, found {:?}",
501    ///     expected, actual
502    /// );
503    /// ```
504    NotEmojiLog,
505}
506
507/// The prefix we put in front of the lint when serialising
508pub const CONFIG_KEY_PREFIX: &str = "mit.lint";
509
510impl TryFrom<&str> for Lint {
511    type Error = Error;
512
513    fn try_from(from: &str) -> Result<Self, Self::Error> {
514        Self::all_lints()
515            .find(|lint| lint.name() == from)
516            .ok_or_else(|| Error::new_lint_not_found(from))
517    }
518}
519
520impl From<Lint> for String {
521    fn from(from: Lint) -> Self {
522        format!("{from}")
523    }
524}
525
526impl From<Lint> for &str {
527    /// Get an lint's unique name
528    ///
529    /// # Examples
530    ///
531    /// ```
532    /// use mit_lint::Lint;
533    /// let actual: &str = Lint::NotConventionalCommit.into();
534    /// assert_eq!(actual, Lint::NotConventionalCommit.name());
535    /// ```
536    fn from(lint: Lint) -> Self {
537        lint.name()
538    }
539}
540
541impl Lint {
542    /// Get an lint's unique name
543    #[must_use]
544    pub const fn name(self) -> &'static str {
545        match self {
546            Self::DuplicatedTrailers => checks::duplicate_trailers::CONFIG,
547            Self::PivotalTrackerIdMissing => checks::missing_pivotal_tracker_id::CONFIG,
548            Self::JiraIssueKeyMissing => checks::missing_jira_issue_key::CONFIG,
549            Self::GitHubIdMissing => checks::missing_github_id::CONFIG,
550            Self::SubjectNotSeparateFromBody => checks::subject_not_separate_from_body::CONFIG,
551            Self::SubjectLongerThan72Characters => {
552                checks::subject_longer_than_72_characters::CONFIG
553            }
554            Self::SubjectNotCapitalized => checks::subject_not_capitalized::CONFIG,
555            Self::SubjectEndsWithPeriod => checks::subject_line_ends_with_period::CONFIG,
556            Self::BodyWiderThan72Characters => checks::body_wider_than_72_characters::CONFIG,
557            Self::NotConventionalCommit => checks::not_conventional_commit::CONFIG,
558            Self::NotEmojiLog => checks::not_emoji_log::CONFIG,
559        }
560    }
561}
562
563/// All the available lints
564static ALL_LINTS: LazyLock<[Lint; 11]> = LazyLock::new(|| {
565    [
566        Lint::DuplicatedTrailers,
567        Lint::PivotalTrackerIdMissing,
568        Lint::JiraIssueKeyMissing,
569        Lint::SubjectNotSeparateFromBody,
570        Lint::GitHubIdMissing,
571        Lint::SubjectLongerThan72Characters,
572        Lint::SubjectNotCapitalized,
573        Lint::SubjectEndsWithPeriod,
574        Lint::BodyWiderThan72Characters,
575        Lint::NotConventionalCommit,
576        Lint::NotEmojiLog,
577    ]
578});
579
580/// The ones that are enabled by default
581static DEFAULT_ENABLED_LINTS: LazyLock<[Lint; 4]> = LazyLock::new(|| {
582    [
583        Lint::DuplicatedTrailers,
584        Lint::SubjectNotSeparateFromBody,
585        Lint::SubjectLongerThan72Characters,
586        Lint::BodyWiderThan72Characters,
587    ]
588});
589
590impl Lint {
591    /// Iterator over all the lints
592    ///
593    /// # Examples
594    ///
595    /// ```rust
596    /// use mit_lint::Lint;
597    /// assert!(Lint::all_lints().next().is_some())
598    /// ```
599    pub fn all_lints() -> impl Iterator<Item = Self> {
600        ALL_LINTS.iter().copied()
601    }
602
603    /// Iterator over all the lints
604    ///
605    /// # Examples
606    ///
607    /// ```rust
608    /// use mit_lint::Lint;
609    /// assert!(Lint::iterator().next().is_some())
610    /// ```
611    #[deprecated(since = "0.1.5", note = "iterator was an unusual name. Use all_lints")]
612    pub fn iterator() -> impl Iterator<Item = Self> {
613        Self::all_lints()
614    }
615
616    /// Check if a lint is enabled by default
617    ///
618    /// # Examples
619    ///
620    /// ```rust
621    /// use mit_lint::Lint;
622    /// assert!(Lint::SubjectNotSeparateFromBody.enabled_by_default());
623    /// assert!(!Lint::NotConventionalCommit.enabled_by_default());
624    /// ```
625    #[must_use]
626    pub fn enabled_by_default(self) -> bool {
627        DEFAULT_ENABLED_LINTS.contains(&self)
628    }
629
630    /// Get a key suitable for a configuration document
631    ///
632    /// # Examples
633    ///
634    /// ```rust
635    /// use mit_lint::Lint;
636    /// assert_eq!(
637    ///     Lint::SubjectNotSeparateFromBody.config_key(),
638    ///     "mit.lint.subject-not-separated-from-body"
639    /// );
640    /// ```
641    #[must_use]
642    pub fn config_key(self) -> String {
643        format!("{CONFIG_KEY_PREFIX}.{self}")
644    }
645
646    /// Run this lint on a commit message
647    ///
648    /// # Examples
649    ///
650    /// ```rust
651    /// use mit_commit::CommitMessage;
652    /// use mit_lint::Lint;
653    /// let actual =
654    ///     Lint::NotConventionalCommit.lint(&CommitMessage::from("An example commit message"));
655    /// assert!(actual.is_some());
656    /// ```
657    #[must_use]
658    pub fn lint(self, commit_message: &CommitMessage<'_>) -> Option<Problem> {
659        match self {
660            Self::DuplicatedTrailers => checks::duplicate_trailers::lint(commit_message),
661            Self::PivotalTrackerIdMissing => {
662                checks::missing_pivotal_tracker_id::lint(commit_message)
663            }
664            Self::JiraIssueKeyMissing => checks::missing_jira_issue_key::lint(commit_message),
665            Self::GitHubIdMissing => checks::missing_github_id::lint(commit_message),
666            Self::SubjectNotSeparateFromBody => {
667                checks::subject_not_separate_from_body::lint(commit_message)
668            }
669            Self::SubjectLongerThan72Characters => {
670                checks::subject_longer_than_72_characters::lint(commit_message)
671            }
672            Self::SubjectNotCapitalized => checks::subject_not_capitalized::lint(commit_message),
673            Self::SubjectEndsWithPeriod => {
674                checks::subject_line_ends_with_period::lint(commit_message)
675            }
676            Self::BodyWiderThan72Characters => {
677                checks::body_wider_than_72_characters::lint(commit_message)
678            }
679            Self::NotConventionalCommit => checks::not_conventional_commit::lint(commit_message),
680            Self::NotEmojiLog => checks::not_emoji_log::lint(commit_message),
681        }
682    }
683
684    /// Try and convert a list of names into lints
685    ///
686    /// # Examples
687    ///
688    /// ```rust
689    /// use mit_lint::Lint;
690    /// let actual = Lint::from_names(vec!["not-emoji-log", "body-wider-than-72-characters"]);
691    /// assert_eq!(
692    ///     actual.unwrap(),
693    ///     vec![Lint::BodyWiderThan72Characters, Lint::NotEmojiLog]
694    /// );
695    /// ```
696    ///
697    /// # Errors
698    /// If the lint does not exist
699    pub fn from_names(names: Vec<&str>) -> Result<Vec<Self>, model::lints::Error> {
700        let lints: Lints = names.try_into()?;
701        Ok(lints.into_iter().collect())
702    }
703}
704
705impl Arbitrary for Lint {
706    fn arbitrary(g: &mut Gen) -> Self {
707        *g.choose(&ALL_LINTS.iter().copied().collect::<Vec<_>>())
708            .unwrap()
709    }
710
711    fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
712        quickcheck::empty_shrinker()
713    }
714}
715
716impl std::fmt::Display for Lint {
717    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
718        write!(f, "{}", self.name())
719    }
720}
721
722impl FromStr for Lint {
723    type Err = Error;
724
725    fn from_str(s: &str) -> Result<Self, Self::Err> {
726        Self::try_from(s)
727    }
728}
729
730/// Errors
731#[derive(Error, Debug, Diagnostic)]
732pub enum Error {
733    /// Lint not found
734    #[error("Lint not found: {0}")]
735    #[diagnostic(
736        code(mit_lint::model::lint::error::LintNotFound),
737        url(docsrs),
738        help("check the list of available lints")
739    )]
740    LintNotFound(#[source_code] String, #[label("Not found")] (usize, usize)),
741}
742
743impl Error {
744    fn new_lint_not_found(missing_lint: &str) -> Self {
745        Self::LintNotFound(missing_lint.to_string(), (0, missing_lint.len()))
746    }
747}
748
749#[cfg(test)]
750mod tests {
751    use super::*;
752
753    use std::convert::TryInto;
754
755    #[quickcheck]
756    fn it_is_creatable_from_string(expected: Lint) -> bool {
757        let lint: String = expected.into();
758        expected == lint.parse().unwrap()
759    }
760
761    #[quickcheck]
762    fn it_is_convertible_to_string(expected: Lint) -> bool {
763        let lint: String = expected.into();
764        expected.name() == lint
765    }
766
767    #[quickcheck]
768    fn it_can_be_created_from_string(expected: Lint) -> bool {
769        let lint: Lint = expected.name().try_into().unwrap();
770        expected == lint
771    }
772
773    #[quickcheck]
774    fn it_is_printable(lint: Lint) -> bool {
775        lint.name() == format!("{lint}")
776    }
777
778    #[quickcheck]
779    fn i_can_get_all_the_lints(lint: Lint) -> bool {
780        Lint::all_lints().any(|x| x == lint)
781    }
782
783    #[test]
784    fn example_it_is_convertible_to_string() {
785        let string: String = Lint::PivotalTrackerIdMissing.into();
786        assert_eq!("pivotal-tracker-id-missing".to_string(), string);
787    }
788
789    #[test]
790    fn example_it_can_be_created_from_string() {
791        let lint: Lint = "pivotal-tracker-id-missing".try_into().unwrap();
792        assert_eq!(Lint::PivotalTrackerIdMissing, lint);
793    }
794
795    #[test]
796    fn example_it_is_printable() {
797        assert_eq!(
798            "pivotal-tracker-id-missing",
799            &format!("{}", Lint::PivotalTrackerIdMissing)
800        );
801    }
802
803    #[test]
804    fn example_i_can_get_all_the_lints() {
805        let all: Vec<Lint> = Lint::all_lints().collect();
806        assert_eq!(
807            all,
808            vec![
809                Lint::DuplicatedTrailers,
810                Lint::PivotalTrackerIdMissing,
811                Lint::JiraIssueKeyMissing,
812                Lint::SubjectNotSeparateFromBody,
813                Lint::GitHubIdMissing,
814                Lint::SubjectLongerThan72Characters,
815                Lint::SubjectNotCapitalized,
816                Lint::SubjectEndsWithPeriod,
817                Lint::BodyWiderThan72Characters,
818                Lint::NotConventionalCommit,
819                Lint::NotEmojiLog,
820            ]
821        );
822    }
823
824    #[test]
825    fn example_i_can_get_if_a_lint_is_enabled_by_default() {
826        assert!(Lint::DuplicatedTrailers.enabled_by_default());
827        assert!(!Lint::PivotalTrackerIdMissing.enabled_by_default());
828        assert!(!Lint::JiraIssueKeyMissing.enabled_by_default());
829        assert!(Lint::SubjectNotSeparateFromBody.enabled_by_default());
830        assert!(!Lint::GitHubIdMissing.enabled_by_default());
831    }
832}