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

Add logrus integration #107

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all 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: 1 addition & 2 deletions cmd/add.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package cmd

import (
"io/ioutil"
"log"
"os/exec"
"path/filepath"
"strings"
Expand Down Expand Up @@ -97,7 +96,7 @@ fi
panic("Can`t rename " + hookName + " to " + hookName + ".old File already exists")
}
e := fs.Rename(pathToFile, pathToFile+".old")
log.Println("Existed " + hookName + " hook renamed to " + hookName + ".old")
loggerClient.Info("Existed " + hookName + " hook renamed to " + hookName + ".old")
check(e)
}
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/cmd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func TestInstallCmdExecutor(t *testing.T) {
"prepare-commit-msg",
}

files, err := afero.ReadDir(fs,getGitHooksDir())
files, err := afero.ReadDir(fs, getGitHooksDir())
assert.NoError(t, err)

actualFiles := []string{}
Expand Down
9 changes: 4 additions & 5 deletions cmd/install.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"encoding/hex"
"io"
"io/ioutil"
"log"
"path/filepath"
"regexp"
"strings"
Expand Down Expand Up @@ -58,8 +57,8 @@ func init() {
// InstallCmdExecutor execute basic configuration
func InstallCmdExecutor(args []string, fs afero.Fs) {
if hasValidConfigFile(fs) {
loggerClient.Debug(au.Cyan("SYNCING"), au.Bold("lefthook.yml"))
if !isConfigSync(fs) || force || aggressive {
log.Println(au.Cyan("SYNCING"), au.Bold("lefthook.yml"))
DeleteGitHooks(fs)
AddGitHooks(fs)
}
Expand Down Expand Up @@ -109,7 +108,7 @@ func AddConfigYaml(fs afero.Fs) {

err := afero.WriteFile(fs, getConfigYamlPath(), []byte(template), defaultDirPermission)
check(err)
log.Println("Added config: ", getConfigYamlPath())
loggerClient.Info("Added config: ", getConfigYamlPath())
}

// AddGitHooks write existed directories in source_dir as hooks in .git/hooks
Expand All @@ -135,7 +134,7 @@ func AddGitHooks(fs afero.Fs) {
unionHooks := append(dirsHooks, configHooks...)
unionHooks = append(unionHooks, checkSumHook) // add special hook for Sync config
unionHooks = uniqueStrSlice(unionHooks)
log.Println(au.Cyan("SERVED HOOKS:"), au.Bold(strings.Join(unionHooks, ", ")))
loggerClient.Info(au.Cyan("SERVED HOOKS:"), au.Bold(strings.Join(unionHooks, ", ")))

for _, key := range unionHooks {
addHook(key, fs)
Expand All @@ -157,7 +156,7 @@ func getConfigLocalYamlPattern() string {
func hasValidConfigFile(fs afero.Fs) bool {
matches, err := afero.Glob(fs, getConfigYamlPattern())
if err != nil {
log.Println("Error occured for search config file: ", err.Error())
loggerClient.Error("Error occured for search config file: ", err.Error())
}
for _, match := range matches {
extension := filepath.Ext(match)
Expand Down
16 changes: 9 additions & 7 deletions cmd/root.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package cmd

import (
"log"
"github.com/Arkweid/lefthook/logger"
"os"
"os/exec"
"path/filepath"
Expand Down Expand Up @@ -30,7 +30,10 @@ var (
Verbose bool
NoColors bool
rootPath string
logLevel string
loggerClient *logger.Logger
cfgFile string

originConfig *viper.Viper
configFileExtensions = []string{".yml", ".yaml"}

Expand All @@ -48,7 +51,7 @@ lefthook install`,
func Execute() {
defer func() {
if r := recover(); r != nil {
log.Println(r)
loggerClient.Panic(r)
os.Exit(1)
}
}()
Expand All @@ -60,21 +63,20 @@ func Execute() {
func init() {
rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")
rootCmd.PersistentFlags().BoolVar(&NoColors, "no-colors", false, "disable colored output")

rootCmd.PersistentFlags().StringVarP(&logLevel, "log-level", "l", logger.Debug.String(), "set log level")
initAurora()
cobra.OnInitialize(initConfig)
level, _ := logger.TransformLogLevel(logLevel)
loggerClient = logger.GetInstance(level)
// re-init Aurora after config reading because `colors` can be specified in config
cobra.OnInitialize(initAurora)
log.SetOutput(os.Stdout)
}

func initAurora() {
au = aurora.NewAurora(EnableColors())
}

func initConfig() {
log.SetFlags(0)

setRootPath(rootExecutionRelPath)

// store original config before merge
Expand Down Expand Up @@ -156,6 +158,6 @@ func EnableColors() bool {
// VerbosePrint print text if Verbose flag persist
func VerbosePrint(v ...interface{}) {
if Verbose {
log.Println(v...)
loggerClient.Debug(v...)
}
}
47 changes: 23 additions & 24 deletions cmd/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"errors"
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"
Expand Down Expand Up @@ -95,7 +94,7 @@ func RunCmdExecutor(args []string, fs afero.Fs) error {
return nil
}
if !isVersionOk() {
log.Println(au.Brown("Config error! Current Lefhook version lower than config version or 'min_version' incorrect, check format: '0.6.0'"))
loggerClient.Error(au.Brown("Config error! Current Lefhook version lower than config version or 'min_version' incorrect, check format: '0.6.0'"))
return errors.New("Current Lefhook version lower than config version or 'min_version' incorrect")
}
if tags := os.Getenv("LEFTHOOK_EXCLUDE"); tags != "" {
Expand All @@ -110,11 +109,11 @@ func RunCmdExecutor(args []string, fs afero.Fs) error {
var wg sync.WaitGroup

startTime := time.Now()
log.Println(au.Cyan("Lefthook v" + version))
log.Println(au.Cyan("RUNNING HOOKS GROUP:"), au.Bold(hooksGroup))
loggerClient.Debug(au.Cyan("Lefthook v" + version))
loggerClient.Debug(au.Cyan("RUNNING HOOKS GROUP:"), au.Bold(hooksGroup))

if isPipedAndParallel(hooksGroup) {
log.Println(au.Brown("Config error! Conflicted options 'piped' and 'parallel'. Remove one of this option from hook group."))
loggerClient.Error(au.Brown("Config error! Conflicted options 'piped' and 'parallel'. Remove one of this option from hook group."))
return errors.New("Piped and Parallel options in conflict")
}

Expand Down Expand Up @@ -172,7 +171,7 @@ func executeCommand(hooksGroup, commandName string, wg *sync.WaitGroup) {

if getPiped(hooksGroup) && isPipeBroken {
mutex.Lock()
log.Println("\n", au.Bold(commandName), au.Brown("(SKIP BY BROKEN PIPE)"))
loggerClient.Info("\n", au.Bold(commandName), au.Brown("(SKIP BY BROKEN PIPE)"))
mutex.Unlock()
return
}
Expand Down Expand Up @@ -224,19 +223,19 @@ func executeCommand(hooksGroup, commandName string, wg *sync.WaitGroup) {

if isSkipCommmand(hooksGroup, commandName) {
mutex.Lock()
log.Println("\n", au.Bold(commandName), au.Brown("(SKIP BY SETTINGS)"))
loggerClient.Info("\n", au.Bold(commandName), au.Brown("(SKIP BY SETTINGS)"))
mutex.Unlock()
return
}
if result, _ := arrop.Intersect(getExcludeTags(hooksGroup), getTags(hooksGroup, commandsConfigKey, commandName)); len(result.Interface().([]string)) > 0 {
mutex.Lock()
log.Println("\n", au.Bold(commandName), au.Brown("(SKIP BY TAGS)"))
loggerClient.Info("\n", au.Bold(commandName), au.Brown("(SKIP BY TAGS)"))
mutex.Unlock()
return
}
if len(files) < 1 && isSkipEmptyCommmand(hooksGroup, commandName) {
mutex.Lock()
log.Println("\n", au.Bold(commandName), au.Brown("(SKIP. NO FILES FOR INSPECTING)"))
loggerClient.Info("\n", au.Bold(commandName), au.Brown("(SKIP. NO FILES FOR INSPECTING)"))
mutex.Unlock()
return
}
Expand All @@ -245,11 +244,11 @@ func executeCommand(hooksGroup, commandName string, wg *sync.WaitGroup) {
mutex.Lock()
defer mutex.Unlock()

log.Println(au.Cyan("\n EXECUTE >"), au.Bold(commandName))
loggerClient.Debug(au.Cyan("\n EXECUTE >"), au.Bold(commandName))
if err != nil {
failList = append(failList, commandName)
setPipeBroken()
log.Println(err)
loggerClient.Error(err)
return
}

Expand All @@ -274,7 +273,7 @@ func executeScript(hooksGroup, source string, executable os.FileInfo, wg *sync.W

if getPiped(hooksGroup) && isPipeBroken {
mutex.Lock()
log.Println("\n", au.Bold(executableName), au.Brown("(SKIP BY BROKEN PIPE)"))
loggerClient.Info("\n", au.Bold(executableName), au.Brown("(SKIP BY BROKEN PIPE)"))
mutex.Unlock()
return
}
Expand All @@ -299,19 +298,19 @@ func executeScript(hooksGroup, source string, executable os.FileInfo, wg *sync.W

if !isScriptExist(hooksGroup, executableName) {
mutex.Lock()
log.Println("\n", au.Bold(executableName), au.Brown("(SKIP BY NOT EXIST IN CONFIG)"))
loggerClient.Info("\n", au.Bold(executableName), au.Brown("(SKIP BY NOT EXIST IN CONFIG)"))
mutex.Unlock()
return
}
if isSkipScript(hooksGroup, executableName) {
mutex.Lock()
log.Println("\n", au.Bold(executableName), au.Brown("(SKIP BY SETTINGS)"))
loggerClient.Info("\n", au.Bold(executableName), au.Brown("(SKIP BY SETTINGS)"))
mutex.Unlock()
return
}
if result, _ := arrop.Intersect(getExcludeTags(hooksGroup), getTags(hooksGroup, scriptsConfigKey, executableName)); len(result.Interface().([]string)) > 0 {
mutex.Lock()
log.Println("\n", au.Bold(executableName), au.Brown("(SKIP BY TAGS)"))
loggerClient.Info("\n", au.Bold(executableName), au.Brown("(SKIP BY TAGS)"))
mutex.Unlock()
return
}
Expand All @@ -320,15 +319,15 @@ func executeScript(hooksGroup, source string, executable os.FileInfo, wg *sync.W
mutex.Lock()
defer mutex.Unlock()

log.Println(au.Cyan("\n EXECUTE >"), au.Bold(executableName))
loggerClient.Info(au.Cyan("\n EXECUTE >"), au.Bold(executableName))
if os.IsPermission(err) {
log.Println(au.Brown("(SKIP NOT EXECUTABLE FILE)"))
loggerClient.Error(au.Brown("(SKIP NOT EXECUTABLE FILE)"))
return
}
if err != nil {
failList = append(failList, executableName)
log.Println(err)
log.Println(au.Brown("TIP: Command start failed. Checkout `runner:` option for this script"))
loggerClient.Error(err)
loggerClient.Error(au.Brown("TIP: Command start failed. Checkout `runner:` option for this script"))
setPipeBroken()
return
}
Expand Down Expand Up @@ -376,17 +375,17 @@ func getRunner(hooksGroup, source, executableName string) string {

func printSummary(execTime time.Duration) {
if len(okList) == 0 && len(failList) == 0 {
log.Println(au.Cyan("\nSUMMARY:"), au.Brown("(SKIP EMPTY)"))
loggerClient.Info(au.Cyan("\nSUMMARY:"), au.Brown("(SKIP EMPTY)"))
} else {
log.Println(au.Cyan(fmt.Sprintf("\nSUMMARY: (done in %.2f seconds)", execTime.Seconds())))
loggerClient.Info(au.Cyan(fmt.Sprintf("\nSUMMARY: (done in %.2f seconds)", execTime.Seconds())))
}

for _, fileName := range okList {
log.Printf("✔️ %s\n", au.Green(fileName))
loggerClient.Infof("✔️ %s\n", au.Green(fileName))
}

for _, fileName := range failList {
log.Printf("🥊 %s", au.Red(fileName))
loggerClient.Infof("🥊 %s", au.Red(fileName))
}
}

Expand Down Expand Up @@ -584,7 +583,7 @@ func isExecutable(executable os.FileInfo) error {

func makeExecutable(path string) {
if err := os.Chmod(path, execMode); err != nil {
log.Fatal(err)
loggerClient.Fatal(err)
}
}

Expand Down
Loading