Skip to content

Commit

Permalink
Merge pull request #38 from muandane/feat/win
Browse files Browse the repository at this point in the history
deprecate ⚰️: removal of signoff flag in favor of config based value
  • Loading branch information
muandane authored Apr 11, 2024
2 parents acc9951 + e267127 commit c079f1f
Show file tree
Hide file tree
Showing 17 changed files with 294 additions and 167 deletions.
10 changes: 5 additions & 5 deletions .github/workflows/coverage.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Set up Go
uses: actions/setup-go@v4.1.0
uses: actions/setup-go@v5.0.0
with:
go-version: '1.21.4'
- name: Check out code
go-version: '1.22.1'
- name: Check out code
uses: actions/[email protected]
- name: Test and generate coverage report
run: go test -coverprofile=coverage.out ./...
- name: Upload coverage reports to Codecov
uses: codecov/codecov-action@v3.1.4
env:
uses: codecov/codecov-action@v4.1.0
env:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
file: coverage.out
2 changes: 1 addition & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ jobs:
- name: Set up Go
uses: actions/[email protected]
with:
go-version: '1.21.4'
go-version: '1.22.1'
-
name: Run GoReleaser
uses: goreleaser/[email protected]
Expand Down
3 changes: 2 additions & 1 deletion .goji.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
"accounts",
"ci"
],
"skipquestions": [],
"signoff": true,
"skipquestions": null,
"subjectmaxlength": 50,
"symbol": true,
"types": [
Expand Down
27 changes: 27 additions & 0 deletions .goreleaser.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,19 @@ builds:
main: ./
goos:
- darwin
- windows
- linux
goarch:
- amd64
- arm64
- arm
goarm:
- "7"
ignore:
- goos: windows
goarch: arm64
- goos: windows
goarm: "7"
env:
- CGO_ENABLED=0
ldflags:
Expand Down Expand Up @@ -57,6 +66,24 @@ brews:
zsh_completion.install "completions/goji.zsh" => "_goji"
fish_completion.install "completions/goji.fish"
man1.install "manpages/goji.1.gz"
winget:
- publisher: muandane
license: "Apache-2.0 license"
copyright: Muandane
homepage: "https://github.com/muandane/goji"
short_description: "Commitizen-like Emoji Commit Tool written in Go"
repository:
owner: "muandane"
name: winget-pkgs
branch: "{{.ProjectName}}-{{.Version}}"
# pull_request:
# enabled: true
# draft: false
# check_boxes: true
# base:
# owner: microsoft
# name: winget-pkgs
# branch: master

checksum:
name_template: 'checksums.txt'
59 changes: 52 additions & 7 deletions cmd/check.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import (
"regexp"
"strings"

"github.com/charmbracelet/log"
"github.com/muandane/goji/pkg/config"
"github.com/spf13/cobra"
)

Expand All @@ -18,7 +20,10 @@ var checkCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
var commitMessage string
fromFile, _ := cmd.Flags().GetBool("from-file")

config, err := config.ViperConfig()
if err != nil {
log.Fatalf("Error loading config file.")
}
if fromFile {
// Read commit message from file
if len(os.Args) < 2 {
Expand All @@ -38,14 +43,54 @@ var checkCmd = &cobra.Command{
commitMessage = strings.TrimSpace(string(output))
}

emojisToIgnore := make(map[string]string)
for _, t := range config.Types {
emojisToIgnore[t.Emoji] = ""
}

for emoji, replacement := range emojisToIgnore {
commitMessage = strings.ReplaceAll(commitMessage, emoji, replacement)
}

// Define the regex pattern for a conventional commit message
re := regexp.MustCompile(`^[\w\s]*?(feat|fix|docs|style|refactor|test|chore|build|ci|perf|improvement|package)(\([\w\s]*\))?[: ].+$`)
if !re.MatchString(commitMessage) {
fmt.Printf("Error: Your commit message does not follow the conventional commit format. %s", commitMessage)
os.Exit(1)
} else {
fmt.Printf("Success: Your commit message follows the conventional commit format. %s", commitMessage)
parts := strings.SplitN(commitMessage, ":", 2)
if len(parts) != 2 {
fmt.Println("Error: Commit message does not follow the conventional commit format.")
return
}
var typeNames []string
for _, t := range config.Types {
typeNames = append(typeNames, t.Name)
}
typePattern := strings.Join(typeNames, "|")
// Validate the type and scope
typeScope := strings.Split(strings.TrimSpace(parts[0]), "(")
if len(typeScope) > 2 {
fmt.Println("Error: Commit message does not follow the conventional commit format.")
return
}

// Validate the type
typeRegex := regexp.MustCompile(`\A[\w\s]*?(` + typePattern + `)\z`)
if !typeRegex.MatchString(typeScope[0]) {
fmt.Println("Error: Commit message type is invalid.")
return
}

// Validate the scope (optional)
if len(typeScope) == 2 {
scope := strings.TrimSuffix(typeScope[1], ")")
if scope == "" {
fmt.Println("Error: Commit message scope is empty.")
return
}
}
description := strings.TrimSpace(parts[1])
if description == "" {
fmt.Println("Error: Commit message description is empty.")
return
}
fmt.Printf("Success: Your commit message follows the conventional commit format: \n%s", commitMessage)
},
}

Expand Down
10 changes: 7 additions & 3 deletions cmd/man.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,9 +118,13 @@ func markdownManual() string {
)
}

func sanitizeMarkdown(s string) string {
return strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(
s, "<", "&lt;"), ">", "&gt;"), specialChar, "`")
func sanitizeMarkdown(input string) string {
escaped := strings.NewReplacer(
"<", "&lt;",
">", "&gt;",
"`", "&#96;", // backtick
).Replace(input)
return strings.ReplaceAll(escaped, specialChar, "`")
}

