Skip to content

Commit

Permalink
create template in temp folder and clean on error
Browse files Browse the repository at this point in the history
  • Loading branch information
StarpTech committed Jan 26, 2018
1 parent 57aabf8 commit 46bd9a2
Show file tree
Hide file tree
Showing 4 changed files with 327 additions and 71 deletions.
38 changes: 14 additions & 24 deletions commands/githook/githook.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"path"

logy "github.com/apex/log"
"github.com/netzkern/butler/utils"
survey "gopkg.in/AlecAivazis/survey.v1"
)

Expand Down Expand Up @@ -35,6 +36,7 @@ type CommandData struct {
// Githook command to create git hooks
type Githook struct {
Path string
GitDir string
CommandData *CommandData
}

Expand All @@ -52,6 +54,13 @@ func New(options ...Option) *Githook {
return v
}

// WithGitDir option.
func WithGitDir(dir string) Option {
return func(g *Githook) {
g.GitDir = dir
}
}

// WithCommandData option.
func WithCommandData(cd *CommandData) Option {
return func(g *Githook) {
Expand All @@ -62,19 +71,19 @@ func WithCommandData(cd *CommandData) Option {
// Install will create hard links from local git_hooks to the corresponding git hooks
func (g *Githook) Install() error {
for _, h := range g.CommandData.Hooks {
hookGitPath := path.Join(g.CommandData.Path, ".git", "hooks", h)
hookGitPath := path.Join(g.GitDir, ".git", "hooks", h)
hookRepoPath := path.Join(g.CommandData.Path, repoHookDir, h)
if !exists(hookGitPath) {
if !utils.Exists(hookGitPath) {
dir := path.Dir(hookGitPath)
logy.Debugf("Path '%s' created", dir)
err := createDirIfNotExist(dir)
err := utils.CreateDirIfNotExist(dir)
if err != nil {
logy.WithError(err).Error("Could not create directory")
}
} else {
os.Remove(hookGitPath)
}
if exists(hookRepoPath) {
if utils.Exists(hookRepoPath) {
logy.Debugf("Create symlink old: %s, new: %s", hookGitPath, hookRepoPath)
err := os.Link(hookRepoPath, hookGitPath)
if err != nil {
Expand All @@ -83,7 +92,7 @@ func (g *Githook) Install() error {
}
logy.Debugf("hook '%s' installed", h)
} else {
logy.Infof("template for hook '%s' could not be found in %s", h, path.Join(g.CommandData.Path, repoHookDir))
logy.Debugf("template for hook '%s' could not be found in %s", h, path.Join(g.CommandData.Path, repoHookDir))
}

}
Expand Down Expand Up @@ -133,22 +142,3 @@ func (g *Githook) StartCommandSurvey() error {
func (g *Githook) Run() error {
return g.Install()
}

func exists(name string) bool {
if _, err := os.Stat(name); err != nil {
if os.IsNotExist(err) {
return false
}
}
return true
}

func createDirIfNotExist(dir string) error {
if _, err := os.Stat(dir); os.IsNotExist(err) {
err = os.MkdirAll(dir, 0755)
if err != nil {
return err
}
}
return nil
}
Loading

0 comments on commit 46bd9a2

Please sign in to comment.