Files
wxiaoguangandsilverwind b3422c0920 refactor: clean up error system (#40328)
1. `ctx.ServerError("LogMessage", err)` is very messy and useless. When
the log is printed, it already contains the caller's file and line
number
2. `ctx.NotFound(nil)` and `ctx.NotFound(err)` were abused a lot, now
only `ctx.NotFound()`

---------

Co-authored-by: silverwind <me@silverwind.io>
2026-11-11 17:07:57 +00:00

111 lines
2.6 KiB
Go

// Copyright 2015 The Gogs Authors. All rights reserved.
// Copyright 2021 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package git
import (
"errors"
"os"
"path/filepath"
"slices"
"strings"
"gitea.dev/modules/git/gitrepo"
"gitea.dev/modules/util"
)
// hookNames is a list of Git server hooks' name that are supported.
var hookNames = []string{
"pre-receive",
"update",
"post-receive",
}
// IsValidHookName returns true if given name is a valid Git hook.
func IsValidHookName(name string) bool {
return slices.Contains(hookNames, name)
}
// Hook represents a Git hook.
type Hook struct {
name string
IsActive bool // Indicates whether repository has this hook.
Content string // Content of hook if it's active.
Sample string // Sample content from Git.
path string // Hook file path.
}
// GetHook returns a Git hook by given name and repository.
func GetHook(repo RepositoryFacade, name string) (*Hook, error) {
repoPath := gitrepo.RepoLocalPath(repo)
if !IsValidHookName(name) {
return nil, util.NewNotExistErrorf("invalid hook name: %s", name)
}
h := &Hook{
name: name,
path: filepath.Join(repoPath, filepath.Join("hooks", name+".d", name)),
}
if data, err := os.ReadFile(h.path); err == nil {
h.IsActive = true
h.Content = string(data)
return h, nil
} else if !os.IsNotExist(err) {
return nil, err
}
samplePath := filepath.Join(repoPath, "hooks", name+".sample")
if data, err := os.ReadFile(samplePath); err == nil {
h.Sample = string(data)
}
return h, nil
}
// Name return the name of the hook
func (h *Hook) Name() string {
return h.name
}
// Update updates hook settings.
func (h *Hook) Update() error {
if len(strings.TrimSpace(h.Content)) == 0 {
// empty content means to remove the file
err := util.RemoveWithRetry(h.path)
if err != nil && !os.IsNotExist(err) {
return err
}
h.IsActive = false
return nil
}
d := filepath.Dir(h.path)
if err := os.MkdirAll(d, os.ModePerm); err != nil {
return err
}
err := os.WriteFile(h.path, []byte(strings.ReplaceAll(h.Content, "\r", "")), os.ModePerm)
if err != nil {
return err
}
h.IsActive = true
return nil
}
// ListHooks returns a list of Git hooks of given repository.
func ListHooks(repo RepositoryFacade) (_ []*Hook, err error) {
exist, err := util.IsDir(filepath.Join(gitrepo.RepoLocalPath(repo), "hooks"))
if err != nil {
return nil, err
} else if !exist {
return nil, errors.New("hooks path does not exist")
}
hooks := make([]*Hook, len(hookNames))
for i, name := range hookNames {
hooks[i], err = GetHook(repo, name)
if err != nil {
return nil, err
}
}
return hooks, nil
}