github.com/autonomy/conform@v0.1.0-alpha.16/internal/policy/commit/check_number_of_commits.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  
    10  	"github.com/autonomy/conform/internal/git"
    11  	"github.com/autonomy/conform/internal/policy"
    12  	"github.com/pkg/errors"
    13  )
    14  
    15  // NumberOfCommits enforces a maximum number of charcters on the commit
    16  // header.
    17  type NumberOfCommits struct {
    18  	ref    string
    19  	ahead  int
    20  	errors []error
    21  }
    22  
    23  // Name returns the name of the check.
    24  func (h NumberOfCommits) Name() string {
    25  	return "Number of Commits"
    26  }
    27  
    28  // Message returns to check message.
    29  func (h NumberOfCommits) Message() string {
    30  	if len(h.errors) != 0 {
    31  		return h.errors[0].Error()
    32  	}
    33  	return fmt.Sprintf("HEAD is %d commit(s) ahead of %s", h.ahead, h.ref)
    34  }
    35  
    36  // Errors returns any violations of the check.
    37  func (h NumberOfCommits) Errors() []error {
    38  	return h.errors
    39  }
    40  
    41  // ValidateNumberOfCommits checks the header length.
    42  func (c Commit) ValidateNumberOfCommits(g *git.Git, ref string) policy.Check {
    43  	check := &NumberOfCommits{
    44  		ref: ref,
    45  	}
    46  
    47  	var err error
    48  	check.ahead, _, err = g.AheadBehind(ref)
    49  	if err != nil {
    50  		check.errors = append(check.errors, err)
    51  		return check
    52  	}
    53  
    54  	if check.ahead > 1 {
    55  		check.errors = append(check.errors, errors.Errorf("HEAD is %d commit(s) ahead of %s", check.ahead, ref))
    56  		return check
    57  	}
    58  
    59  	return check
    60  }