Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added bot command to enforce changelog requirements #159

Merged
merged 6 commits into from
Sep 26, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion bot/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@ require (
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/sirupsen/logrus v1.9.0 // indirect
golang.org/x/crypto v0.6.0 // indirect
golang.org/x/exp v0.0.0-20230905200255-921286631fa9
golang.org/x/net v0.7.0 // indirect
golang.org/x/sys v0.5.0 // indirect
golang.org/x/sys v0.12.0 // indirect
golang.org/x/term v0.5.0 // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/protobuf v1.28.1 // indirect
Expand Down
6 changes: 4 additions & 2 deletions bot/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,8 @@ golang.org/x/crypto v0.0.0-20220126234351-aa10faf2a1f8/go.mod h1:IxCIyHEi3zRg3s0
golang.org/x/crypto v0.6.0 h1:qfktjS5LUO+fFKeJXZ+ikTRijMmljikvG68fpMMruSc=
golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
Expand Down Expand Up @@ -113,8 +115,8 @@ golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0 h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0 h1:CM0HF96J0hcLAwsHPJZjfdNzs0gftsLfgKt57wWHJ0o=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0 h1:n2a8QNdAb0sZNpU9R1ALUXBbY+w51fCQDN+7EdxNBsY=
Expand Down
124 changes: 124 additions & 0 deletions bot/internal/bot/changelog.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
/*
Copyright 2023 Gravitational, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package bot

import (
"context"
"fmt"
"log"
"regexp"
"strings"
"unicode"

"github.com/gravitational/trace"
"golang.org/x/exp/slices"
)

const NoChangelogLabel string = "no-changelog"
const ChangelogPrefix string = "changelog: "
const ChangelogRegex string = "(?mi)^changelog: .*"

// Checks if the PR contains a changelog entry in the PR body, or a "no-changelog" label.
//
// A few tests are performed on the extracted changelog entry to ensure it conforms to a
// common standard.
func (b *Bot) CheckChangelog(ctx context.Context) error {
pull, err := b.c.GitHub.GetPullRequest(ctx,
b.c.Environment.Organization,
b.c.Environment.Repository,
b.c.Environment.Number,
)
if err != nil {
return trace.Wrap(err, "failed to retrieve pull request for https://github.com/%s/%s/pull/%d", b.c.Environment.Organization, b.c.Environment.Repository, b.c.Environment.Number)
}

if slices.Contains(pull.UnsafeLabels, NoChangelogLabel) {
log.Printf("PR contains %q label, skipping changelog check", NoChangelogLabel)
return nil
}

changelogEntries, err := b.getChangelogEntries(ctx, pull.UnsafeBody)
if err != nil {
return trace.Wrap(err, "failed to get changelog entry")
}

for _, changelogEntry := range changelogEntries {
err = b.validateChangelogEntry(ctx, changelogEntry)
if err != nil {
return trace.Wrap(err, "failed to validate changelog entry %q", changelogEntry)
}
}

return nil
}

func (b *Bot) getChangelogEntries(ctx context.Context, prBody string) ([]string, error) {
changelogRegex := regexp.MustCompile(ChangelogRegex)

changelogMatches := changelogRegex.FindAllString(prBody, -1)
if len(changelogMatches) == 0 {
return nil, b.logFailedCheck(ctx, "Changelog entry not found in the PR body. Please add a %q label to the PR, or changelog lines starting with `%s` followed by the changelog entries for the PR.", NoChangelogLabel, ChangelogPrefix)
}

for i, changelogMatch := range changelogMatches {
changelogMatches[i] = changelogMatch[len(ChangelogPrefix):] // Case insensitive prefix removal
}

log.Printf("Found changelog entries %v", changelogMatches)
return changelogMatches, nil
}

// Checks for common issues with the changelog entry.
// This is not intended to be comprehensive, rather, it is intended to cover the majority of problems.
func (b *Bot) validateChangelogEntry(ctx context.Context, changelogEntry string) error {
if strings.TrimSpace(changelogEntry) == "" {
return b.logFailedCheck(ctx, "The changelog entry must contain one or more non-whitespace characters")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To make logic more clear, I would make the following changes:

  • Instead of returning b.logFailedCheck() from each branch here and in "getChangelogEntry", have them return a normal trace.BadParameter("xxx") error.
  • In CheckChangelog call b.logFailedCheck(ctx, err) when the respective function returns an error.

Basically, move logFailedCheck call up the stack. Otherwise it's very implicit that get/validate functions also leave comments on the PR.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I disagree here, on the grounds that validateChangelogEntry could potentially return an error that is not due to an invalid changelog. Currently this is not an issue, however, if a developer were to add another check that does something like checking to see if the changelog entry is already in the CHANGELOG.md file, then this could result in an error message being written to the PR body that is not due to an invalid changelog entry. More specifically, if a check was added that did something like err := os.ReadFile("CHANGELOG.md") then this error could potentially get logged as a changelog entry failure.

Maybe one of these would be a better solution to the issue:

  • I could add a comment to the validateChangelogEntry function that explicitly says that it logs errors to the PR
  • I could return an error type that is specific to a changelog entry problem, and only log to the PR if the error is of this type

What do you think?

If I were to go with the second route, would it be better to return and instance of this new error type, or return a trace.Wrap of this new error type? In other words, ValidationError("some message") or trace.Wrap(ValidationError("some message"), "some error occured")?

}

if !unicode.IsLetter([]rune(changelogEntry)[0]) {
return b.logFailedCheck(ctx, "The changelog entry must start with a letter")
}

if strings.HasPrefix(strings.ToLower(changelogEntry), "backport of") ||
strings.HasPrefix(strings.ToLower(changelogEntry), "backports") {
return b.logFailedCheck(ctx, "The changelog entry must contain the actual change, not a reference to the source PR of the backport.")
}

if strings.Contains(changelogEntry, "](") {
return b.logFailedCheck(ctx, "The changelog entry must not contain a Markdown link or image")
}

if strings.Contains(changelogEntry, "```") {
return b.logFailedCheck(ctx, "The changelog entry must not contain a multiline code block")
}

return nil
}

func (b *Bot) logFailedCheck(ctx context.Context, format string, args ...interface{}) error {
err := b.c.GitHub.CreateComment(ctx,
b.c.Environment.Organization,
b.c.Environment.Repository,
b.c.Environment.Number,
fmt.Sprintf(format, args...),
)
if err != nil {
return trace.Wrap(err, "failed to create or update the changelog comment")
}

return trace.Errorf(format, args...)
}
216 changes: 216 additions & 0 deletions bot/internal/bot/changelog_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
/*
Copyright 2021 Gravitational, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package bot

import (
"context"
"fmt"
"strings"
"testing"

"github.com/gravitational/shared-workflows/bot/internal/env"
"github.com/gravitational/shared-workflows/bot/internal/github"
"github.com/stretchr/testify/require"
)

func TestChangelog(t *testing.T) {
t.Run("pass-no-changelog-label", func(t *testing.T) {
b, ctx := buildTestingFixtures()
b.c.GitHub.(*fakeGithub).pull.UnsafeLabels = []string{NoChangelogLabel}

err := b.CheckChangelog(ctx)
require.True(t, err == nil)
})
}

func TestGetChangelogEntry(t *testing.T) {
tests := []struct {
desc string
body string
shouldError bool
expected []string
}{
{
desc: "pass-simple",
body: strings.Join([]string{"some typical PR entry", fmt.Sprintf("%schangelog entry", ChangelogPrefix), "some extra text"}, "\n"),
shouldError: false,
expected: []string{"changelog entry"},
},
{
desc: "pass-case-invariant",
body: strings.Join([]string{"some typical PR entry", fmt.Sprintf("%schangelog entry", strings.ToUpper(ChangelogPrefix))}, "\n"),
shouldError: false,
expected: []string{"changelog entry"},
},
{
desc: "pass-prefix-in-changelog-entry",
body: strings.Join([]string{"some typical PR entry", strings.Repeat(ChangelogPrefix, 5)}, "\n"),
shouldError: false,
expected: []string{strings.Repeat(ChangelogPrefix, 4)},
},
{
desc: "pass-only-changelog-in-body",
body: fmt.Sprintf("%schangelog entry", ChangelogPrefix),
shouldError: false,
expected: []string{"changelog entry"},
},
{
desc: "pass-multiple-entries",
body: strings.Join([]string{
ChangelogPrefix + "entry 1",
ChangelogPrefix + "entry 2",
ChangelogPrefix + "entry 3",
}, "\n"),
expected: []string{
"entry 1",
"entry 2",
"entry 3",
},
shouldError: false,
},
{
desc: "fail-if-no-body",
body: "",
shouldError: true,
},
{
desc: "fail-if-no-entry",
body: "some typical PR entry",
shouldError: true,
},
}
for _, test := range tests {
t.Run(test.desc, func(t *testing.T) {
b, ctx := buildTestingFixtures()

changelogEntries, err := b.getChangelogEntries(ctx, test.body)
require.Equal(t, test.shouldError, err != nil)
if !test.shouldError {
require.Exactly(t, test.expected, changelogEntries)
}
})
}
}

func TestValidateGetChangelogEntry(t *testing.T) {
tests := []struct {
desc string
entry string
shouldError bool
}{
{
desc: "pass-simple",
entry: "Changelog entry",
shouldError: false,
},
{
desc: "pass-markdown-single-line-code-block",
entry: "Changelog `entry`",
shouldError: false,
},
{
desc: "fail-empty",
entry: "",
shouldError: true,
},
{
desc: "fail-whitespace",
entry: " \t ",
shouldError: true,
},
{
desc: "fail-non-alphabetical-starting-character",
entry: "1234Changelog entry",
shouldError: true,
},
{
desc: "fail-refers-to-backport",
entry: "Backport of #1234",
shouldError: true,
},
{
desc: "fail-ends-with-markdown-link",
entry: "Changelog [entry](https://some-link.com).",
shouldError: true,
},
{
desc: "fail-ends-with-markdown-image",
entry: "Changelog ![entry](https://some-link.com).",
shouldError: true,
},
{
desc: "fail-ends-with-markdown-header",
entry: "## Changelog entry",
shouldError: true,
},
{
desc: "fail-ends-with-markdown-ordered-list",
entry: "1. Changelog entry",
shouldError: true,
},
{
desc: "fail-ends-with-markdown-unordered-list",
entry: "- Changelog entry",
shouldError: true,
},
{
desc: "fail-ends-with-markdown-multiline-code-block",
entry: "Changelog entry ```",
shouldError: true,
},
}
for _, test := range tests {
t.Run(test.desc, func(t *testing.T) {
b, ctx := buildTestingFixtures()

err := b.validateChangelogEntry(ctx, test.entry)
require.Equal(t, test.shouldError, err != nil)
})
}
}

func TestLogFailedCheck(t *testing.T) {
t.Run("fail-contains-passed-message", func(t *testing.T) {
b, ctx := buildTestingFixtures()

err := b.logFailedCheck(ctx, "error %s", "message")
require.ErrorContains(t, err, "error message")
})
}

func buildTestingFixtures() (*Bot, context.Context) {
return &Bot{
c: &Config{
Environment: &env.Environment{
Organization: "foo",
Author: "9",
Repository: "bar",
Number: 0,
UnsafeBase: "branch/v8",
UnsafeHead: "fix",
},
GitHub: &fakeGithub{
comments: []github.Comment{
{
Author: "[email protected]",
Body: "PR comment body",
},
},
},
},
}, context.Background()
}
2 changes: 2 additions & 0 deletions bot/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ func main() {
err = b.CalculateBinarySizes(ctx, flags.buildDir, flags.artifacts, out)
case "bloat":
err = b.BloatCheck(ctx, flags.baseStats, flags.buildDir, flags.artifacts, os.Stdout)
case "changelog":
err = b.CheckChangelog(ctx)
default:
err = trace.BadParameter("unknown workflow: %v", flags.workflow)
}
Expand Down