pages-server/pagerouter/target.go
hazycora 4db7fc335c
All checks were successful
Deploy to VPS / build_site (push) Successful in 4s
rework PageRouters heavily
2024-04-05 16:31:05 -05:00

108 lines
2.4 KiB
Go

package pagerouter
import (
"fmt"
"time"
"code.gitea.io/sdk/gitea"
"git.gay/gitgay/pages/cache"
"git.gay/gitgay/pages/forgejo"
"git.gay/gitgay/pages/utils"
)
var (
targetCacheTTL = time.Hour * 24
slightlyStale = targetCacheTTL - time.Minute
targetCache = cache.NewRedisCache[*Target]("target", time.Hour*24)
)
type Target struct {
Repository *forgejo.Repository
SHA string
BasePath string
}
func GetTarget(domain string, path string, options ...cache.CachedCallOptions) (info *Target, err error) {
var cacheOptions cache.CachedCallOptions
if len(options) > 0 {
cacheOptions = options[0]
} else {
cacheOptions = cache.CachedCallOptions{}
}
potentialRepoName := getPotentialRepoName(path)
target, err := utils.ResolveDomain(domain)
if err != nil {
return
}
key := fmt.Sprintf("%s:%s", target.String(), potentialRepoName)
info, err = targetCache.Get(key)
if err == nil {
durationLeft, expiresErr := targetCache.Expires(key)
cachedMoreRecently := expiresErr == nil && durationLeft > slightlyStale
if cachedMoreRecently || !cacheOptions.HardRefresh {
return
}
}
var repository *forgejo.Repository
var branchName string
basePath := "/"
if target.Repository == "pages" && potentialRepoName != "" {
repository, err = getPotentialRepo(target.Owner, potentialRepoName)
if err != nil {
repository = nil
} else if repository != nil {
branchName = "pages"
basePath = fmt.Sprintf("/%s/", potentialRepoName)
}
}
if repository == nil {
repository, err = forgejo.GetRepo(target.Owner, target.Repository)
if err != nil {
return
}
if target.Branch != nil {
branchName = *target.Branch
} else {
branchName = repository.DefaultBranch
for _, branch := range repository.Branches {
if branch.Name == "pages" {
branchName = "pages"
break
}
}
}
}
// Get the SHA of the branch or commit
var sha string
branch, _, err := forgejo.Client.GetRepoBranch(repository.Owner, repository.Name, branchName)
if err != nil {
var commit *gitea.Commit
if commitRegex.MatchString(branchName) {
commit, _, err = forgejo.Client.GetSingleCommit(repository.Owner, repository.Name, branchName)
}
if err != nil {
return
}
sha = commit.SHA
} else {
sha = branch.Commit.ID
}
info = &Target{
Repository: repository,
SHA: sha,
BasePath: basePath,
}
err = targetCache.Set(key, info)
if err != nil {
return
}
return
}