-
Notifications
You must be signed in to change notification settings - Fork 128
/
repo_hook.go
76 lines (68 loc) · 1.86 KB
/
repo_hook.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Copyright 2015 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package git
import (
"io/ioutil"
"os"
"path/filepath"
)
// DefaultHooksDir is the default directory for Git hooks.
const DefaultHooksDir = "hooks"
// NewHook creates and returns a new hook with given name. Update method must be
// called to actually save the hook to disk.
func (r *Repository) NewHook(dir string, name HookName) *Hook {
return &Hook{
name: name,
path: filepath.Join(r.path, dir, string(name)),
}
}
// Hook returns a Git hook by given name in the repository. Giving empty
// directory will use the default directory. It returns an os.ErrNotExist if
// both active and sample hook do not exist.
func (r *Repository) Hook(dir string, name HookName) (*Hook, error) {
if dir == "" {
dir = DefaultHooksDir
}
// 1. Check if there is an active hook.
fpath := filepath.Join(r.path, dir, string(name))
if isFile(fpath) {
p, err := ioutil.ReadFile(fpath)
if err != nil {
return nil, err
}
return &Hook{
name: name,
path: fpath,
content: string(p),
}, nil
}
// 2. Check if sample content exists.
sample := ServerSideHookSamples[name]
if sample != "" {
return &Hook{
name: name,
path: fpath,
isSample: true,
content: sample,
}, nil
}
return nil, os.ErrNotExist
}
// Hooks returns a list of Git hooks found in the repository. Giving empty
// directory will use the default directory. It may return an empty slice when
// no hooks found.
func (r *Repository) Hooks(dir string) ([]*Hook, error) {
hooks := make([]*Hook, 0, len(ServerSideHooks))
for _, name := range ServerSideHooks {
h, err := r.Hook(dir, name)
if err != nil {
if err == os.ErrNotExist {
continue
}
return nil, err
}
hooks = append(hooks, h)
}
return hooks, nil
}