projects

showcase

A public git mirror

refactor: trim gitea client and link ordering

daniel daum committed parent 218f53a commit 9215a2c

Showing 5 changed files with 55 additions and 70 deletions.

internal/build/build.go +9 −25
@@ -2,11 +2,13 @@22package build3344import (5	"cmp"56	"context"67	"errors"78	"fmt"89	"html/template"910	"log/slog"11	"maps"1012	"path/filepath"1113	"slices"1214	"strings"@@ -124,33 +126,15 @@ func (b *Builder) Render(ctx context.Context, dir string) error {124126	return nil125127}126128127var linkOrder = []string{"website", "atproto", "tangled", "github"}128var linkNames = map[string]string{"website": "website", "atproto": "bluesky", "tangled": "tangled", "github": "github"}129129// links orders the footer links: known keys first, then the rest by key.130130func links(m map[string]string) []render.Link {131	keys := make([]string, 0, len(m))132	for k := range m {133		keys = append(keys, k)134	}135	rank := func(k string) int {136		if i := slices.Index(linkOrder, k); i >= 0 {137			return i138		}139		return len(linkOrder)140	}141	slices.SortFunc(keys, func(a, c string) int {142		if d := rank(a) - rank(c); d != 0 {143			return d144		}145		return strings.Compare(a, c)146	})147	out := make([]render.Link, 0, len(keys))148	for _, k := range keys {149		name := linkNames[k]150		if name == "" {151			name = k131	seen := map[string]bool{}132	var out []render.Link133	for _, k := range append([]string{"website", "atproto", "tangled", "github"}, slices.Sorted(maps.Keys(m))...) {134		if u, ok := m[k]; ok && !seen[k] {135			seen[k] = true136			out = append(out, render.Link{Name: cmp.Or(map[string]string{"atproto": "bluesky"}[k], k), URL: u})152137		}153		out = append(out, render.Link{Name: name, URL: m[k]})154138	}155139	return out156140}
internal/build/extra.go +1 −2
@@ -59,7 +59,6 @@ func (b *Builder) renderExtras(rd *render.Renderer, dir string, r *repo) error {5959	}60606161	pkgs := ExtraPage{Repo: r, Tab: "packages"}62	host := strings.TrimPrefix(strings.TrimPrefix(b.Cfg.SiteURL, "https://"), "http://")6362	for _, x := range r.Packages {6463		if strings.HasPrefix(x.Version, "sha256:") {6564			continue // untagged image manifests@@ -69,7 +68,7 @@ func (b *Builder) renderExtras(rd *render.Renderer, dir string, r *repo) error {6968			if !b.Cfg.HasImage(x.Name) {7069				continue // not pullable through the proxy, so don't advertise it7170			}72			v.Command = "docker pull " + host + "/" + b.Cfg.User + "/" + x.Name + ":" + x.Version71			v.Command = "docker pull " + siteHost(b.Cfg.SiteURL) + "/" + b.Cfg.User + "/" + x.Name + ":" + x.Version7372		}7473		pkgs.Packages = append(pkgs.Packages, v)7574	}
internal/build/repo.go +5 −2
@@ -261,6 +261,9 @@ func isImage(name string) bool {261261}262262263263func goImport(siteURL, name string) string {264	host := strings.TrimPrefix(strings.TrimPrefix(siteURL, "https://"), "http://")265	return host + "/" + name + " git " + siteURL + "/" + name + ".git"264	return siteHost(siteURL) + "/" + name + " git " + siteURL + "/" + name + ".git"265}266267func siteHost(siteURL string) string {268	return strings.TrimPrefix(strings.TrimPrefix(siteURL, "https://"), "http://")266269}
internal/gitea/gitea.go +26 −40
@@ -43,7 +43,6 @@ type User struct {4343	FullName    string `json:"full_name"`4444	AvatarURL   string `json:"avatar_url"`4545	Description string `json:"description"`46	Website     string `json:"website"`4746	Location    string `json:"location"`4847}4948@@ -61,9 +60,7 @@ type Repo struct {6160}62616362type Asset struct {64	Name        string `json:"name"`65	Size        int64  `json:"size"`66	DownloadURL string `json:"browser_download_url"`63	Name string `json:"name"` // the download URL is rebuilt, never Gitea's6764}68656966type Release struct {@@ -89,31 +86,38 @@ type PullRequest struct {8986}90879188type Package struct {92	Name       string    `json:"name"`93	Type       string    `json:"type"`94	Version    string    `json:"version"`95	CreatedAt  time.Time `json:"created_at"`96	Repository *Repo     `json:"repository"`89	Name       string `json:"name"`90	Type       string `json:"type"`91	Version    string `json:"version"`92	Repository *Repo  `json:"repository"`9793}989499func (c *Client) get(ctx context.Context, path string, v any) error {95// fetch GETs base+path (never anything else) without credentials.96func (c *Client) fetch(ctx context.Context, path string) ([]byte, error) {10097	req, err := http.NewRequestWithContext(ctx, "GET", c.base+path, nil)10198	if err != nil {102		return err99		return nil, err103100	}104	req.Header.Set("Accept", "application/json")105101	resp, err := c.http.Do(req)106102	if err != nil {107		return err103		return nil, err108104	}109105	defer resp.Body.Close()110106	if resp.StatusCode == http.StatusNotFound {111		return fmt.Errorf("GET %s: %w", path, ErrNotFound)107		return nil, fmt.Errorf("GET %s: %w", path, ErrNotFound)112108	}113109	if resp.StatusCode != http.StatusOK {114		return fmt.Errorf("gitea: GET %s: %s", path, resp.Status)110		return nil, fmt.Errorf("gitea: GET %s: %s", path, resp.Status)111	}112	return io.ReadAll(io.LimitReader(resp.Body, maxBody))113}114115func (c *Client) get(ctx context.Context, path string, v any) error {116	b, err := c.fetch(ctx, path)117	if err != nil {118		return err115119	}116	return json.NewDecoder(io.LimitReader(resp.Body, maxBody)).Decode(v)120	return json.Unmarshal(b, v)117121}118122119123func (c *Client) repoPath(repo, rest string) string {@@ -186,39 +190,21 @@ func (c *Client) Packages(ctx context.Context, repos []string) ([]Package, error186190	return out, nil187191}188192189// Avatar fetches the user's avatar image. Gitea builds avatar URLs from its190// ROOT_URL, so Gitea-hosted avatars are re-fetched through the configured base.193// Avatar fetches the user's avatar. Gitea builds avatar URLs from its194// ROOT_URL, so only the path is kept and fetched from the configured base.191195func (c *Client) Avatar(ctx context.Context, avatarURL string) ([]byte, string, error) {192196	u, err := url.Parse(avatarURL)193197	if err != nil {194198		return nil, "", err195199	}196	target := avatarURL197	if strings.HasPrefix(u.Path, "/avatars/") || strings.HasPrefix(u.Path, "/avatar/") {198		target = c.base + u.RequestURI()199	} else if u.Scheme != "https" {200		return nil, "", fmt.Errorf("gitea: unsupported avatar url %q", avatarURL)201	}202	req, err := http.NewRequestWithContext(ctx, "GET", target, nil)203	if err != nil {204		return nil, "", err205	}206	resp, err := c.http.Do(req)207	if err != nil {208		return nil, "", err209	}210	defer resp.Body.Close()211	if resp.StatusCode != http.StatusOK {212		return nil, "", fmt.Errorf("gitea: avatar: %s", resp.Status)213	}214	b, err := io.ReadAll(io.LimitReader(resp.Body, 2<<20))200	b, err := c.fetch(ctx, u.RequestURI())215201	if err != nil {216202		return nil, "", err217203	}218	ct := http.DetectContentType(b)219	switch ct {204	switch ct := http.DetectContentType(b); ct {220205	case "image/png", "image/jpeg", "image/gif", "image/webp":221206		return b, ct, nil207	default:208		return nil, "", fmt.Errorf("gitea: avatar has type %s", ct)222209	}223	return nil, "", fmt.Errorf("gitea: avatar has type %s", ct)224210}
justfile +14 −1
@@ -16,6 +16,19 @@ lint:1616    test -z "$(gofmt -l .)" || { gofmt -l .; exit 1; }1717    go vet ./...181819# Lint the Dockerfile20lint-docker:21    hadolint Dockerfile2223# Print the current digests of the pinned base images, to compare with the Dockerfile24digests:25    @echo "golang:1.27.4-alpine3.24 $(crane digest golang:1.27.4-alpine3.24)"26    @echo "alpine:3.24.4            $(crane digest alpine:3.24.4)"2728# Build the image (needs Docker, e.g. on the host)29image:30    docker build -t daumdev:latest .311932# Build the binary into ./bin2033build:2134    CGO_ENABLED=0 go build -trimpath -o bin/daumdev ./cmd/daumdev@@ -44,4 +57,4 @@ demo:44574558# Count Go lines (budget: ~1,800, excluding tests, templates and CSS)4659loc:47    find . -name '*.go' ! -name '*_test.go' -print0 | xargs -0 cat | wc -l60    find cmd internal web -name '*.go' ! -name '*_test.go' -print0 | xargs -0 cat | wc -l