github.com/twelho/conform@v0.0.0-20231016230407-c25e9238598a/internal/policy/commit/check_spelling.go (about)

     1  // This Source Code Form is subject to the terms of the Mozilla Public
     2  // License, v. 2.0. If a copy of the MPL was not distributed with this
     3  // file, You can obtain one at http://mozilla.org/MPL/2.0/.
     4  
     5  package commit
     6  
     7  import (
     8  	"fmt"
     9  	"strings"
    10  
    11  	"github.com/golangci/misspell"
    12  
    13  	"github.com/twelho/conform/internal/policy"
    14  )
    15  
    16  // SpellCheck represents to spell check policy.
    17  type SpellCheck struct {
    18  	Locale string `mapstructure:"locale"`
    19  }
    20  
    21  // SpellingCheck enforces correct spelling.
    22  type SpellingCheck struct {
    23  	errors []error
    24  }
    25  
    26  // Name returns the name of the check.
    27  func (h SpellingCheck) Name() string {
    28  	return "Spellcheck"
    29  }
    30  
    31  // Message returns to check message.
    32  func (h SpellingCheck) Message() string {
    33  	return fmt.Sprintf("Commit contains %d misspellings", len(h.errors))
    34  }
    35  
    36  // Errors returns any violations of the check.
    37  func (h SpellingCheck) Errors() []error {
    38  	return h.errors
    39  }
    40  
    41  // ValidateSpelling checks the spelling.
    42  func (c Commit) ValidateSpelling() policy.Check { //nolint:ireturn
    43  	check := &SpellingCheck{}
    44  
    45  	r := misspell.Replacer{
    46  		Replacements: misspell.DictMain,
    47  	}
    48  
    49  	switch strings.ToUpper(c.SpellCheck.Locale) {
    50  	case "":
    51  	case "US":
    52  		r.AddRuleList(misspell.DictAmerican)
    53  	case "UK", "GB":
    54  		r.AddRuleList(misspell.DictBritish)
    55  	case "NZ", "AU", "CA":
    56  		check.errors = append(check.errors, fmt.Errorf("unknown locale: %q", c.SpellCheck.Locale))
    57  	}
    58  
    59  	r.Compile()
    60  
    61  	_, diffs := r.Replace(c.msg)
    62  
    63  	for _, diff := range diffs {
    64  		check.errors = append(check.errors, fmt.Errorf("`%s` is a misspelling of `%s`", diff.Original, diff.Corrected))
    65  	}
    66  
    67  	return check
    68  }