Skip to content

Commit

Permalink
Merge pull request #71 from kcmvp/hook_update
Browse files Browse the repository at this point in the history
 #68: check modified files by lint during hook
  • Loading branch information
kcmvp authored Jan 17, 2024
2 parents 012a782 + 39269b5 commit f75df0b
Show file tree
Hide file tree
Showing 13 changed files with 57 additions and 58 deletions.
7 changes: 2 additions & 5 deletions cmd/action.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package cmd
import (
"errors"
"fmt"
"github.com/kcmvp/gob/shared" //nolint
"os"
"os/exec"
"path/filepath"
Expand Down Expand Up @@ -64,8 +63,6 @@ func execute(cmd *cobra.Command, arg string) error {
if err != nil {
return err
}
msg := fmt.Sprintf("Start %s project", arg)
color.Cyan("%-20s ...... \n", msg)
if plugin, ok := lo.Find(internal.CurProject().Plugins(), func(plugin internal.Plugin) bool {
return plugin.Alias == arg
}); ok {
Expand All @@ -75,7 +72,7 @@ func execute(cmd *cobra.Command, arg string) error {
}); ok {
err = action.B(cmd, arg)
} else {
return fmt.Errorf("can not find command %s", arg)
return fmt.Errorf(color.RedString("can not find command %s", arg))
}
if err == nil {
return afterExecution(cmd, arg)
Expand Down Expand Up @@ -144,7 +141,7 @@ func cleanAction(_ *cobra.Command, _ ...string) error {
func testAction(_ *cobra.Command, args ...string) error {
coverProfile := fmt.Sprintf("-coverprofile=%s/cover.out", internal.CurProject().Target())
testCmd := exec.Command("go", []string{"test", "-v", coverProfile, "./..."}...) //nolint
return shared.StreamCmdOutput(testCmd, fmt.Sprintf("%s/test.log", internal.CurProject().Target()))
return internal.StreamCmdOutput(testCmd, "test")
}

func coverReport(_ *cobra.Command, _ ...string) error {
Expand Down
10 changes: 10 additions & 0 deletions cmd/action_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cmd

import (
"github.com/fatih/color"
"github.com/kcmvp/gob/internal"
"github.com/samber/lo"
"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -55,3 +56,12 @@ func (suite *ActionTestSuite) TestBuiltInActions() {
return item.A
}))
}

func (suite *ActionTestSuite) TestExecute() {
_ = os.Chdir(internal.CurProject().Root())
err := execute(builderCmd, "build")
assert.NoError(suite.T(), err)
err = execute(builderCmd, "build1")
assert.Error(suite.T(), err)
assert.Contains(suite.T(), err.Error(), color.RedString("can not find command %s", "build1"))
}
6 changes: 3 additions & 3 deletions cmd/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ func execValidArgs() []string {
}

func pushDelete(cmd string) bool {
if cmd == internal.PrePushCmd {
if cmd == internal.PrePush {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
line := scanner.Text()
Expand All @@ -55,18 +55,18 @@ func pushDelete(cmd string) bool {
}

func do(execution internal.Execution, cmd *cobra.Command, args ...string) error {
if execution.CmdKey == internal.CommitMsgCmd {
if execution.CmdKey == internal.CommitMsg {
args = append(args, execution.Actions...)
return validateCommitMsg(cmd, args...)
} else {
if pushDelete(execution.CmdKey) {
return nil
}
// process hook
for _, arg := range execution.Actions {
if err := execute(cmd, arg); err != nil {
return errors.New(color.RedString("failed to %s the project \n", arg))
}
color.Green("%s successfully", strings.ToUpper(string(arg[0]))+arg[1:])
}
return nil
}
Expand Down
6 changes: 3 additions & 3 deletions cmd/exec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func TestExecSuite(t *testing.T) {

func (suite *ExecTestSuite) TestActions() {
assert.Equal(suite.T(), 3, len(execValidArgs()))
assert.True(suite.T(), lo.Every(execValidArgs(), []string{internal.CommitMsgCmd, internal.PreCommitCmd, internal.PreCommitCmd}))
assert.True(suite.T(), lo.Every(execValidArgs(), []string{internal.CommitMsg, internal.PreCommit, internal.PreCommit}))
}

func (suite *ExecTestSuite) TestCmdArgs() {
Expand All @@ -49,9 +49,9 @@ func (suite *ExecTestSuite) TestCmdArgs() {
}{
{"no args", []string{}, true},
{"no match", []string{lo.RandomString(10, lo.LettersCharset)}, true},
{"first match", []string{internal.CommitMsgCmd, lo.RandomString(10, lo.LettersCharset)}, false},
{"first match", []string{internal.CommitMsg, lo.RandomString(10, lo.LettersCharset)}, false},
{"second match", []string{lo.RandomString(10, lo.LettersCharset), "msghook"}, true},
{"more than 3", []string{internal.CommitMsgCmd, lo.RandomString(10, lo.AlphanumericCharset),
{"more than 3", []string{internal.CommitMsg, lo.RandomString(10, lo.AlphanumericCharset),
lo.RandomString(10, lo.AlphanumericCharset),
lo.RandomString(10, lo.AlphanumericCharset)},
true,
Expand Down
6 changes: 3 additions & 3 deletions gob.yaml
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
exec:
commit-msg-hook: ^#[0-9]+:\s*.{10,}$
pre-commit-hook:
commit-msg: ^#[0-9]+:\s*.{10,}$
pre-commit:
- lint
- test
pre-push-hook:
pre-push:
- test
plugins:
golangci-lint:
Expand Down
36 changes: 15 additions & 21 deletions internal/hook.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,29 +12,23 @@ import (
const (
execCfgKey = "exec"
//hook script name
commitMsg = "commit-msg"
preCommit = "pre-commit"
prePush = "pre-push"
)

var (
CommitMsgCmd = fmt.Sprintf("%s-hook", commitMsg)
PreCommitCmd = fmt.Sprintf("%s-hook", preCommit)
PrePushCmd = fmt.Sprintf("%s-hook", prePush)
CommitMsg = "commit-msg"
PreCommit = "pre-commit"
PrePush = "pre-push"
)

func HookScripts() map[string]string {
return map[string]string{
commitMsg: fmt.Sprintf("gob exec %s $1", CommitMsgCmd),
preCommit: fmt.Sprintf("gob exec %s", PreCommitCmd),
prePush: fmt.Sprintf("gob exec %s $1 $2", PrePushCmd),
CommitMsg: fmt.Sprintf("gob exec %s $1", CommitMsg),
PreCommit: fmt.Sprintf("gob exec %s", PreCommit),
PrePush: fmt.Sprintf("gob exec %s $1 $2", PrePush),
}
}

type GitHook struct {
CommitMsg string `mapstructure:"commit-msg-hook"`
PreCommit []string `mapstructure:"pre-commit-hook"`
PrePush []string `mapstructure:"pre-push-hook"`
CommitMsg string `mapstructure:"commit-msg"`
PreCommit []string `mapstructure:"pre-commit"`
PrePush []string `mapstructure:"pre-push"`
}

func (project *Project) GitHook() GitHook {
Expand Down Expand Up @@ -67,9 +61,9 @@ func (project *Project) Executions() []Execution {
func (project *Project) SetupHooks(force bool) {
if force {
hook := map[string]any{
fmt.Sprintf("%s.%s", execCfgKey, CommitMsgCmd): "^#[0-9]+:\\s*.{10,}$",
fmt.Sprintf("%s.%s", execCfgKey, PreCommitCmd): []string{"lint", "test"},
fmt.Sprintf("%s.%s", execCfgKey, PrePushCmd): []string{"test"},
fmt.Sprintf("%s.%s", execCfgKey, CommitMsg): "^#[0-9]+:\\s*.{10,}$",
fmt.Sprintf("%s.%s", execCfgKey, PreCommit): []string{"lint", "test"},
fmt.Sprintf("%s.%s", execCfgKey, PrePush): []string{"test"},
}
if err := project.mergeConfig(hook); err != nil {
color.Red("failed to setup hook")
Expand All @@ -83,13 +77,13 @@ func (project *Project) SetupHooks(force bool) {
gitHook := CurProject().GitHook()
var hooks []string
if len(gitHook.CommitMsg) > 0 {
hooks = append(hooks, commitMsg)
hooks = append(hooks, CommitMsg)
}
if len(gitHook.PreCommit) > 0 {
hooks = append(hooks, preCommit)
hooks = append(hooks, PreCommit)
}
if len(gitHook.PrePush) > 0 {
hooks = append(hooks, prePush)
hooks = append(hooks, PrePush)
}
shell := lo.IfF(Windows(), func() string {
return "#!/usr/bin/env pwsh\n"
Expand Down
2 changes: 1 addition & 1 deletion internal/hook_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ func (suite *GitHookTestSuite) TestSetupHook() {
assert.NoError(suite.T(), err)
executions := CurProject().Executions()
assert.Equal(suite.T(), 3, len(executions))
rs := lo.Every([]string{"commit-msg-hook", "pre-commit-hook", "pre-push-hook"}, lo.Map(executions, func(item Execution, _ int) string {
rs := lo.Every([]string{"commit-msg", "pre-commit", "pre-push"}, lo.Map(executions, func(item Execution, _ int) string {
return item.CmdKey
}))
assert.True(suite.T(), rs)
Expand Down
22 changes: 12 additions & 10 deletions shared/multiple_writer.go → internal/multiple_writer.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
package shared
package internal

import (
"bufio"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"time"
Expand All @@ -15,7 +16,7 @@ import (
"github.com/creack/pty"
)

func StreamCmdOutput(cmd *exec.Cmd, file string) error {
func StreamCmdOutput(cmd *exec.Cmd, task string) error {
// Start the command with a pty
var scanner *bufio.Scanner
if ptmx, err := pty.Start(cmd); err == nil {
Expand All @@ -29,9 +30,9 @@ func StreamCmdOutput(cmd *exec.Cmd, file string) error {
return err
}
}

color.HiCyan("Start %s ......\n", task)
// Create a file to save the output
log, err := os.Create(file)
log, err := os.Create(filepath.Join(CurProject().Target(), fmt.Sprintf("%s.log", task)))
if err != nil {
fmt.Println("Error creating file:", err)
return err
Expand All @@ -46,7 +47,7 @@ func StreamCmdOutput(cmd *exec.Cmd, file string) error {
go func() {
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if len(line) > 0 {
if len(line) > 1 {
ch <- line
}
}
Expand All @@ -56,16 +57,16 @@ func StreamCmdOutput(cmd *exec.Cmd, file string) error {
}
}()
ticker := time.NewTicker(150 * time.Millisecond)
inProgress := false
overwrite := true
progress := NewProgress()
for !eof {
select {
case line := <-ch:
progress.Reset()
lineWithoutColor := colorRegex.ReplaceAllString(line, "")
_, err = log.WriteString(lineWithoutColor + "\n")
line = lo.IfF(inProgress, func() string {
inProgress = false
line = lo.IfF(overwrite, func() string {
overwrite = false
return fmt.Sprintf("\r%-20s", line)
}).Else(line)
fmt.Println(line)
Expand All @@ -74,13 +75,14 @@ func StreamCmdOutput(cmd *exec.Cmd, file string) error {
break
}
case <-ticker.C:
if !inProgress {
inProgress = true
if !overwrite {
overwrite = true
}
_ = progress.Add(1)
}
}
_ = progress.Finish()
color.HiCyan("\rFinish %s ......\n", task)
ticker.Stop()
return cmd.Wait()
}
5 changes: 2 additions & 3 deletions internal/plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"errors"
"fmt"
"github.com/fatih/color"
"github.com/kcmvp/gob/shared"
"github.com/samber/lo"
"io/fs"
"os"
Expand Down Expand Up @@ -98,7 +97,7 @@ func (plugin Plugin) Name() string {
return plugin.name
}

func (plugin Plugin) logName() string {
func (plugin Plugin) taskName() string {
return lo.If(len(plugin.Alias) > 0, plugin.Alias).Else(plugin.Name())
}

Expand Down Expand Up @@ -150,7 +149,7 @@ func (plugin Plugin) Execute() error {
return err
}
pCmd := exec.Command(plugin.Binary(), strings.Split(plugin.Args, " ")...) //nolint #gosec
if err := shared.StreamCmdOutput(pCmd, filepath.Join(CurProject().Target(), fmt.Sprintf("%s.log", plugin.logName()))); err != nil {
if err := StreamCmdOutput(pCmd, plugin.taskName()); err != nil {
return err
}
if pCmd.ProcessState.ExitCode() != 0 {
Expand Down
2 changes: 1 addition & 1 deletion internal/plugin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ func (suite *InternalPluginTestSuit) TestNewPlugin() {
for _, test := range tests {
suite.T().Run(test.name, func(t *testing.T) {
plugin, err := NewPlugin(test.url)
assert.Equal(t, plugin.logName(), test.logName)
assert.Equal(t, plugin.taskName(), test.logName)
assert.Equal(t, plugin.Binary(), test.binary)
assert.True(t, test.wantErr == (err != nil))
if !test.wantErr {
Expand Down
5 changes: 1 addition & 4 deletions shared/progress.go → internal/progress.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package shared
package internal

import (
"fmt"
Expand All @@ -15,9 +15,6 @@ func NewProgress() *progressbar.ProgressBar {
progressbar.OptionSpinnerCustom(lo.Map(spinner, func(item string, idx int) string {
return fmt.Sprintf("[yellow]%s", item)
})),
progressbar.OptionOnCompletion(func() {
fmt.Printf("\r%-50s\n", " ")
}),
progressbar.OptionFullWidth(),
progressbar.OptionSetRenderBlankState(true),
progressbar.OptionEnableColorCodes(true),
Expand Down
2 changes: 1 addition & 1 deletion internal/project_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func (suite *ProjectTestSuite) SetupSuite() {
}

func (suite *ProjectTestSuite) TearDownSuite() {
os.RemoveAll(suite.testDir)
//os.RemoveAll(suite.testDir)
os.RemoveAll(suite.goPath)
}

Expand Down
6 changes: 3 additions & 3 deletions testdata/gob.yaml
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
exec:
commit-msg-hook: ^#[0-9]+:\s*.{10,}$
pre-commit-hook:
commit-msg: ^#[0-9]+:\s*.{10,}$
pre-commit:
- lint
- test
pre-push-hook:
pre-push:
- test
plugins:
depth:
Expand Down

0 comments on commit f75df0b

Please sign in to comment.