1
0
Fork 0
mirror of https://codeberg.org/forgejo/forgejo.git synced 2024-12-24 13:09:23 -05:00
forgejo/services/repository/hooks.go
zeripath 5cb0c9aa0d
Propagate context and ensure git commands run in request context (#17868)
This PR continues the work in #17125 by progressively ensuring that git
commands run within the request context.

This now means that the if there is a git repo already open in the context it will be used instead of reopening it.

Signed-off-by: Andrew Thornton <art27@cantab.net>
2022-01-19 23:26:57 +00:00

86 lines
2.2 KiB
Go

// Copyright 2021 The Gitea 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 repository
import (
"context"
"fmt"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/log"
repo_module "code.gitea.io/gitea/modules/repository"
"xorm.io/builder"
)
// SyncRepositoryHooks rewrites all repositories' pre-receive, update and post-receive hooks
// to make sure the binary and custom conf path are up-to-date.
func SyncRepositoryHooks(ctx context.Context) error {
log.Trace("Doing: SyncRepositoryHooks")
if err := db.Iterate(
db.DefaultContext,
new(repo_model.Repository),
builder.Gt{"id": 0},
func(idx int, bean interface{}) error {
repo := bean.(*repo_model.Repository)
select {
case <-ctx.Done():
return db.ErrCancelledf("before sync repository hooks for %s", repo.FullName())
default:
}
if err := repo_module.CreateDelegateHooks(repo.RepoPath()); err != nil {
return fmt.Errorf("SyncRepositoryHook: %v", err)
}
if repo.HasWiki() {
if err := repo_module.CreateDelegateHooks(repo.WikiPath()); err != nil {
return fmt.Errorf("SyncRepositoryHook: %v", err)
}
}
return nil
},
); err != nil {
return err
}
log.Trace("Finished: SyncRepositoryHooks")
return nil
}
// GenerateGitHooks generates git hooks from a template repository
func GenerateGitHooks(ctx context.Context, templateRepo, generateRepo *repo_model.Repository) error {
generateGitRepo, err := git.OpenRepositoryCtx(ctx, generateRepo.RepoPath())
if err != nil {
return err
}
defer generateGitRepo.Close()
templateGitRepo, err := git.OpenRepositoryCtx(ctx, templateRepo.RepoPath())
if err != nil {
return err
}
defer templateGitRepo.Close()
templateHooks, err := templateGitRepo.Hooks()
if err != nil {
return err
}
for _, templateHook := range templateHooks {
generateHook, err := generateGitRepo.GetHook(templateHook.Name())
if err != nil {
return err
}
generateHook.Content = templateHook.Content
if err := generateHook.Update(); err != nil {
return err
}
}
return nil
}