Skip to content

Commit

Permalink
feat: init creates hooks dir in root git dir
Browse files Browse the repository at this point in the history
This also makes `commitlint init` only possible
from git repository directory
  • Loading branch information
muthukrishnan24 committed Sep 22, 2021
1 parent cd42e21 commit e007af6
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 7 deletions.
17 changes: 10 additions & 7 deletions cmd/callback.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package cmd
import (
"fmt"
"os"
"path/filepath"

"github.com/urfave/cli/v2"

Expand All @@ -20,14 +19,13 @@ const (
)

func initCallback(ctx *cli.Context) (retErr error) {
// get user home dir
homeDir, err := os.UserHomeDir()
isGlobal := ctx.Bool("global")

hookDir, err := getHookDir(isGlobal)
if err != nil {
return err
}

// create hooks dir
hookDir := filepath.Join(homeDir, filepath.Clean(HookDir))
err = os.MkdirAll(hookDir, os.ModePerm)
if err != nil {
return err
Expand All @@ -39,8 +37,13 @@ func initCallback(ctx *cli.Context) (retErr error) {
return err
}

isGlobal := ctx.Bool("global")
return setGitConf(hookDir, isGlobal)
err = setGitConf(hookDir, isGlobal)
if err != nil {
return err
}

fmt.Println("commitlint init successfully")
return nil
}

func lintCallback(ctx *cli.Context) error {
Expand Down
45 changes: 45 additions & 0 deletions cmd/util.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package cmd

import (
"bytes"
"io"
"os"
"os/exec"
"path/filepath"
"strings"

"github.com/conventionalcommit/commitlint/config"
Expand Down Expand Up @@ -60,6 +62,7 @@ func setGitConf(hookDir string, isGlobal bool) error {
args = append(args, "core.hooksPath", hookDir)

cmd := exec.Command("git", args...)
cmd.Stderr = os.Stderr
return cmd.Run()
}

Expand Down Expand Up @@ -105,3 +108,45 @@ func readStdInPipe() (string, error) {
s := string(readBytes)
return strings.TrimSpace(s), nil
}

func getHookDir(isGlobal bool) (string, error) {
baseDir := filepath.Clean(HookDir)

if isGlobal {
// get user home dir
homeDir, err := os.UserHomeDir()
if err != nil {
return "", err
}

// create hooks dir
hookDir := filepath.Join(homeDir, baseDir)
return hookDir, nil
}

gitDir, err := getRepoRootDir()
if err != nil {
return "", err
}
return filepath.Join(gitDir, baseDir), nil
}

func getRepoRootDir() (string, error) {
byteOut := &bytes.Buffer{}

cmd := exec.Command("git", "rev-parse", "--git-dir")
cmd.Stdout = byteOut
cmd.Stderr = os.Stderr

err := cmd.Run()
if err != nil {
return "", err
}

gitDir := filepath.Clean(byteOut.String())

// remove /.git at last
gitDir = filepath.Dir(gitDir)

return gitDir, nil
}

0 comments on commit e007af6

Please sign in to comment.