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

type: [feat], message: Add commit lint option. #18

Merged
merged 25 commits into from
Mar 5, 2024
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
ed20bb8
Add commit lint CLI option
esequielvirtuoso Feb 23, 2024
052689e
Update README.md file with commit-lint usage instructions.
esequielvirtuoso Feb 23, 2024
57e91cb
Add tests to git commit message lint
esequielvirtuoso Feb 26, 2024
85fabe8
type: [docs], message: Add pre commit message pattern.
esequielvirtuoso Feb 26, 2024
7343d8c
type: [docs], message: Add pre commit message pattern.
esequielvirtuoso Feb 26, 2024
4d9e08c
type: [fix], message: Fix main logic..
esequielvirtuoso Feb 26, 2024
5e1e15e
type: [docs], message: Add log with rebase tip.
esequielvirtuoso Feb 26, 2024
0ac7cb3
type: [fix], message: separate commit message manager package.
esequielvirtuoso Feb 27, 2024
b95ee19
type: [fix], message: change error message color
esequielvirtuoso Feb 27, 2024
99d8272
type: [fix], message: change error message color
esequielvirtuoso Feb 27, 2024
aba4a05
type: [docs], message: Add git init instruction to the documentation.
esequielvirtuoso Feb 28, 2024
2c692f5
type: [fix], message: remove sensitive log information.
esequielvirtuoso Feb 28, 2024
ed3761a
type: [docs], message: Add rebase instructions to README.md file.
esequielvirtuoso Feb 28, 2024
b4ac813
type: [docs], message: Add warn to the end of the commit lint function.
esequielvirtuoso Feb 28, 2024
0ea4fab
type: [docs], message: Add pre-commit installation instructions
esequielvirtuoso Feb 28, 2024
1fadec4
type: [fix], message: Fix pre-commit documentation on README.md file
esequielvirtuoso Feb 28, 2024
d294d10
breaking change: change semantic release commit message pattern.
esequielvirtuoso Feb 29, 2024
fc65df0
fix: fix git_integration_test commit message
esequielvirtuoso Feb 29, 2024
6266ce2
fix: remove old pre commit message
esequielvirtuoso Feb 29, 2024
960916e
fix: remove old pattern messages
esequielvirtuoso Feb 29, 2024
5507704
fix: fix integration tests
esequielvirtuoso Feb 29, 2024
3cba856
test: add more tests and allow multiple row commit messages
esequielvirtuoso Mar 1, 2024
1889332
test: add more tests
esequielvirtuoso Mar 1, 2024
e350d66
refactor: version package refactor
esequielvirtuoso Mar 1, 2024
0ccb779
add complete word and abbreviation commit type options
esequielvirtuoso Mar 1, 2024
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
5 changes: 4 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -123,4 +123,7 @@ githooks:
@echo "git hooks copied"

shell: modcache imagedev
$(run) sh
$(run) sh

pre-commit-install:
./hack/set-pre-commit.sh
80 changes: 73 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,15 @@ stages:

semantic-release:
stage: semantic-release
only:
refs:
- master
before_script:
- docker pull registry.com/dataplatform/semantic-release:latest
variables:
SEMANTIC_RELEASE_VERSION: latest
dependencies: []
except:
- master
before_script:
- docker pull registry.com/dataplatform/semantic-release:$SEMANTIC_RELEASE_VERSION
script:
- docker run registry.com/dataplatform/semantic-release:latest up -git-host ${CI_SERVER_HOST} -git-group ${CI_PROJECT_NAMESPACE} -git-project ${CI_PROJECT_NAME} -username ${PPD2_USERNAME} -password ${PPD2_ACCESS_TOKEN}

- docker run registry.com/dataplatform/semantic-release:$SEMANTIC_RELEASE_VERSION up -git-host ${CI_SERVER_HOST} -git-group ${CI_PROJECT_NAMESPACE} -git-project ${CI_PROJECT_NAME} -username ${PPD2_USERNAME} -password ${PPD2_ACCESS_TOKEN}
```

If your project is a Python project you can add the flag `-setup-py true` to update the release version in this file too.
Expand Down Expand Up @@ -77,6 +78,71 @@ setup(
)
```

### Adding pre-commit message lint

