github.com/autonomy/conform@v0.1.0-alpha.16/internal/policy/commit/check_header_length.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/autonomy/conform/internal/policy"
    12  	"github.com/pkg/errors"
    13  )
    14  
    15  // MaxNumberOfCommitCharacters is the default maximium number of characters
    16  // allowed in a commit header.
    17  var MaxNumberOfCommitCharacters = 89
    18  
    19  // HeaderLengthCheck enforces a maximum number of charcters on the commit
    20  // header.
    21  type HeaderLengthCheck struct {
    22  	headerLength int
    23  	errors       []error
    24  }
    25  
    26  // Name returns the name of the check.
    27  func (h HeaderLengthCheck) Name() string {
    28  	return "Header Length"
    29  }
    30  
    31  // Message returns to check message.
    32  func (h HeaderLengthCheck) Message() string {
    33  	return fmt.Sprintf("Header is %d characters", h.headerLength)
    34  }
    35  
    36  // Errors returns any violations of the check.
    37  func (h HeaderLengthCheck) Errors() []error {
    38  	return h.errors
    39  }
    40  
    41  // ValidateHeaderLength checks the header length.
    42  func (c Commit) ValidateHeaderLength() policy.Check {
    43  	check := &HeaderLengthCheck{}
    44  
    45  	if c.HeaderLength != 0 {
    46  		MaxNumberOfCommitCharacters = c.HeaderLength
    47  	}
    48  
    49  	header := strings.Split(strings.TrimPrefix(c.msg, "\n"), "\n")[0]
    50  	check.headerLength = len(header)
    51  	if check.headerLength > MaxNumberOfCommitCharacters {
    52  		check.errors = append(check.errors, errors.Errorf("Commit header is %d characters", len(header)))
    53  	}
    54  
    55  	return check
    56  }