1
0
Fork 0
mirror of https://github.com/vbatts/git-validation.git synced 2025-06-04 02:52:28 +00:00

commits: add a fallback if rev-list fails due to shallow depth

Fixes: #53

When CI only fetches some shallow depth of commits in a repo, don't fail
on `git rev-list` on commits that are outside that range.

Signed-off-by: Vincent Batts <vbatts@hashbangbash.com>
This commit is contained in:
Vincent Batts 2023-03-14 22:56:57 -04:00
parent 767ae83c3f
commit a041fe84ae
Signed by: vbatts
GPG key ID: 10937E57733F1362
2 changed files with 45 additions and 5 deletions

View file

@ -15,13 +15,19 @@ import (
// If commitrange is a single commit, all ancestor commits up through the hash provided.
// If commitrange is an empty commit range, then nil is returned.
func Commits(commitrange string) ([]CommitEntry, error) {
// TEST if it has _enough_ of a range from rev-list
commitrange, err := checkRevList(commitrange)
if err != nil {
logrus.Errorf("failed to validate the git commit range: %s", err)
return nil, err
}
cmdArgs := []string{"git", "rev-list", commitrange}
if debug() {
logrus.Infof("[git] cmd: %q", strings.Join(cmdArgs, " "))
}
output, err := exec.Command(cmdArgs[0], cmdArgs[1:]...).Output()
if err != nil {
logrus.Errorf("mm[git] cmd: %q", strings.Join(cmdArgs, " "))
logrus.Errorf("[git] cmd: %q", strings.Join(cmdArgs, " "))
return nil, err
}
if len(output) == 0 {
@ -39,6 +45,39 @@ func Commits(commitrange string) ([]CommitEntry, error) {
return commits, nil
}
// Since the commitrange requested may be longer than the depth being cloned in CI,
// check for an error, if so do a git log to get the oldest available commit for a reduced range.
func checkRevList(commitrange string) (string, error) {
cmdArgs := []string{"git", "rev-list", commitrange}
if debug() {
logrus.Infof("[git] cmd: %q", strings.Join(cmdArgs, " "))
}
_, err := exec.Command(cmdArgs[0], cmdArgs[1:]...).Output()
if err == nil {
// no issues, return now
return commitrange, nil
}
cmdArgs = []string{"git", "log", "--pretty=oneline"}
if debug() {
logrus.Infof("[git] cmd: %q", strings.Join(cmdArgs, " "))
}
output, err := exec.Command(cmdArgs[0], cmdArgs[1:]...).Output()
if err != nil {
logrus.Errorf("[git] cmd: %q", strings.Join(cmdArgs, " "))
return "", err
}
// This "output" is now the list of available commits and short description.
// We want the last commit hash only.. (i.e. `| tail -n1 | awk '{ print $1 }'`)
chunks := strings.Split(strings.TrimSpace(string(output)), "\n")
if len(chunks) == 1 {
return strings.Split(chunks[0], " ")[0], nil
}
last := chunks[len(chunks)-1]
lastCommit := strings.Split(last, " ")[0]
return fmt.Sprintf("%s..HEAD", lastCommit), nil
}
// FieldNames are for the formating and rendering of the CommitEntry structs.
// Keys here are from git log pretty format "format:..."
var FieldNames = map[string]string{