The semantic-release `pre-commit message lint` will validate your commit messages before the commit being accepted.
That will prevent you from having to rebase your commit history to adapt your commit messages to semantic-release standards.

Notes:
1. To activate commit message template in a pre-existing local repository, go to the project root folder and run `git init` command.
2. After `make commit-message-install`, Git will automatically activate commit message template to new cloned projects.

Run the following command:

```
make commit-message-install
```

If for some reason you need to skip commit lint, you can run git commit with the `--no-verify` tag as follows.

```
git commit -m "type: [typo], message: We do not recommend doing this!" --no-verify
```

We do not recommind using `--no-verify` for projects that use [commit lint ci step](#how-to-add-commit-lint-stage-to-gitlab) once it will validate all the branche commit messages.

If at least one commit message breaks semantic-release standards, you'll have to rebase and reword the wrong commit messages.

### How to use `rebase` to rename commit message?

If the [commit lint ci step](#how-to-add-commit-lint-stage-to-gitlab) fail, you can rebase you commit history and fix the wrong commit messages.

With your local repository up to date with your remote branch, run the following command.
Note: `N` is the number of commits you pushed to your branch.

```
git rebase -i HEAD~N
```

Edit the document and replace the first word `pick` to `r` or `reword`. Save it with `ctrl+o` and close it with `ctrl+x`;

Force push it with `-f` tag as follows:

```
git push -f origin my-branch-name
```

### How to add commit lint stage to Gitlab?

You must add a new stage to `gitlab-ci.yml` file adding two new arguments to semantic-release script.
- `-commit-lint=true` to run commit-lint logic;
- `-branch-name=${CI_COMMIT_REF_NAME}` so that semantic-release can validate only the commits of the referenced branch.

```yaml
stages:
- commit-lint

commit-lint:
stage: commit-int
variables:
SEMANTIC_RELEASE_VERSION: latest
dependencies: []
before_script:
- docker pull registry.com/dataplatform/semantic-release:$SEMANTIC_RELEASE_VERSION
script:
- docker run registry.com/dataplatform/semantic-release:$SEMANTIC_RELEASE_VERSION up -commit-lint=true -branch-name=${CI_COMMIT_REF_NAME} -git-host ${CI_SERVER_HOST} -git-group ${CI_PROJECT_NAMESPACE} -git-project ${CI_PROJECT_NAME} -username ${PPD2_USERNAME} -password ${PPD2_ACCESS_TOKEN}
```

### If you need more information about the semantic release CLI usage you can run the following command.

```
Expand Down
35 changes: 25 additions & 10 deletions cmd/semantic-release/semantic-release.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"os"

commitmessage "github.com/NeowayLabs/semantic-release/src/commit-message"
"github.com/NeowayLabs/semantic-release/src/files"
"github.com/NeowayLabs/semantic-release/src/git"
"github.com/NeowayLabs/semantic-release/src/log"
Expand Down Expand Up @@ -37,6 +38,8 @@ func main() {
helpCmd := flag.NewFlagSet("help", flag.ExitOnError)
helpCommitCmd := flag.NewFlagSet("help-cmt", flag.ExitOnError)

commitLint := upgradeVersionCmd.Bool("commit-lint", false, "Only lint commit history if set as true. (default false)")
branchName := upgradeVersionCmd.String("branch-name", "", "Branch name to be cloned.")
gitHost := upgradeVersionCmd.String("git-host", "", "Git host name. I.e.: gitlab.integration-tests.com. (required)")
groupName := upgradeVersionCmd.String("git-group", "", "Git group name. (required)")
projectName := upgradeVersionCmd.String("git-project", "", "Git project name. (required)")
Expand Down Expand Up @@ -67,15 +70,26 @@ func main() {
case "up":
logger.Info(colorYellow + "\nSemantic Version just started the process...\n\n" + colorReset)

semantic := newSemantic(logger, upgradeVersionCmd, gitHost, groupName, projectName, username, password, upgradePyFile)

if err := semantic.GenerateNewRelease(); err != nil {
logger.Error(err.Error())
os.Exit(1)
semantic := newSemantic(logger, upgradeVersionCmd, gitHost, groupName, projectName, username, password, upgradePyFile, branchName)

if *commitLint {
if *branchName == "" {
logger.Error(colorRed + "\nThe argument -branch-name must be set when --commit-lint is true.\n\n" + colorReset)
}

logger.Info(colorYellow + "\nSemantic Version commit lint started...\n\n" + colorReset)
err := semantic.CommitLint()
if err != nil {
os.Exit(1)
}
} else {
if err := semantic.GenerateNewRelease(); err != nil {
logger.Error(err.Error())
os.Exit(1)
}
}

logger.Info(colorYellow + "\nDone!" + colorReset)

case "help":
printMainCommands()
helpCmd.PrintDefaults()
Expand Down Expand Up @@ -112,7 +126,6 @@ func addFilesToUpgradeList(upgradePyFile *bool, repositoryRootPath string) Upgra
}

func validateIncomingParams(logger *log.Log, upgradeVersionCmd *flag.FlagSet, gitHost, groupName, projectName, username, password *string, upgradePyFile *bool) {

if *gitHost == "" {
logger.Info(colorRed + "Oops! Git host name must be specified." + colorReset + "[docker run neowaylabs/semantic-release up " + colorYellow + "-git-host gitHostNameHere]" + colorReset)
os.Exit(1)
Expand Down Expand Up @@ -180,20 +193,22 @@ func printCommitMessageExample() {
fmt.Println("\n\tNote: The maximum number of characters is 150. If the commit subject exceeds it, it will be cut, keeping only the first 150 characters.")
}

func newSemantic(logger *log.Log, upgradeVersionCmd *flag.FlagSet, gitHost, groupName, projectName, username, password *string, upgradePyFile *bool) *semantic.Semantic {
func newSemantic(logger *log.Log, upgradeVersionCmd *flag.FlagSet, gitHost, groupName, projectName, username, password *string, upgradePyFile *bool, branchName *string) *semantic.Semantic {

validateIncomingParams(logger, upgradeVersionCmd, gitHost, groupName, projectName, username, password, upgradePyFile)

timer := time.New(logger)
repositoryRootPath := fmt.Sprintf("%s/%s", homePath, *projectName)

url := fmt.Sprintf("https://%s:%s@%s/%s/%s.git", *username, *password, *gitHost, *groupName, *projectName)
repoVersionControl, err := git.New(logger, timer.PrintElapsedTime, url, *username, *password, repositoryRootPath)
repoVersionControl, err := git.New(logger, timer.PrintElapsedTime, url, *username, *password, repositoryRootPath, *branchName)
if err != nil {
logger.Fatal(err.Error())
}

filesVersionControl := files.New(logger, timer.PrintElapsedTime, *gitHost, repositoryRootPath, *groupName, *projectName)
commitMessageManager := commitmessage.New(logger)

filesVersionControl := files.New(logger, timer.PrintElapsedTime, *gitHost, repositoryRootPath, *groupName, *projectName, commitMessageManager)

versionControl := v.NewVersionControl(logger, timer.PrintElapsedTime)

Expand Down
25 changes: 25 additions & 0 deletions hack/githooks/commit-msg
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#!/bin/sh
#!/bin/sh
found=0
for commit_type in 'fix' 'feat' 'docs' 'skip' 'build' 'ci' 'perf' 'refactor' 'style' 'test' 'breaking change' 'breaking changes' 'skip versioning' 'skip v'
do
# I.e.: type: [fix], message:
regex_pattern="type: \[${commit_type}\], message:"

message=$(head -1 $1)

check=$(echo "$message" | grep -o -i "$regex_pattern" | wc -l)

if [ $check = "1" ] ; then
echo "Commit message ok!"
found=1
break
fi
done
if [ ${found} = 0 ] ; then
echo "Commit message should meet semantic-release pattern." 1>&2
echo " type: [type-here], message: message here" 1>&2
echo "Allowed types:" 1>&2
echo " ['fix', 'feat', 'docs', 'skip', 'build', 'ci', 'perf', 'refactor', 'style', 'test', 'breaking change', 'breaking changes', 'skip versioning', 'skip v']"1>&2
exit 1
fi
6 changes: 6 additions & 0 deletions hack/set-pre-commit.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#!/bin/bash
mkdir -p ~/.git-templates/hooks
cp -f ./hack//githooks/commit-msg ~/.git-templates/hooks
chmod +x ~/.git-templates/hooks/commit-msg
git init
echo "To activate commit message template in a pre-existing local repository, go to the project root folder and run `git init` command."
91 changes: 91 additions & 0 deletions src/commit-message/commit_message_manager.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package commitmessage

import (
"errors"
"fmt"
"strings"
)

const (
messageTag = "message:"
)

type Logger interface {
Info(s string, args ...interface{})
Error(s string, args ...interface{})
Warn(s string, args ...interface{})
}

type CommitMessage struct {
log Logger
}

func (f *CommitMessage) findMessageTag(commitMessage string) bool {
return strings.Contains(strings.ToLower(commitMessage), messageTag)
}

func (f *CommitMessage) isMessageLongerThanLimit(message string) bool {
return len(message) >= 150
}

func (f *CommitMessage) upperFirstLetterOfSentence(text string) string {
return fmt.Sprintf("%s%s", strings.ToUpper(text[:1]), text[1:])
}

func (f *CommitMessage) getMessage(messageRow string) (string, error) {
startPosition := strings.Index(messageRow, messageTag) + len(messageTag)

if startPosition-1 == len(messageRow)-1 {
return "", errors.New("message not found")
}

message := strings.TrimSpace(messageRow[startPosition:])
if strings.ReplaceAll(message, " ", "") == "" {
return "", errors.New("message not found")
}

return message, nil
}

// prettifyCommitMessage aims to keep a short message based on the commit message, removing extra information such as commit type.
// Args:
//
// commitMessage (string): Full commit message.
//
// Returns:
//
// string: Returns a commit message with limmited number of characters.
// err: Error whenever unexpected issues happen.
func (f *CommitMessage) PrettifyCommitMessage(commitMessage string) (string, error) {

var message string
splitedMessage := strings.Split(commitMessage, "\n")

for _, row := range splitedMessage {
row := strings.ToLower(row)
if f.findMessageTag(row) {

currentMessage, err := f.getMessage(row)
if err != nil {
return "", fmt.Errorf("error while getting message due to: %w", err)
}
message = currentMessage
}
}

if message == "" {
return "", errors.New("commit message has no tag 'message:'")
}

if f.isMessageLongerThanLimit(message) {
message = fmt.Sprintf("%s...", message[:150])
}

return f.upperFirstLetterOfSentence(message), nil
}

func New(log Logger) *CommitMessage {
return &CommitMessage{
log: log,
}
}
52 changes: 52 additions & 0 deletions src/commit-message/commit_message_manager_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
//go:build unit
// +build unit

package commitmessage_test

import (
"testing"

commitMessage "github.com/NeowayLabs/semantic-release/src/commit-message"
"github.com/NeowayLabs/semantic-release/src/log"
"github.com/NeowayLabs/semantic-release/src/tests"
)

type fixture struct {
log *log.Log
commitMessageManager commitMessage.CommitMessage
}

func setup(t *testing.T) *fixture {
logger, err := log.New("test", "1.0.0", "debug")
if err != nil {
t.Errorf("error while getting log due to %s", err.Error())
}

commitMessageMenager := commitMessage.New(logger)

return &fixture{log: logger, commitMessageManager: *commitMessageMenager}
}

func TestPrettifyCommitMessageNoMessageTagError(t *testing.T) {
f := setup(t)
message := "type: [feat], MSG: This is a message without message tag."
prettyMessage, err := f.commitMessageManager.PrettifyCommitMessage(message)
tests.AssertError(t, err)
tests.AssertEmpty(t, prettyMessage)
}

func TestPrettifyCommitMessageNewLinesSuccess(t *testing.T) {
f := setup(t)
message := "type: [feat] \n\n\n\n\nMessage: This is a message with new lines."
prettyMessage, err := f.commitMessageManager.PrettifyCommitMessage(message)
tests.AssertNoError(t, err)
tests.AssertEqualValues(t, "This is a message with new lines.", prettyMessage)
}

func TestPrettifyCommitMessageCutSuccess(t *testing.T) {
f := setup(t)
message := "type: [feat], Message: This is a long message to write to CHANGELOG.md file. Bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo cut here."
prettyMessage, err := f.commitMessageManager.PrettifyCommitMessage(message)
tests.AssertNoError(t, err)
tests.AssertEqualValues(t, "This is a long message to write to changelog.md file. bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo ...", prettyMessage)
}
Loading
Loading