1
// Copyright 2015 The Gogs Authors. All rights reserved.
2
// Copyright 2021 The Gitea Authors. All rights reserved.
3
// SPDX-License-Identifier: MIT
14
"code.gitea.io/gitea/modules/log"
15
"code.gitea.io/gitea/modules/util"
18
// hookNames is a list of Git server hooks' name that are supported.
19
var hookNames = []string{
25
// ErrNotValidHook error when a git hook is not valid
26
var ErrNotValidHook = errors.New("not a valid Git hook")
28
// IsValidHookName returns true if given name is a valid Git hook.
29
func IsValidHookName(name string) bool {
30
for _, hn := range hookNames {
38
// Hook represents a Git hook.
41
IsActive bool // Indicates whether repository has this hook.
42
Content string // Content of hook if it's active.
43
Sample string // Sample content from Git.
44
path string // Hook file path.
47
// GetHook returns a Git hook by given name and repository.
48
func GetHook(repoPath, name string) (*Hook, error) {
49
if !IsValidHookName(name) {
50
return nil, ErrNotValidHook
54
path: path.Join(repoPath, "hooks", name+".d", name),
56
samplePath := filepath.Join(repoPath, "hooks", name+".sample")
58
data, err := os.ReadFile(h.path)
63
h.Content = string(data)
64
} else if isFile(samplePath) {
65
data, err := os.ReadFile(samplePath)
69
h.Sample = string(data)
74
// Name return the name of the hook
75
func (h *Hook) Name() string {
79
// Update updates hook settings.
80
func (h *Hook) Update() error {
81
if len(strings.TrimSpace(h.Content)) == 0 {
83
err := util.Remove(h.path)
91
d := filepath.Dir(h.path)
92
if err := os.MkdirAll(d, os.ModePerm); err != nil {
96
err := os.WriteFile(h.path, []byte(strings.ReplaceAll(h.Content, "\r", "")), os.ModePerm)
104
// ListHooks returns a list of Git hooks of given repository.
105
func ListHooks(repoPath string) (_ []*Hook, err error) {
106
if !isDir(path.Join(repoPath, "hooks")) {
107
return nil, errors.New("hooks path does not exist")
110
hooks := make([]*Hook, len(hookNames))
111
for i, name := range hookNames {
112
hooks[i], err = GetHook(repoPath, name)
121
// HookPathUpdate hook update path
122
HookPathUpdate = "hooks/update"
125
// SetUpdateHook writes given content to update hook of the repository.
126
func SetUpdateHook(repoPath, content string) (err error) {
127
log.Debug("Setting update hook: %s", repoPath)
128
hookPath := path.Join(repoPath, HookPathUpdate)
129
isExist, err := util.IsExist(hookPath)
131
log.Debug("Unable to check if %s exists. Error: %v", hookPath, err)
135
err = util.Remove(hookPath)
137
err = os.MkdirAll(path.Dir(hookPath), os.ModePerm)
142
return os.WriteFile(hookPath, []byte(content), 0o777)