feat: Add tests for the repository picking behaviour
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful

This commit is contained in:
2024-01-06 14:47:47 +01:00
parent 3692168346
commit 493758f56f
9 changed files with 555 additions and 105 deletions

View File

@@ -1,22 +1,18 @@
package pages
import (
"fmt"
"io"
"mime"
"net/http"
"strings"
"time"
"git.polynom.me/rio/internal/constants"
"git.polynom.me/rio/internal/repo"
"github.com/patrickmn/go-cache"
log "github.com/sirupsen/logrus"
)
const (
// The branch name on which files must reside.
PagesBranch = "pages"
)
var (
pageCache = cache.New(6*time.Hour, 1*time.Hour)
)
@@ -31,7 +27,7 @@ func makePageContentCacheEntry(username, path string) string {
return username + ":" + path
}
func ServeFile(username, reponame, path, giteaUrl string, w http.ResponseWriter) {
func ServeFile(username, reponame, path string, giteaClient *repo.GiteaClient, w http.ResponseWriter) {
// Provide a default
if path == "" {
path = "/index.html"
@@ -47,30 +43,23 @@ func ServeFile(username, reponame, path, giteaUrl string, w http.ResponseWriter)
var content []byte
var mimeType string
var err error
var since *time.Time = nil
if found {
log.Debugf("Returning %s from cache", path)
content = entry.(PageContentCache).Content
mimeType = entry.(PageContentCache).mimeType
sinceRaw := entry.(PageContentCache).RequestedAt
since = &sinceRaw
}
// We have to do the raw request manually because the Gitea SDK does not allow
// passing the If-Modfied-Since header.
apiUrl := fmt.Sprintf(
"%s/api/v1/repos/%s/%s/raw/%s?ref=%s",
giteaUrl,
content, changed, err := giteaClient.GetFile(
username,
reponame,
constants.PagesBranch,
path,
PagesBranch,
since,
)
client := &http.Client{}
req, err := http.NewRequest("GET", apiUrl, nil)
if found {
since := entry.(PageContentCache).RequestedAt.Format(time.RFC1123)
log.Debugf("Found %s in cache. Adding '%s' as If-Modified-Since", key, since)
req.Header.Add("If-Modified-Since", since)
}
resp, err := client.Do(req)
if err != nil {
if !found {
log.Errorf("Failed to get file %s/%s/%s (%s)", username, reponame, path, err)
@@ -84,10 +73,8 @@ func ServeFile(username, reponame, path, giteaUrl string, w http.ResponseWriter)
return
}
defer resp.Body.Close()
log.Debugf("Gitea API request returned %d", resp.StatusCode)
if found && resp.StatusCode == 302 {
if found && !changed {
log.Debugf("Page %s is unchanged and cached in memory", path)
w.WriteHeader(200)
w.Header().Set("Content-Type", mimeType)
@@ -95,19 +82,6 @@ func ServeFile(username, reponame, path, giteaUrl string, w http.ResponseWriter)
return
}
// Correctly propagate 404s.
if resp.StatusCode == 404 {
w.WriteHeader(404)
return
}
content, err = io.ReadAll(resp.Body)
if err != nil {
log.Errorf("Failed to get file %s/%s/%s (%s)", username, reponame, path, err)
w.WriteHeader(404)
return
}
pathParts := strings.Split(path, ".")
ext := pathParts[len(pathParts)-1]
mimeType = mime.TypeByExtension("." + ext)