func sanitizeSpecial(s string) string {
Expand Down
13 changes: 8 additions & 5 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import (
var (
version string
versionFlag bool
signFlag bool
typeFlag string
scopeFlag string
messageFlag string
Expand Down Expand Up @@ -72,6 +71,8 @@ var rootCmd = &cobra.Command{
}
} else {
// If not all flags are provided, fall back to the interactive prompt logic

// fmt.Printf("Enter commit message:%v", signOff)
commitMessages, err := utils.AskQuestions(config)
if err != nil {
log.Fatalf("Error asking questions: %v", err)
Expand All @@ -84,7 +85,9 @@ var rootCmd = &cobra.Command{
}
var gitCommitError error
action := func() {
gitCommitError = executeGitCommit(commitMessage, commitBody, signFlag)
signOff := config.SignOff
gitCommitError = commit(commitMessage, commitBody, signOff)
// gitCommitError = config.GitCommit(".", commitMessage, commitBody)
}

err = spinner.New().
Expand All @@ -95,14 +98,14 @@ var rootCmd = &cobra.Command{
fmt.Printf("\nError committing changes: %v\n", gitCommitError)
fmt.Println("Check the output above for details.")
} else if err != nil {
fmt.Println("Error committing: ", err)
fmt.Printf("Error committing: %s", err)
}
},
}

func init() {
rootCmd.Flags().BoolVarP(&versionFlag, "version", "v", false, "Display version information")
rootCmd.Flags().BoolVarP(&signFlag, "sign-off", "S", false, "add a Signed-off-by trailer")
// rootCmd.Flags().BoolVarP(&signFlag, "sign-off", "S", false, "add a Signed-off-by trailer")
rootCmd.Flags().StringVarP(&typeFlag, "type", "t", "", "Specify the type from the config file")
rootCmd.Flags().StringVarP(&scopeFlag, "scope", "s", "", "Specify a custom scope")
rootCmd.Flags().StringVarP(&messageFlag, "message", "m", "", "Specify a commit message")
Expand All @@ -115,7 +118,7 @@ func Execute() {
}
}

func executeGitCommit(commitMessage, commitBody string, signOff bool) error {
func commit(commitMessage, commitBody string, signOff bool) error {
args := []string{"commit", "-m", commitMessage, "-m", commitBody}

if signOff {
Expand Down
4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module github.com/muandane/goji

go 1.21.7
go 1.22.2

require (
github.com/charmbracelet/glamour v0.6.0
Expand Down Expand Up @@ -60,7 +60,7 @@ require (
github.com/yuin/goldmark-emoji v1.0.1 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/exp v0.0.0-20240119083558-1b970713d09a // indirect
golang.org/x/net v0.19.0 // indirect
golang.org/x/net v0.20.0 // indirect
golang.org/x/sync v0.6.0 // indirect
golang.org/x/sys v0.16.0 // indirect
golang.org/x/term v0.16.0 // indirect
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -142,8 +142,8 @@ go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN8
golang.org/x/exp v0.0.0-20240119083558-1b970713d09a h1:Q8/wZp0KX97QFTc2ywcOE0YRjZPVIx+MXInMzdvQqcA=
golang.org/x/exp v0.0.0-20240119083558-1b970713d09a/go.mod h1:idGWGoKP1toJGkd5/ig9ZLuPcZBC3ewk7SzmH0uou08=
golang.org/x/net v0.0.0-20221002022538-bcab6841153b/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk=
golang.org/x/net v0.19.0 h1:zTwKpTd2XuCqf8huc7Fo2iSy+4RHPd10s4KzeTnVr1c=
golang.org/x/net v0.19.0/go.mod h1:CfAk/cbD4CthTvqiEl8NpboMuiuOYsAr/7NOjZJtv1U=
golang.org/x/net v0.20.0 h1:aCL9BSgETF1k+blQaYUBx9hJ9LOGP3gAVemcZlf1Kpo=
golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY=
golang.org/x/sync v0.6.0 h1:5BMeUDZ7vkXGfEr1x9B4bRcTH4lpkTkpdh0T/J+qjbQ=
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
Expand Down
8 changes: 1 addition & 7 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ package config
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"

"github.com/spf13/viper"
)
Expand All @@ -14,15 +12,11 @@ func ViperConfig() (*Config, error) {
viper.SetConfigName(".goji")
viper.SetConfigType("json")

cmd := exec.Command("git", "rev-parse", "--show-toplevel")
gitDirBytes, err := cmd.Output()
gitDir, err := GetGitRootDir()
if err != nil {
return nil, err
}

gitDir := strings.TrimSpace(string(gitDirBytes))
homeDir, _ := os.UserHomeDir()

_, err = os.Stat(filepath.Join(gitDir, ".goji.json"))
if err == nil {
viper.AddConfigPath(gitDir)
Expand Down
60 changes: 24 additions & 36 deletions pkg/config/configInit.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
)

func AddCustomCommitTypes(gitmojis []Gitmoji) []Gitmoji {
customGitmojis := []Gitmoji{
custom := []Gitmoji{
{Emoji: "✨", Code: ":sparkles:", Description: "Introduce new features.", Name: "feat"},
{Emoji: "🐛", Code: ":bug:", Description: "Fix a bug.", Name: "fix"},
{Emoji: "📚", Code: ":books:", Description: "Documentation change.", Name: "docs"},
Expand All @@ -24,7 +24,7 @@ func AddCustomCommitTypes(gitmojis []Gitmoji) []Gitmoji {
{Emoji: "📦", Code: ":package:", Description: "Add or update compiled files or packages.", Name: "package"},
}

return append(gitmojis, customGitmojis...)
return append(gitmojis, custom...)
}

func GetGitRootDir() (string, error) {
Expand All @@ -39,66 +39,54 @@ func GetGitRootDir() (string, error) {
return gitDir, nil
}

func SaveGitmojisToFile(config initConfig, filename string, dir string) error {
viper.Set("Types", config.Types)
viper.Set("Scopes", config.Scopes)
viper.Set("Symbol", config.Symbol)
viper.Set("SkipQuestions", config.SkipQuestions)
viper.Set("SubjectMaxLength", config.SubjectMaxLength)
func SaveConfigToFile(config initConfig, file, dir string) error {
viper.Set("types", config.Types)
viper.Set("scopes", config.Scopes)
viper.Set("symbol", config.Symbol)
viper.Set("skipQuestions", config.SkipQuestions)
viper.Set("subjectMaxLength", config.SubjectMaxLength)
viper.Set("signOff", config.SignOff)

viper.SetConfigName(filename) // name of config file (without extension)
viper.SetConfigType("json") // specifying the config type
viper.AddConfigPath(dir) // path to look for the config file in
viper.SetConfigName(file)
viper.SetConfigType("json")
viper.AddConfigPath(dir)

err := viper.SafeWriteConfig()
if err != nil {
if _, ok := err.(viper.ConfigFileAlreadyExistsError); ok {
err = viper.WriteConfig()
if err != nil {
return fmt.Errorf("error writing config file: %v", err)
}
} else {
return fmt.Errorf("error creating config file: %v", err)
}
if err := viper.WriteConfig(); err != nil {
return fmt.Errorf("error writing config file: %v", err)
}

return nil
}

func InitRepoConfig(global bool, repo bool) error {
func InitRepoConfig(global, repo bool) error {
gitmojis := AddCustomCommitTypes([]Gitmoji{})
config := initConfig{
Types: gitmojis,
Scopes: []string{"home", "accounts", "ci"},
Symbol: true,
SkipQuestions: []string{},
SkipQuestions: nil,
SubjectMaxLength: 50,
SignOff: true,
}

var dir string
var location string
var err error

switch {
case global:
dir, err = os.UserHomeDir()
if err != nil {
return err
}
location, err = os.UserHomeDir()
case repo:
dir, err = GetGitRootDir()
if err != nil {
return err
}
location, err = GetGitRootDir()
default:
return fmt.Errorf("no flag set for location to save configuration file")
}

err = SaveGitmojisToFile(config, ".goji", dir)

if err != nil {
return err
}

if err = SaveConfigToFile(config, ".goji", location); err != nil {
return fmt.Errorf("error saving gitmojis to file: %v", err)
} else {
fmt.Println("Gitmojis saved to .goji.json 🎊")
}

return nil
Expand Down
Loading

0 comments on commit c079f1f

Please sign in to comment.