feat: 发行版功能与主页板块,AI 更新说明基于 diff 正文与提交正文
22 个文件变更
+1669
-42
fqh@example.com
| •internal/ai/ai.go | +78 -29 |
| •internal/ai/ai_test.go | +70 -0 |
| •internal/gitx/gitx.go | +50 -0 |
| •internal/gitx/gitx_test.go | +55 -0 |
| •internal/server/githttp.go | +21 -0 |
| •internal/server/releases.go | +719 -0 |
| •internal/server/repo.go | +10 -0 |
| •internal/server/server.go | +15 -0 |
| •internal/store/releases.go | +230 -0 |
| •internal/store/store.go | +13 -6 |
| •webroot/static/release-upload.js | +148 -0 |
| •webroot/static/style.css | +38 -1 |
| •webroot/templates/layout.html | +1 -0 |
| •webroot/templates/repo_activity.html | +1 -1 |
| •webroot/templates/repo_blob.html | +1 -1 |
| •webroot/templates/repo_branches.html | +1 -1 |
| •webroot/templates/repo_commits.html | +1 -1 |
| •webroot/templates/repo_home.html | +28 -1 |
| •webroot/templates/repo_release.html | +100 -0 |
| •webroot/templates/repo_release_new.html | +43 -0 |
| •webroot/templates/repo_releases.html | +45 -0 |
| •webroot/templates/repo_settings.html | +1 -1 |
变更内容
diff --git a/internal/ai/ai.go b/internal/ai/ai.go
index d0f48db..efcb179 100644
--- a/internal/ai/ai.go
+++ b/internal/ai/ai.go
@@ -8,6 +8,7 @@ import (
"fmt"
"io"
"net/http"
+ "regexp"
"strings"
"time"
)
@@ -46,6 +47,9 @@ type CommitLine struct {
SHA string
Author string
Subject string
+ // Body 是提交正文(subject 之外的部分),常包含改动机与实现说明,
+ // 对归纳"为什么改"最有价值;可为空。
+ Body string
}
// SummaryInput 是一次推送的全部素材。
@@ -56,6 +60,9 @@ type SummaryInput struct {
DiffStat string
Additions int
Deletions int
+ // Patch 是 unified diff 正文(含 hunk 头与函数名)。为空表示本次
+ // 未提供(diff 过大或读取失败),模型只能依据提交信息归纳。
+ Patch string
}
type chatRequest struct {
@@ -83,12 +90,16 @@ type chatResponse struct {
func systemPrompt(lang string) string {
if lang == "en" {
return `You are the changelog assistant of "gitcat", a self-hosted Git service for a small studio.
-Given the commits and change stats of one git push, write a short visitor-friendly "What's New" summary.
-Rules: English; at most 3 bullet points, each starting with "- "; summarize the intent instead of copying commit messages; do not invent features; keep it under 80 words; no headings, no extra commentary.`
+Given the commits, change stats and (usually) the unified diff of one git push, write a short visitor-friendly "What's New" summary.
+Rules: English; base your summary on the actual code changes and commit bodies — commit titles are secondary; when they disagree, trust the code; explain intent and mention concrete files/functions when helpful; do not invent anything absent from the diff; use cautious wording for changes whose effect you cannot confirm; at most 3 bullet points, each starting with "- "; keep it under 80 words; no headings, no extra commentary.`
}
return `你是 "gitcat"(工作室自建 Git 服务)的更新日志助手。
-请根据一次代码推送的提交信息与变更统计,写一段面向访问者的「What's New」更新说明。
-要求:使用简体中文;最多 3 条要点,每条以「- 」开头并单独成行;归纳改动意图而不是照抄提交信息;不要编造未提及的内容;总字数控制在 120 字以内;不要输出标题或额外说明。`
+下面会给你一次代码推送的提交信息、变更统计,通常还有 unified diff 正文。请据此写一段面向访问者的「What's New」更新说明。
+要求:
+- 以 diff 正文与提交正文为主要依据,提交标题仅作辅助;两者矛盾时以代码实际改动为准。
+- 归纳改动意图与影响的功能模块,可引用具体文件名或函数名帮助读者理解。
+- 不要编造 diff 中不存在的内容;无法确认效果的改动用保守表述(如"调整了……")。
+- 使用简体中文;最多 3 条要点,每条以「- 」开头并单独成行;总字数控制在 150 字以内;不要输出标题或额外说明。`
}
// GenerateWhatsNew 调用模型生成更新说明。
@@ -96,31 +107,9 @@ func GenerateWhatsNew(ctx context.Context, cfg Config, in SummaryInput) (string,
if !cfg.Ready() {
return "", fmt.Errorf("AI 未启用或配置不完整")
}
- var sb strings.Builder
- fmt.Fprintf(&sb, "仓库:%s\n分支:%s\n提交数:%d\n", in.RepoName, in.Ref, len(in.Commits))
- if in.Additions > 0 || in.Deletions > 0 {
- fmt.Fprintf(&sb, "代码行变化:+%d / -%d\n", in.Additions, in.Deletions)
- }
- if in.DiffStat != "" {
- sb.WriteString("变更文件统计:\n")
- sb.WriteString(truncate(in.DiffStat, 3000))
- sb.WriteString("\n")
- }
- sb.WriteString("提交列表:\n")
- for i, c := range in.Commits {
- if i >= 40 {
- fmt.Fprintf(&sb, "…… 其余 %d 条提交已省略\n", len(in.Commits)-i)
- break
- }
- fmt.Fprintf(&sb, "- %s %s: %s\n", shortSHA(c.SHA), c.Author, c.Subject)
- }
-
body, err := json.Marshal(chatRequest{
- Model: cfg.Model,
- Messages: []chatMessage{
- {Role: "system", Content: systemPrompt(cfg.Language)},
- {Role: "user", Content: sb.String()},
- },
+ Model: cfg.Model,
+ Messages: buildMessages(cfg.Language, in),
Temperature: 0.3,
})
if err != nil {
@@ -173,9 +162,11 @@ func TestConnection(ctx context.Context, cfg Config) (string, error) {
RepoName: "gitcat-demo",
Ref: "main",
Commits: []CommitLine{
- {SHA: "0123456789abcdef", Author: "gitcat", Subject: "add hello world page"},
+ {SHA: "0123456789abcdef", Author: "gitcat", Subject: "add hello world page",
+ Body: "Visitors asked for a landing page; this adds a minimal one."},
},
DiffStat: " hello.txt | 1 +\n 1 file changed, 1 insertion(+)",
+ Patch: "diff --git a/hello.txt b/hello.txt\nindex 0000000..9daeafb 100644\n--- a/hello.txt\n+++ b/hello.txt\n@@ -0,0 +1 @@\n+hello world\n",
})
}
@@ -186,6 +177,43 @@ func shortSHA(s string) string {
return s
}
+// buildMessages 组装一次请求的 system + user 消息。
+// user 消息即素材:仓库信息、变更统计、提交列表(含正文)、diff 正文。
+func buildMessages(lang string, in SummaryInput) []chatMessage {
+ var sb strings.Builder
+ fmt.Fprintf(&sb, "仓库:%s\n分支:%s\n提交数:%d\n", in.RepoName, in.Ref, len(in.Commits))
+ if in.Additions > 0 || in.Deletions > 0 {
+ fmt.Fprintf(&sb, "代码行变化:+%d / -%d\n", in.Additions, in.Deletions)
+ }
+ if in.DiffStat != "" {
+ sb.WriteString("变更文件统计:\n")
+ sb.WriteString(truncate(in.DiffStat, 3000))
+ sb.WriteString("\n")
+ }
+ sb.WriteString("提交列表(含正文):\n")
+ for i, c := range in.Commits {
+ if i >= 40 {
+ fmt.Fprintf(&sb, "…… 其余 %d 条提交已省略\n", len(in.Commits)-i)
+ break
+ }
+ fmt.Fprintf(&sb, "- %s %s: %s\n", shortSHA(c.SHA), c.Author, c.Subject)
+ if c.Body != "" {
+ fmt.Fprintf(&sb, " 正文:%s\n", truncate(redactSecrets(c.Body), 600))
+ }
+ }
+ if in.Patch != "" {
+ sb.WriteString("变更内容(unified diff,可能被截断):\n")
+ sb.WriteString(truncate(redactSecrets(in.Patch), 200000))
+ sb.WriteString("\n")
+ } else {
+ sb.WriteString("变更内容:未提供(diff 过大或不可用),只能依据提交信息归纳,表述请保守。\n")
+ }
+ return []chatMessage{
+ {Role: "system", Content: systemPrompt(lang)},
+ {Role: "user", Content: sb.String()},
+ }
+}
+
// truncate 按字符(而非字节)截断,避免切断多字节字符。
func truncate(s string, max int) string {
r := []rune(s)
@@ -198,3 +226,24 @@ func truncate(s string, max int) string {
}
return cut + "\n…"
}
+
+// secretPatterns 是 diff/提交正文里常见的密钥形态。素材会被发送给
+// 第三方 AI 服务,送出前把疑似密钥遮挡,避免通过 diff 泄露凭据。
+var secretPatterns = []*regexp.Regexp{
+ regexp.MustCompile(`AKIA[0-9A-Z]{16}`), // AWS access key id
+ regexp.MustCompile(`(?i)(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}`), // GitHub token
+ regexp.MustCompile(`(?i)\bsk-[A-Za-z0-9_-]{20,}`), // OpenAI 风格 key
+ regexp.MustCompile(`(?i)\bxox[baprs]-[A-Za-z0-9-]{10,}`), // Slack token
+ regexp.MustCompile(`(?i)(?:password|passwd|secret|token|api[_-]?key)\s*[:=]\s*["']?[^\s"']{8,}`), // 赋值形态
+ regexp.MustCompile(`(?s)-----BEGIN [A-Z ]*PRIVATE KEY-----.*?-----END [A-Z ]*PRIVATE KEY-----`), // 私钥块
+}
+
+const redacted = "[REDACTED]"
+
+// redactSecrets 把疑似密钥的片段替换为 [REDACTED]。宁可误伤也不放过。
+func redactSecrets(s string) string {
+ for _, re := range secretPatterns {
+ s = re.ReplaceAllString(s, redacted)
+ }
+ return s
+}
diff --git a/internal/ai/ai_test.go b/internal/ai/ai_test.go
new file mode 100644
index 0000000..b41dc1a
--- /dev/null
+++ b/internal/ai/ai_test.go
@@ -0,0 +1,70 @@
+package ai
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestRedactSecrets(t *testing.T) {
+ cases := []struct {
+ name, in, wantAbsent string
+ }{
+ {"AWS key", "+aws_key = AKIAIOSFODNN7EXAMPLE", "AKIAIOSFODNN7EXAMPLE"},
+ {"GitHub token", "+token: ghp_0123456789abcdefghijklmnopqrstuv", "ghp_0123456789"},
+ {"OpenAI key", "sk-proj-0123456789abcdefghijklmn", "sk-proj-0123456789"},
+ {"Slack token", "xoxb-123456789012-abcdefghijkl", "xoxb-123456789012"},
+ {"赋值形态", "password = hunter2hunter2", "hunter2hunter2"},
+ {"私钥块", "-----BEGIN RSA PRIVATE KEY-----\nMIIabc\ndef\n-----END RSA PRIVATE KEY-----", "MIIabc"},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ out := redactSecrets(c.in)
+ if strings.Contains(out, c.wantAbsent) {
+ t.Errorf("脱敏后仍含敏感内容 %q,输出: %q", c.wantAbsent, out)
+ }
+ if !strings.Contains(out, redacted) {
+ t.Errorf("应替换为 %s,输出: %q", redacted, out)
+ }
+ })
+ }
+ // 普通代码不应被遮挡
+ if out := redactSecrets("token := r.Header.Get(\"Authorization\")"); strings.Contains(out, redacted) {
+ t.Errorf("普通代码被误遮挡: %q", out)
+ }
+}
+
+// TestUserPromptContainsPatchAndBody 验证素材组装把 diff 与提交正文带上,
+// 且缺 diff 时给出"只能保守归纳"的提示。
+func TestUserPromptContainsPatchAndBody(t *testing.T) {
+ in := SummaryInput{
+ RepoName: "demo", Ref: "main",
+ Commits: []CommitLine{
+ {SHA: "0123456789abcdef0123456789abcdef01234567", Author: "t", Subject: "fix login", Body: "根因是 session 未落库"},
+ },
+ DiffStat: " login.go | 2 +-\n 1 file changed",
+ Patch: "diff --git a/login.go b/login.go\n@@ -1,1 +1,1 @@ func Login()\n-x := 1\n+x = 1",
+ }
+ var user string
+ msgs := buildMessages("zh", in)
+ for _, m := range msgs {
+ if m.Role == "user" {
+ user = m.Content
+ }
+ }
+ for _, want := range []string{"根因是 session 未落库", "func Login()", "+x = 1", "login.go | 2"} {
+ if !strings.Contains(user, want) {
+ t.Errorf("素材缺少 %q", want)
+ }
+ }
+
+ in.Patch = ""
+ user = ""
+ for _, m := range buildMessages("zh", in) {
+ if m.Role == "user" {
+ user = m.Content
+ }
+ }
+ if !strings.Contains(user, "未提供") {
+ t.Errorf("diff 缺失时应提示保守归纳,实际: %q", user)
+ }
+}
diff --git a/internal/gitx/gitx.go b/internal/gitx/gitx.go
index c31a8ce..5a827f5 100644
--- a/internal/gitx/gitx.go
+++ b/internal/gitx/gitx.go
@@ -926,6 +926,56 @@ func DiffStat(repo, oldSHA, newSHA string) string {
return strings.TrimSpace(string(out))
}
+// DiffPatch 返回两次提交之间的 unified diff 正文(含 hunk 头与所在函数名),
+// 供 AI 阅读真实代码改动、减少仅凭提交标题产生的理解偏差。
+// max > 0 时输出超过 max 字节返回 ErrTooLarge,调用方应降级为仅提供统计。
+func DiffPatch(repo, oldSHA, newSHA string, max int) (string, error) {
+ if oldSHA == "" || oldSHA == strings.Repeat("0", 40) {
+ oldSHA = EmptyTreeSHA
+ }
+ if newSHA == "" || newSHA == strings.Repeat("0", 40) {
+ return "", nil
+ }
+ out, err := runLimit(context.Background(), repo, max,
+ "diff", "--no-color", "--find-renames", "--find-copies", oldSHA, newSHA)
+ if err != nil {
+ // 其他失败(对象缺失等)按无 diff 处理,不影响推送主流程。
+ if errors.Is(err, ErrTooLarge) {
+ return "", err
+ }
+ return "", nil
+ }
+ return strings.TrimSpace(string(out)), nil
+}
+
+// CommitBodies 返回 old..new 之间各提交的完整提交正文(subject 之外的部分),
+// key 为 40 位 SHA。提交正文里的动机说明对 AI 归纳改动意图最有价值。
+func CommitBodies(repo, oldSHA, newSHA string, limit int) map[string]string {
+ rng := newSHA
+ if oldSHA != "" && oldSHA != strings.Repeat("0", 40) {
+ rng = oldSHA + ".." + newSHA
+ }
+ out, err := run(repo, "log", "--no-color", "--format=%H%x1f%b%x1e", "-n", strconv.Itoa(limit), rng)
+ if err != nil {
+ return nil
+ }
+ bodies := make(map[string]string)
+ for _, entry := range strings.Split(string(out), "\x1e") {
+ entry = strings.TrimSpace(entry)
+ if entry == "" {
+ continue
+ }
+ parts := strings.SplitN(entry, "\x1f", 2)
+ if len(parts) != 2 {
+ continue
+ }
+ if body := strings.TrimSpace(parts[1]); body != "" {
+ bodies[parts[0]] = body
+ }
+ }
+ return bodies
+}
+
// SetDefaultBranch 修改裸仓库的 HEAD 指向。
func SetDefaultBranch(repo, branch string) error {
if !ValidRef(branch) {
diff --git a/internal/gitx/gitx_test.go b/internal/gitx/gitx_test.go
index 0f39d16..29415e9 100644
--- a/internal/gitx/gitx_test.go
+++ b/internal/gitx/gitx_test.go
@@ -151,3 +151,58 @@ func TestSetDefaultBranchRejectsBadRef(t *testing.T) {
}
var _ = context.Background
+
+// commitObject 用底层命令造一个提交,msg 可含多段(空行分隔)。
+func commitObject(t *testing.T, dir, tree, msg string) string {
+ t.Helper()
+ return runStdin(t, dir, "", "commit-tree", tree, "-m", msg)
+}
+
+// TestDiffPatchAndCommitBodies 验证 AI 素材读取:diff 正文含 hunk 头与新行,
+// 提交正文能按 SHA 取回;超过上限时返回 ErrTooLarge。
+func TestDiffPatchAndCommitBodies(t *testing.T) {
+ dir := t.TempDir()
+ if err := InitBare(dir, "main"); err != nil {
+ t.Fatalf("InitBare 失败: %v", err)
+ }
+
+ blob1 := runStdin(t, dir, "hello\n", "hash-object", "-w", "--stdin")
+ tree1 := runStdin(t, dir, "100644 blob "+blob1+"\tlogin.go\n", "mktree")
+ c1 := commitObject(t, dir, tree1, "init\n\n初始提交,无更多说明")
+
+ blob2 := runStdin(t, dir, "hello\nworld\n", "hash-object", "-w", "--stdin")
+ tree2 := runStdin(t, dir, "100644 blob "+blob2+"\tlogin.go\n", "mktree")
+ c2 := commitObject(t, dir, tree2, "add world\n\n根因是缺少输出,Closes #1")
+ _, _ = run(dir, "update-ref", "refs/heads/main", c2)
+
+ patch, err := DiffPatch(dir, c1, c2, 64<<10)
+ if err != nil {
+ t.Fatalf("DiffPatch 失败: %v", err)
+ }
+ for _, want := range []string{"diff --git a/login.go", "@@", "+world"} {
+ if !strings.Contains(patch, want) {
+ t.Errorf("diff 正文缺少 %q", want)
+ }
+ }
+
+ bodies := CommitBodies(dir, c1, c2, 10)
+ if bodies == nil {
+ t.Fatal("CommitBodies 返回 nil")
+ }
+ if b, ok := bodies[c2]; !ok || !strings.Contains(b, "Closes #1") {
+ t.Errorf("c2 正文取回失败: %q ok=%v", b, ok)
+ }
+ if b, ok := bodies[c1]; ok && b != "" {
+ t.Errorf("c1 无正文不应出现在结果中: %q", b)
+ }
+
+ // 超限场景:1MB 内容变更,限 1KB 读取
+ big := strings.Repeat("A", 1<<20)
+ blob3 := runStdin(t, dir, big, "hash-object", "-w", "--stdin")
+ tree3 := runStdin(t, dir, "100644 blob "+blob3+"\tbig.txt\n", "mktree")
+ c3 := commitObject(t, dir, tree3, "big")
+ _, _ = run(dir, "update-ref", "refs/heads/main", c3)
+ if _, err := DiffPatch(dir, c2, c3, 1024); !errors.Is(err, ErrTooLarge) {
+ t.Errorf("超过上限应返回 ErrTooLarge,实际 %v", err)
+ }
+}
diff --git a/internal/server/githttp.go b/internal/server/githttp.go
index 33fd01a..4d51ab1 100644
--- a/internal/server/githttp.go
+++ b/internal/server/githttp.go
@@ -28,6 +28,11 @@ const gitTransferTimeout = 30 * time.Minute
// 恶意(或失控的)客户端可以用 gzip 炸弹把任意大的数据灌进 git 的 stdin。
const maxGitBodySize = 512 << 20
+// aiPatchLimit 是送给 AI 的 diff 正文体积上限(字节)。
+// 512KB 约对应十几万 token,正常功能推送远用不满;
+// 超限(巨型重构、依赖 vendoring 等)降级为只给变更统计。
+const aiPatchLimit = 512 << 10
+
// handleGitAction 处理 Git Smart HTTP 协议请求。
func (s *Server) handleGitAction(w http.ResponseWriter, r *http.Request, name, action string) {
if !s.st.Installed() {
@@ -333,6 +338,21 @@ func (s *Server) generateWhatsNew(pushID int64, repo *store.Repo, primary refCha
for _, c := range details {
lines = append(lines, ai.CommitLine{SHA: c.SHA, Author: c.Author, Subject: c.Subject})
}
+ // 提交正文:改动动机常写在这里,给 AI 归纳"为什么改"提供依据。
+ dir := s.repoPath(repo.Name)
+ bodies := gitx.CommitBodies(dir, primary.Old, primary.New, len(details))
+ for i := range lines {
+ if b, ok := bodies[lines[i].SHA]; ok {
+ lines[i].Body = b
+ }
+ }
+ // diff 正文:让 AI 读真实代码改动而非只猜标题。超过上限时降级为
+ // 仅统计,避免一次巨型推送拖垮生成请求。
+ patch, err := gitx.DiffPatch(dir, primary.Old, primary.New, aiPatchLimit)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "diff 正文超过 AI 素材上限,本次仅提供统计: %v\n", err)
+ patch = ""
+ }
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
out, err := ai.GenerateWhatsNew(ctx, cfg, ai.SummaryInput{
@@ -342,6 +362,7 @@ func (s *Server) generateWhatsNew(pushID int64, repo *store.Repo, primary refCha
DiffStat: diffStat,
Additions: additions,
Deletions: deletions,
+ Patch: patch,
})
if err != nil {
fmt.Fprintf(os.Stderr, "AI 生成更新说明失败: %v\n", err)
diff --git a/internal/server/releases.go b/internal/server/releases.go
new file mode 100644
index 0000000..3a246c6
--- /dev/null
+++ b/internal/server/releases.go
@@ -0,0 +1,719 @@
+// 发行版(Releases)页面与附件上传下载。
+//
+// 大文件上传采用分片协议,核心约束是"服务端任何时刻都不把整个文件读进
+// 内存":每个分片请求体直接流式写盘,complete 阶段也是分片拼接、边写边
+// 算 sha256。上传状态(meta.json)落盘而非内存,进程重启后分片仍在,
+// 浏览器从断点继续即可。下载走 http.ServeContent,天然支持 Range 续传。
+package server
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "time"
+
+ "gitcat/internal/gitx"
+ "gitcat/internal/store"
+)
+
+// 上传相关的固定限制。
+const (
+ // assetChunkSize 是单个分片的字节数。
+ assetChunkSize = 8 << 20 // 8 MiB
+ // maxAssetSize 是单个附件的体积上限。
+ maxAssetSize = 4 << 30 // 4 GiB
+ // maxAssetsPerRelease 是每个发行版的附件数量上限。
+ maxAssetsPerRelease = 20
+ // maxReleaseNotes 是发行版说明的长度上限(Markdown)。
+ maxReleaseNotes = 50 << 10
+ // maxReleaseTitle 是标题长度上限。
+ maxReleaseTitle = 200
+ // staleUploadAge 是废弃上传会话的回收时限。
+ staleUploadAge = 24 * time.Hour
+)
+
+// ---------------------------------------------------------------- 路径与校验
+
+// releaseDir 返回某发行版附件在磁盘上的目录。
+func (s *Server) releaseDir(repoID, releaseID int64) string {
+ return filepath.Join(s.cfg.DataDir, "releases",
+ strconv.FormatInt(repoID, 10), strconv.FormatInt(releaseID, 10))
+}
+
+// uploadDir 返回分片上传的会话根目录。
+func (s *Server) uploadDir() string {
+ return filepath.Join(s.cfg.DataDir, "tmp", "uploads")
+}
+
+// uploadSessionDir 返回单个上传会话的目录(uid 已校验为 32 位 hex)。
+func (s *Server) uploadSessionDir(uid string) string {
+ return filepath.Join(s.uploadDir(), uid)
+}
+
+// validUploadID 校验上传会话 ID:只允许 32 位小写 hex,
+// 从根上杜绝它参与路径拼接时的目录穿越。
+func validUploadID(uid string) bool {
+ if len(uid) != 32 {
+ return false
+ }
+ for _, c := range uid {
+ if (c < '0' || c > '9') && (c < 'a' || c > 'f') {
+ return false
+ }
+ }
+ return true
+}
+
+// sanitizeAssetName 清洗客户端提交的文件名:取 base、去控制字符、限长。
+func sanitizeAssetName(name string) (string, error) {
+ name = strings.ReplaceAll(name, "\\", "/")
+ name = filepath.Base(strings.TrimSpace(name))
+ var b strings.Builder
+ for _, r := range name {
+ if r < 0x20 || r == 0x7f {
+ continue
+ }
+ b.WriteRune(r)
+ }
+ name = strings.Trim(b.String(), ". ")
+ if name == "" {
+ return "", fmt.Errorf("文件名无效")
+ }
+ if len([]rune(name)) > 200 {
+ return "", fmt.Errorf("文件名过长(最多 200 字符)")
+ }
+ return name, nil
+}
+
+// uploadMeta 是落盘的上传会话元数据。
+type uploadMeta struct {
+ Name string `json:"name"`
+ Size int64 `json:"size"`
+ RepoID int64 `json:"repo_id"`
+ ReleaseID int64 `json:"release_id"`
+ CreatedAt time.Time `json:"created_at"`
+}
+
+func writeMeta(path string, m *uploadMeta) error {
+ raw, err := json.Marshal(m)
+ if err != nil {
+ return err
+ }
+ return os.WriteFile(path, raw, 0o644)
+}
+
+func readMeta(path string) (*uploadMeta, error) {
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ return nil, err
+ }
+ var m uploadMeta
+ if err := json.Unmarshal(raw, &m); err != nil {
+ return nil, err
+ }
+ return &m, nil
+}
+
+// ---------------------------------------------------------------- 通用前置
+
+// guardReleasePage 校验"登录 + 仓库管理权 + CSRF + 发行版归属",
+// 失败时自行写出 HTML 错误并返回 ok=false。
+func (s *Server) guardReleasePage(w http.ResponseWriter, r *http.Request) (*store.Repo, *store.Release, bool) {
+ repo, _, ok := s.loadRepo(w, r)
+ if !ok {
+ return nil, nil, false
+ }
+ u := userFrom(r.Context())
+ if !canManageRepo(u, repo) {
+ s.renderError(w, r, http.StatusForbidden, "只有项目创建者或管理员可以管理发行版")
+ return nil, nil, false
+ }
+ if !s.checkCSRF(r) {
+ s.renderError(w, r, http.StatusForbidden, "表单已过期,请重试")
+ return nil, nil, false
+ }
+ rel, ok := s.releaseFromPath(w, r, repo)
+ if !ok {
+ return nil, nil, false
+ }
+ return repo, rel, true
+}
+
+// guardReleaseAPI 与 guardReleasePage 相同,但失败时返回 JSON——
+// 分片上传是 fetch 发起的,重定向到 HTML 页面对脚本没有意义。
+func (s *Server) guardReleaseAPI(w http.ResponseWriter, r *http.Request) (*store.Repo, *store.Release, bool) {
+ repo, _, ok := s.loadRepo(w, r)
+ if !ok {
+ failJSON(w, http.StatusNotFound, "项目不存在")
+ return nil, nil, false
+ }
+ u := userFrom(r.Context())
+ if u == nil {
+ failJSON(w, http.StatusUnauthorized, "登录已过期,请刷新页面重新登录")
+ return nil, nil, false
+ }
+ if !canManageRepo(u, repo) {
+ failJSON(w, http.StatusForbidden, "没有管理发行版的权限")
+ return nil, nil, false
+ }
+ if !s.checkCSRF(r) {
+ failJSON(w, http.StatusForbidden, "CSRF 校验失败,请刷新页面重试")
+ return nil, nil, false
+ }
+ rel, ok := s.releaseFromPath(w, r, repo)
+ if !ok {
+ failJSON(w, http.StatusNotFound, "发行版不存在")
+ return nil, nil, false
+ }
+ return repo, rel, true
+}
+
+// releaseFromPath 解析 URL 中的发行版 ID 并校验归属关系。
+func (s *Server) releaseFromPath(w http.ResponseWriter, r *http.Request, repo *store.Repo) (*store.Release, bool) {
+ rid, err := strconv.ParseInt(r.PathValue("rid"), 10, 64)
+ if err != nil || rid <= 0 {
+ s.renderError(w, r, http.StatusNotFound, "发行版不存在")
+ return nil, false
+ }
+ rel, err := s.st.ReleaseByID(rid)
+ if err != nil {
+ s.renderError(w, r, http.StatusNotFound, "发行版不存在")
+ return nil, false
+ }
+ if rel.RepoID != repo.ID {
+ s.renderError(w, r, http.StatusNotFound, "发行版不存在")
+ return nil, false
+ }
+ return rel, true
+}
+
+// ---------------------------------------------------------------- JSON 工具
+
+func writeJSON(w http.ResponseWriter, code int, v any) {
+ w.Header().Set("Content-Type", "application/json; charset=utf-8")
+ w.WriteHeader(code)
+ _ = json.NewEncoder(w).Encode(v)
+}
+
+func failJSON(w http.ResponseWriter, code int, msg string) {
+ writeJSON(w, code, map[string]string{"error": msg})
+}
+
+// ---------------------------------------------------------------- 页面
+
+func (s *Server) handleReleasesList(w http.ResponseWriter, r *http.Request) {
+ repo, dir, ok := s.loadRepo(w, r)
+ if !ok {
+ return
+ }
+ ref := s.pickRef(dir, repo, "")
+ releases, err := s.st.ReleasesByRepo(repo.ID, 100)
+ if err != nil {
+ s.renderError(w, r, http.StatusInternalServerError, "读取发行版失败:"+err.Error())
+ return
+ }
+ p := s.page(r, repo.Name+" · 发行版")
+ p.Active = "repo"
+ p.Data = s.repoCommon(r, repo, dir, ref)
+ p.Data["Tab"] = "releases"
+ p.Data["Releases"] = releases
+ s.render(w, r, "repo_releases", p)
+}
+
+func (s *Server) handleReleaseNewPage(w http.ResponseWriter, r *http.Request) {
+ repo, dir, ok := s.loadRepo(w, r)
+ if !ok {
+ return
+ }
+ u := userFrom(r.Context())
+ if !canManageRepo(u, repo) {
+ s.renderError(w, r, http.StatusForbidden, "只有项目创建者或管理员可以发布发行版")
+ return
+ }
+ ref := s.pickRef(dir, repo, "")
+ p := s.page(r, repo.Name+" · 新建发行版")
+ p.Active = "repo"
+ p.Data = s.repoCommon(r, repo, dir, ref)
+ p.Data["Tab"] = "releases"
+ s.render(w, r, "repo_release_new", p)
+}
+
+func (s *Server) handleReleaseCreate(w http.ResponseWriter, r *http.Request) {
+ repo, _, ok := s.loadRepo(w, r)
+ if !ok {
+ return
+ }
+ u := userFrom(r.Context())
+ if !canManageRepo(u, repo) {
+ s.renderError(w, r, http.StatusForbidden, "只有项目创建者或管理员可以发布发行版")
+ return
+ }
+ if !s.checkCSRF(r) {
+ s.renderError(w, r, http.StatusForbidden, "表单已过期,请重试")
+ return
+ }
+ tag := strings.TrimSpace(r.FormValue("tag_name"))
+ title := strings.TrimSpace(r.FormValue("title"))
+ notes := r.FormValue("notes")
+ if tag != "" && !gitx.ValidRef(tag) {
+ s.renderError(w, r, http.StatusBadRequest, "非法的标签名")
+ return
+ }
+ if title == "" {
+ title = tag
+ }
+ if len([]rune(title)) > maxReleaseTitle {
+ s.renderError(w, r, http.StatusBadRequest, "标题过长(最多 200 字符)")
+ return
+ }
+ if len(notes) > maxReleaseNotes {
+ s.renderError(w, r, http.StatusBadRequest, "发行说明过长(最多 50KB)")
+ return
+ }
+ rel, err := s.st.CreateRelease(repo.ID, &u.ID, u.Username, u.Display(), tag, title, notes)
+ if err != nil {
+ s.renderError(w, r, http.StatusInternalServerError, "创建发行版失败:"+err.Error())
+ return
+ }
+ _ = s.st.TouchRepo(repo.ID)
+ setFlash(w, "发行版已创建,可以上传附件了")
+ http.Redirect(w, r, "/"+repo.Name+"/releases/"+strconv.FormatInt(rel.ID, 10), http.StatusFound)
+}
+
+func (s *Server) handleReleaseDetail(w http.ResponseWriter, r *http.Request) {
+ repo, dir, ok := s.loadRepo(w, r)
+ if !ok {
+ return
+ }
+ rid, err := strconv.ParseInt(r.PathValue("rid"), 10, 64)
+ if err != nil || rid <= 0 {
+ s.renderError(w, r, http.StatusNotFound, "发行版不存在")
+ return
+ }
+ rel, err := s.st.ReleaseByID(rid)
+ if err != nil || rel.RepoID != repo.ID {
+ s.renderError(w, r, http.StatusNotFound, "发行版不存在")
+ return
+ }
+ assets, _ := s.st.AssetsByRelease(rel.ID)
+ ref := s.pickRef(dir, repo, "")
+ p := s.page(r, repo.Name+" · "+rel.Title)
+ p.Active = "repo"
+ p.Data = s.repoCommon(r, repo, dir, ref)
+ p.Data["Tab"] = "releases"
+ p.Data["Release"] = rel
+ p.Data["Assets"] = assets
+ p.Data["Base"] = "/" + repo.Name + "/releases/" + strconv.FormatInt(rel.ID, 10)
+ p.Data["OriginURL"] = originURL(r)
+ s.render(w, r, "repo_release", p)
+}
+
+// originURL 返回 scheme://host 形式的站点根地址(拼接附件直链用)。
+func originURL(r *http.Request) string {
+ scheme := "http"
+ if r.TLS != nil {
+ scheme = "https"
+ }
+ if proto := r.Header.Get("X-Forwarded-Proto"); proto == "https" || proto == "http" {
+ scheme = proto
+ }
+ return scheme + "://" + r.Host
+}
+
+func (s *Server) handleReleaseEdit(w http.ResponseWriter, r *http.Request) {
+ repo, rel, ok := s.guardReleasePage(w, r)
+ if !ok {
+ return
+ }
+ tag := strings.TrimSpace(r.FormValue("tag_name"))
+ title := strings.TrimSpace(r.FormValue("title"))
+ notes := r.FormValue("notes")
+ if tag != "" && !gitx.ValidRef(tag) {
+ s.renderError(w, r, http.StatusBadRequest, "非法的标签名")
+ return
+ }
+ if title == "" {
+ title = tag
+ }
+ if len([]rune(title)) > maxReleaseTitle {
+ s.renderError(w, r, http.StatusBadRequest, "标题过长(最多 200 字符)")
+ return
+ }
+ if len(notes) > maxReleaseNotes {
+ s.renderError(w, r, http.StatusBadRequest, "发行说明过长(最多 50KB)")
+ return
+ }
+ if err := s.st.UpdateRelease(rel.ID, tag, title, notes); err != nil {
+ s.renderError(w, r, http.StatusInternalServerError, "保存失败:"+err.Error())
+ return
+ }
+ setFlash(w, "发行版已更新")
+ http.Redirect(w, r, "/"+repo.Name+"/releases/"+strconv.FormatInt(rel.ID, 10), http.StatusFound)
+}
+
+func (s *Server) handleReleaseDelete(w http.ResponseWriter, r *http.Request) {
+ repo, rel, ok := s.guardReleasePage(w, r)
+ if !ok {
+ return
+ }
+ if err := s.st.DeleteRelease(rel.ID); err != nil {
+ s.renderError(w, r, http.StatusInternalServerError, "删除失败:"+err.Error())
+ return
+ }
+ _ = os.RemoveAll(s.releaseDir(repo.ID, rel.ID))
+ setFlash(w, "发行版已删除")
+ http.Redirect(w, r, "/"+repo.Name+"/releases", http.StatusFound)
+}
+
+func (s *Server) handleReleaseAssetDelete(w http.ResponseWriter, r *http.Request) {
+ repo, rel, ok := s.guardReleasePage(w, r)
+ if !ok {
+ return
+ }
+ aid, err := strconv.ParseInt(r.PathValue("aid"), 10, 64)
+ if err != nil || aid <= 0 {
+ s.renderError(w, r, http.StatusNotFound, "附件不存在")
+ return
+ }
+ asset, gotRepo, err := s.st.AssetByID(aid)
+ if err != nil || gotRepo != repo.ID || asset.ReleaseID != rel.ID {
+ s.renderError(w, r, http.StatusNotFound, "附件不存在")
+ return
+ }
+ if err := s.st.DeleteAsset(aid); err != nil {
+ s.renderError(w, r, http.StatusInternalServerError, "删除失败:"+err.Error())
+ return
+ }
+ _ = os.Remove(filepath.Join(s.releaseDir(repo.ID, rel.ID), strconv.FormatInt(aid, 10)))
+ setFlash(w, "附件已删除")
+ http.Redirect(w, r, "/"+repo.Name+"/releases/"+strconv.FormatInt(rel.ID, 10), http.StatusFound)
+}
+
+// ---------------------------------------------------------------- 下载
+
+// handleReleaseDownload 公开下载附件。附件内容与仓库 raw 一样属于不可信
+// 内容,沿用同一套响应头策略:nosniff + CSP sandbox,活动内容强制
+// attachment。ServeContent 自带 Range 支持,下载器可断点续传。
+func (s *Server) handleReleaseDownload(w http.ResponseWriter, r *http.Request) {
+ repo, _, ok := s.loadRepo(w, r)
+ if !ok {
+ return
+ }
+ rid, err := strconv.ParseInt(r.PathValue("rid"), 10, 64)
+ if err != nil || rid <= 0 {
+ http.NotFound(w, r)
+ return
+ }
+ aid, err := strconv.ParseInt(r.PathValue("aid"), 10, 64)
+ if err != nil || aid <= 0 {
+ http.NotFound(w, r)
+ return
+ }
+ asset, gotRepo, err := s.st.AssetByID(aid)
+ if err != nil || gotRepo != repo.ID || asset.ReleaseID != rid {
+ http.NotFound(w, r)
+ return
+ }
+ full := filepath.Join(s.releaseDir(repo.ID, rid), strconv.FormatInt(aid, 10))
+ f, err := os.Open(full)
+ if err != nil {
+ http.NotFound(w, r)
+ return
+ }
+ defer f.Close()
+ st, err := f.Stat()
+ if err != nil || st.IsDir() {
+ http.NotFound(w, r)
+ return
+ }
+ // 完整请求才计数:Range 续传产生的部分请求不算一次下载。
+ if r.Header.Get("Range") == "" {
+ s.st.IncAssetDownload(aid)
+ }
+ ext := strings.ToLower(filepath.Ext(asset.Filename))
+ disposition := "attachment"
+ rawSecurityHeaders(w)
+ if inlineSafeExt[ext] {
+ disposition = "inline"
+ }
+ w.Header().Set("Content-Disposition",
+ disposition+`; filename*=UTF-8''`+url.PathEscape(asset.Filename))
+ http.ServeContent(w, r, asset.Filename, st.ModTime(), f)
+}
+
+// ---------------------------------------------------------------- 分片上传
+
+// handleReleaseUploadInit 创建上传会话。
+//
+// 请求体 JSON:{"name": "...", "size": 12345}
+// 响应 JSON:{"upload_id": "...", "chunk_size": 8388608, "chunk_count": n}
+func (s *Server) handleReleaseUploadInit(w http.ResponseWriter, r *http.Request) {
+ repo, rel, ok := s.guardReleaseAPI(w, r)
+ if !ok {
+ return
+ }
+ var req struct {
+ Name string `json:"name"`
+ Size int64 `json:"size"`
+ }
+ dec := json.NewDecoder(io.LimitReader(r.Body, 64<<10))
+ if err := dec.Decode(&req); err != nil {
+ failJSON(w, http.StatusBadRequest, "请求格式错误")
+ return
+ }
+ name, err := sanitizeAssetName(req.Name)
+ if err != nil {
+ failJSON(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ if req.Size <= 0 {
+ failJSON(w, http.StatusBadRequest, "文件为空")
+ return
+ }
+ if req.Size > maxAssetSize {
+ failJSON(w, http.StatusBadRequest, "文件超过大小上限(单个附件最大 "+humanSize(maxAssetSize)+")")
+ return
+ }
+ assets, _ := s.st.AssetsByRelease(rel.ID)
+ if len(assets) >= maxAssetsPerRelease {
+ failJSON(w, http.StatusBadRequest, "每个发行版最多 "+strconv.Itoa(maxAssetsPerRelease)+" 个附件")
+ return
+ }
+ for _, a := range assets {
+ if strings.EqualFold(a.Filename, name) {
+ failJSON(w, http.StatusConflict, "该发行版下已存在同名附件 "+name)
+ return
+ }
+ }
+
+ // 顺手回收超过 24 小时没人认领的半截上传。
+ s.cleanupStaleUploads()
+
+ uid := randomToken(16)
+ dir := s.uploadSessionDir(uid)
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ failJSON(w, http.StatusInternalServerError, "创建上传会话失败")
+ return
+ }
+ if err := writeMeta(filepath.Join(dir, "meta.json"), &uploadMeta{
+ Name: name, Size: req.Size, RepoID: repo.ID, ReleaseID: rel.ID, CreatedAt: time.Now(),
+ }); err != nil {
+ _ = os.RemoveAll(dir)
+ failJSON(w, http.StatusInternalServerError, "创建上传会话失败")
+ return
+ }
+ chunks := (req.Size + assetChunkSize - 1) / assetChunkSize
+ writeJSON(w, http.StatusOK, map[string]any{
+ "upload_id": uid,
+ "chunk_size": assetChunkSize,
+ "chunk_count": chunks,
+ })
+}
+
+// cleanupStaleUploads 删除长时间无进展的上传会话目录(尽力而为)。
+func (s *Server) cleanupStaleUploads() {
+ entries, err := os.ReadDir(s.uploadDir())
+ if err != nil {
+ return
+ }
+ cutoff := time.Now().Add(-staleUploadAge)
+ for _, e := range entries {
+ if !e.IsDir() || !validUploadID(e.Name()) {
+ continue
+ }
+ info, err := e.Info()
+ if err != nil || info.ModTime().After(cutoff) {
+ continue
+ }
+ _ = os.RemoveAll(filepath.Join(s.uploadDir(), e.Name()))
+ }
+}
+
+// handleReleaseUploadChunk 接收一个分片:URL 携带 index 与 csrf,
+// 请求体就是该分片的原始字节,直接流式写盘。
+func (s *Server) handleReleaseUploadChunk(w http.ResponseWriter, r *http.Request) {
+ _, rel, ok := s.guardReleaseAPI(w, r)
+ if !ok {
+ return
+ }
+ uid := r.PathValue("uid")
+ if !validUploadID(uid) {
+ failJSON(w, http.StatusBadRequest, "非法的上传会话")
+ return
+ }
+ meta, err := readMeta(filepath.Join(s.uploadSessionDir(uid), "meta.json"))
+ if err != nil || meta.ReleaseID != rel.ID {
+ failJSON(w, http.StatusNotFound, "上传会话不存在或已失效,请重新上传")
+ return
+ }
+ index, err := strconv.ParseInt(r.URL.Query().Get("index"), 10, 64)
+ if err != nil || index < 0 {
+ failJSON(w, http.StatusBadRequest, "非法的分片序号")
+ return
+ }
+ chunks := (meta.Size + assetChunkSize - 1) / assetChunkSize
+ if index >= chunks {
+ failJSON(w, http.StatusBadRequest, "分片序号超出范围")
+ return
+ }
+ expected := int64(assetChunkSize)
+ if index == chunks-1 {
+ expected = meta.Size - index*assetChunkSize
+ }
+ if r.ContentLength >= 0 && r.ContentLength != expected {
+ failJSON(w, http.StatusBadRequest,
+ fmt.Sprintf("分片大小不符:期望 %d 字节,实际 %d 字节", expected, r.ContentLength))
+ return
+ }
+ r.Body = http.MaxBytesReader(w, r.Body, expected+1)
+
+ part := filepath.Join(s.uploadSessionDir(uid), fmt.Sprintf("part-%07d", index))
+ f, err := os.OpenFile(part, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644)
+ if err != nil {
+ failJSON(w, http.StatusInternalServerError, "写入分片失败")
+ return
+ }
+ n, err := io.Copy(f, r.Body)
+ closeErr := f.Close()
+ if err != nil {
+ _ = os.Remove(part)
+ failJSON(w, http.StatusBadRequest, "分片传输中断,请重试")
+ return
+ }
+ if n != expected || closeErr != nil {
+ _ = os.Remove(part)
+ failJSON(w, http.StatusBadRequest, "分片大小不符,请重试")
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"ok": true, "index": index})
+}
+
+// handleReleaseUploadComplete 校验分片完整性,流式拼接出最终文件
+// (边拼边算 sha256),登记附件并清理会话目录。
+func (s *Server) handleReleaseUploadComplete(w http.ResponseWriter, r *http.Request) {
+ repo, rel, ok := s.guardReleaseAPI(w, r)
+ if !ok {
+ return
+ }
+ uid := r.PathValue("uid")
+ if !validUploadID(uid) {
+ failJSON(w, http.StatusBadRequest, "非法的上传会话")
+ return
+ }
+ sdir := s.uploadSessionDir(uid)
+ meta, err := readMeta(filepath.Join(sdir, "meta.json"))
+ if err != nil || meta.ReleaseID != rel.ID || meta.RepoID != repo.ID {
+ failJSON(w, http.StatusNotFound, "上传会话不存在或已失效,请重新上传")
+ return
+ }
+ chunks := (meta.Size + assetChunkSize - 1) / assetChunkSize
+ parts := make([]string, 0, chunks)
+ var expectedTotal int64
+ for i := int64(0); i < chunks; i++ {
+ part := filepath.Join(sdir, fmt.Sprintf("part-%07d", i))
+ want := int64(assetChunkSize)
+ if i == chunks-1 {
+ want = meta.Size - i*assetChunkSize
+ }
+ st, err := os.Stat(part)
+ if err != nil || st.Size() != want {
+ failJSON(w, http.StatusBadRequest,
+ fmt.Sprintf("第 %d 个分片缺失或不完整,请重试上传", i+1))
+ return
+ }
+ parts = append(parts, part)
+ expectedTotal += want
+ }
+
+ adDir := s.releaseDir(repo.ID, rel.ID)
+ if err := os.MkdirAll(adDir, 0o755); err != nil {
+ failJSON(w, http.StatusInternalServerError, "创建附件目录失败")
+ return
+ }
+ tmp := filepath.Join(adDir, "final.tmp")
+ if err := concatParts(parts, tmp, meta.Size); err != nil {
+ _ = os.Remove(tmp)
+ failJSON(w, http.StatusInternalServerError, "合并分片失败:"+err.Error())
+ return
+ }
+ sum, err := sha256File(tmp)
+ if err != nil {
+ _ = os.Remove(tmp)
+ failJSON(w, http.StatusInternalServerError, "计算校验值失败")
+ return
+ }
+ asset, err := s.st.CreateAsset(rel.ID, meta.Name, meta.Size, sum)
+ if err != nil {
+ _ = os.Remove(tmp)
+ failJSON(w, http.StatusConflict, err.Error())
+ return
+ }
+ final := filepath.Join(adDir, strconv.FormatInt(asset.ID, 10))
+ if err := os.Rename(tmp, final); err != nil {
+ _ = s.st.DeleteAsset(asset.ID)
+ _ = os.Remove(tmp)
+ failJSON(w, http.StatusInternalServerError, "保存附件失败")
+ return
+ }
+ _ = os.RemoveAll(sdir)
+ writeJSON(w, http.StatusOK, map[string]any{
+ "asset_id": asset.ID,
+ "size": asset.Size,
+ "sha256": asset.SHA256,
+ })
+}
+
+// concatParts 把分片按序拼接进 dst,同时核对总体积。
+func concatParts(parts []string, dst string, wantTotal int64) error {
+ out, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644)
+ if err != nil {
+ return err
+ }
+ var total int64
+ for _, p := range parts {
+ in, err := os.Open(p)
+ if err != nil {
+ _ = out.Close()
+ return err
+ }
+ n, err := io.Copy(out, in)
+ _ = in.Close()
+ if err != nil {
+ _ = out.Close()
+ return err
+ }
+ total += n
+ }
+ if err := out.Sync(); err != nil {
+ _ = out.Close()
+ return err
+ }
+ if err := out.Close(); err != nil {
+ return err
+ }
+ if total != wantTotal {
+ return fmt.Errorf("合并后体积 %d 字节,与声明值 %d 不符", total, wantTotal)
+ }
+ return nil
+}
+
+func sha256File(path string) (string, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return "", err
+ }
+ defer f.Close()
+ h := sha256.New()
+ if _, err := io.Copy(h, f); err != nil {
+ return "", err
+ }
+ return hex.EncodeToString(h.Sum(nil)), nil
+}
diff --git a/internal/server/repo.go b/internal/server/repo.go
index 8938126..3ca58fc 100644
--- a/internal/server/repo.go
+++ b/internal/server/repo.go
@@ -9,6 +9,7 @@ import (
"net/url"
"os"
"path"
+ "path/filepath"
"strconv"
"strings"
@@ -142,6 +143,13 @@ func (s *Server) repoCommon(r *http.Request, repo *store.Repo, dir string, ref s
data["RecentPushes"] = pushes
data["LatestPush"], _ = s.st.LatestPush(repo.ID)
+ // 发行版数量:仓库 Tab 角标。读取失败按 0 展示,不阻断页面。
+ data["ReleaseCount"] = s.st.ReleaseCount(repo.ID)
+ // 最新发行版:主页侧栏卡片。取不到(无发行版)时模板按空渲染。
+ if rels, err := s.st.ReleasesByRepo(repo.ID, 1); err == nil && len(rels) > 0 {
+ data["LatestRelease"] = rels[0]
+ }
+
data["IsEmpty"] = !gitx.HasCommits(dir)
// 统计信息在这里统一填充:repo_home 模板的“关于”卡片在空仓库与目录页
@@ -704,6 +712,8 @@ func (s *Server) handleRepoDelete(w http.ResponseWriter, r *http.Request) {
return
}
_ = removeRepoDir(s.repoPath(repo.Name))
+ // 发行版附件按 repoID 存放,随仓库一并清理。
+ _ = os.RemoveAll(filepath.Join(s.cfg.DataDir, "releases", strconv.FormatInt(repo.ID, 10)))
setFlash(w, fmt.Sprintf("项目 %s 已删除", repo.Name))
http.Redirect(w, r, "/", http.StatusFound)
}
diff --git a/internal/server/server.go b/internal/server/server.go
index af71ff0..87d22c8 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -182,6 +182,7 @@ func (s *Server) buildTemplates() error {
pages := []string{
"error", "install", "login", "home", "new_project",
"repo_home", "repo_commits", "repo_commit", "repo_blob", "repo_branches", "repo_activity", "repo_settings",
+ "repo_releases", "repo_release", "repo_release_new",
"profile",
"admin_dashboard", "admin_users", "admin_user", "admin_repos", "admin_repo", "admin_ai", "admin_settings", "admin_activity", "admin_upgrade",
}
@@ -278,6 +279,20 @@ func (s *Server) routes() {
m.HandleFunc("POST /{repo}/settings", s.handleRepoSettingsSave)
m.HandleFunc("POST /{repo}/delete", s.handleRepoDelete)
+ // 发行版
+ m.HandleFunc("GET /{repo}/releases", s.handleReleasesList)
+ m.HandleFunc("GET /{repo}/releases/new", s.handleReleaseNewPage)
+ m.HandleFunc("POST /{repo}/releases/new", s.handleReleaseCreate)
+ m.HandleFunc("GET /{repo}/releases/{rid}", s.handleReleaseDetail)
+ m.HandleFunc("POST /{repo}/releases/{rid}/edit", s.handleReleaseEdit)
+ m.HandleFunc("POST /{repo}/releases/{rid}/delete", s.handleReleaseDelete)
+ m.HandleFunc("POST /{repo}/releases/{rid}/assets/{aid}/delete", s.handleReleaseAssetDelete)
+ m.HandleFunc("GET /{repo}/releases/{rid}/files/{aid}/{name...}", s.handleReleaseDownload)
+ // 分片上传协议:init 建会话 → PUT 逐片传(query 携带 index/csrf)→ complete 合并
+ m.HandleFunc("POST /{repo}/releases/{rid}/upload/init", s.handleReleaseUploadInit)
+ m.HandleFunc("PUT /{repo}/releases/{rid}/upload/{uid}", s.handleReleaseUploadChunk)
+ m.HandleFunc("POST /{repo}/releases/{rid}/upload/{uid}/complete", s.handleReleaseUploadComplete)
+
// 管理后台
m.HandleFunc("GET /admin", s.handleAdminDashboard)
m.HandleFunc("GET /admin/users", s.handleAdminUsers)
diff --git a/internal/store/releases.go b/internal/store/releases.go
new file mode 100644
index 0000000..9867d98
--- /dev/null
+++ b/internal/store/releases.go
@@ -0,0 +1,230 @@
+// 发行版与附件:类似 GitHub Releases 的项目发布页。
+//
+// 附件二进制只落磁盘(<data>/releases/<repoID>/<releaseID>/<assetID>),
+// 数据库只存元数据(文件名、体积、sha256、下载次数),
+// 避免 SQLite 里塞大 blob。
+package store
+
+import (
+ "database/sql"
+ "errors"
+ "time"
+)
+
+// releasesSchema 是发行版功能引入的表与索引,随 migration v2 执行。
+// 全部 IF NOT EXISTS,保证重放安全。
+var releasesSchema = []string{
+ `CREATE TABLE IF NOT EXISTS releases (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ repo_id INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE,
+ tag_name TEXT NOT NULL DEFAULT '',
+ title TEXT NOT NULL DEFAULT '',
+ notes TEXT NOT NULL DEFAULT '',
+ user_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
+ author_username TEXT NOT NULL DEFAULT '',
+ author_display TEXT NOT NULL DEFAULT '',
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL
+ )`,
+ `CREATE TABLE IF NOT EXISTS release_assets (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ release_id INTEGER NOT NULL REFERENCES releases(id) ON DELETE CASCADE,
+ filename TEXT NOT NULL,
+ size INTEGER NOT NULL DEFAULT 0,
+ sha256 TEXT NOT NULL DEFAULT '',
+ downloads INTEGER NOT NULL DEFAULT 0,
+ created_at TEXT NOT NULL,
+ UNIQUE(release_id, filename)
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_releases_repo ON releases(repo_id, id DESC)`,
+ `CREATE INDEX IF NOT EXISTS idx_assets_release ON release_assets(release_id, id)`,
+}
+
+// Release 表示一个项目发行版。
+type Release struct {
+ ID int64
+ RepoID int64
+ RepoName string
+ TagName string
+ Title string
+ Notes string
+ UserID *int64
+ AuthorUsername string
+ AuthorDisplay string
+ CreatedAt time.Time
+ UpdatedAt time.Time
+
+ // 统计字段(列表查询附带)。
+ AssetCount int
+ TotalSize int64
+}
+
+// ReleaseAsset 表示发行版下的一个附件文件。
+type ReleaseAsset struct {
+ ID int64
+ ReleaseID int64
+ Filename string
+ Size int64
+ SHA256 string
+ Downloads int
+ CreatedAt time.Time
+}
+
+const releaseCols = `r.id, r.repo_id, COALESCE(rep.name, ''), r.tag_name, r.title, r.notes,
+ r.user_id, r.author_username, r.author_display, r.created_at, r.updated_at`
+
+func scanRelease(scan func(dest ...any) error) (*Release, error) {
+ var rel Release
+ var userID sql.NullInt64
+ var created, updated string
+ var assetCount int
+ var totalSize int64
+ // 查询统一附带附件数与总体积两个统计列,见 ReleaseByID / ReleasesByRepo。
+ if err := scan(&rel.ID, &rel.RepoID, &rel.RepoName, &rel.TagName, &rel.Title, &rel.Notes,
+ &userID, &rel.AuthorUsername, &rel.AuthorDisplay, &created, &updated, &assetCount, &totalSize); err != nil {
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, ErrNotFound
+ }
+ return nil, err
+ }
+ if userID.Valid {
+ id := userID.Int64
+ rel.UserID = &id
+ }
+ rel.AssetCount = assetCount
+ rel.TotalSize = totalSize
+ rel.CreatedAt = parseTime(created)
+ rel.UpdatedAt = parseTime(updated)
+ return &rel, nil
+}
+
+// CreateRelease 新建发行版。作者名字以快照形式留存,删号后仍可展示。
+func (s *Store) CreateRelease(repoID int64, userID *int64, authorUsername, authorDisplay, tagName, title, notes string) (*Release, error) {
+ ts := nowString()
+ res, err := s.db.Exec(`INSERT INTO releases(repo_id, tag_name, title, notes, user_id, author_username, author_display, created_at, updated_at)
+ VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ repoID, tagName, title, notes, userID, authorUsername, authorDisplay, ts, ts)
+ if err != nil {
+ return nil, err
+ }
+ id, _ := res.LastInsertId()
+ return s.ReleaseByID(id)
+}
+
+// ReleaseByID 按主键查询发行版,附带附件数与附件总体积。
+func (s *Store) ReleaseByID(id int64) (*Release, error) {
+ return scanRelease(s.db.QueryRow(`SELECT `+releaseCols+`,
+ (SELECT COUNT(*) FROM release_assets a WHERE a.release_id = r.id),
+ COALESCE((SELECT SUM(a.size) FROM release_assets a WHERE a.release_id = r.id), 0)
+ FROM releases r LEFT JOIN repos rep ON rep.id = r.repo_id WHERE r.id = ?`, id).Scan)
+}
+
+// ReleasesByRepo 返回项目的发行版列表(新的在前)。
+func (s *Store) ReleasesByRepo(repoID int64, limit int) ([]*Release, error) {
+ rows, err := s.db.Query(`SELECT `+releaseCols+`,
+ (SELECT COUNT(*) FROM release_assets a WHERE a.release_id = r.id),
+ COALESCE((SELECT SUM(a.size) FROM release_assets a WHERE a.release_id = r.id), 0)
+ FROM releases r LEFT JOIN repos rep ON rep.id = r.repo_id
+ WHERE r.repo_id = ? ORDER BY r.id DESC LIMIT ?`, repoID, limit)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []*Release
+ for rows.Next() {
+ rel, err := scanRelease(rows.Scan)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, rel)
+ }
+ return out, rows.Err()
+}
+
+// ReleaseCount 返回项目的发行版数量(仓库 Tab 上的角标)。
+func (s *Store) ReleaseCount(repoID int64) int {
+ var n int
+ _ = s.db.QueryRow(`SELECT COUNT(*) FROM releases WHERE repo_id = ?`, repoID).Scan(&n)
+ return n
+}
+
+// UpdateRelease 保存发行版的可编辑字段。
+func (s *Store) UpdateRelease(id int64, tagName, title, notes string) error {
+ _, err := s.db.Exec(`UPDATE releases SET tag_name = ?, title = ?, notes = ?, updated_at = ? WHERE id = ?`,
+ tagName, title, notes, nowString(), id)
+ return err
+}
+
+// DeleteRelease 删除发行版(附件行级联删除,磁盘文件由调用方清理)。
+func (s *Store) DeleteRelease(id int64) error {
+ _, err := s.db.Exec(`DELETE FROM releases WHERE id = ?`, id)
+ return err
+}
+
+// CreateAsset 登记一个附件。同发行版下文件名唯一,重复时报友好错误。
+func (s *Store) CreateAsset(releaseID int64, filename string, size int64, sha256 string) (*ReleaseAsset, error) {
+ res, err := s.db.Exec(`INSERT INTO release_assets(release_id, filename, size, sha256, created_at)
+ VALUES(?, ?, ?, ?, ?)`, releaseID, filename, size, sha256, nowString())
+ if err != nil {
+ if isUniqueErr(err) {
+ return nil, errors.New("该发行版下已存在同名附件")
+ }
+ return nil, err
+ }
+ id, _ := res.LastInsertId()
+ asset, _, err := s.AssetByID(id)
+ return asset, err
+}
+
+const assetCols = `a.id, a.release_id, a.filename, a.size, a.sha256, a.downloads, a.created_at, rel.repo_id`
+
+func scanAsset(scan func(dest ...any) error) (*ReleaseAsset, int64, error) {
+ var a ReleaseAsset
+ var repoID int64
+ var created string
+ if err := scan(&a.ID, &a.ReleaseID, &a.Filename, &a.Size, &a.SHA256, &a.Downloads, &created, &repoID); err != nil {
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, 0, ErrNotFound
+ }
+ return nil, 0, err
+ }
+ a.CreatedAt = parseTime(created)
+ return &a, repoID, nil
+}
+
+// AssetByID 按主键查询附件,并返回所属 repoID(磁盘路径定位需要)。
+func (s *Store) AssetByID(id int64) (*ReleaseAsset, int64, error) {
+ return scanAsset(s.db.QueryRow(`SELECT `+assetCols+` FROM release_assets a
+ JOIN releases rel ON rel.id = a.release_id WHERE a.id = ?`, id).Scan)
+}
+
+// AssetsByRelease 返回发行版下的全部附件。
+func (s *Store) AssetsByRelease(releaseID int64) ([]*ReleaseAsset, error) {
+ rows, err := s.db.Query(`SELECT `+assetCols+` FROM release_assets a
+ JOIN releases rel ON rel.id = a.release_id
+ WHERE a.release_id = ? ORDER BY a.id ASC`, releaseID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []*ReleaseAsset
+ for rows.Next() {
+ a, _, err := scanAsset(rows.Scan)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, a)
+ }
+ return out, rows.Err()
+}
+
+// DeleteAsset 删除附件记录(磁盘文件由调用方清理)。
+func (s *Store) DeleteAsset(id int64) error {
+ _, err := s.db.Exec(`DELETE FROM release_assets WHERE id = ?`, id)
+ return err
+}
+
+// IncAssetDownload 累加附件下载次数。
+func (s *Store) IncAssetDownload(id int64) {
+ _, _ = s.db.Exec(`UPDATE release_assets SET downloads = downloads + 1 WHERE id = ?`, id)
+}
diff --git a/internal/store/store.go b/internal/store/store.go
index 27a047b..07c0066 100644
--- a/internal/store/store.go
+++ b/internal/store/store.go
@@ -131,7 +131,7 @@ var schema = []string{
// 版本 1 = 最原始的 5 张表(无 schema_meta),用于识别旧版数据库。
// SchemaVersion 是当前二进制支持的最新数据库版本。
-const SchemaVersion = 1
+const SchemaVersion = 2
// execer 让迁移既能跑在事务里(*sql.Tx)也能直接跑在连接上(*sql.DB)。
type execer interface {
@@ -149,11 +149,18 @@ type migration struct {
// migrations 追加式列表:新增变更时在末尾追加,version 必须递增。
var migrations = []migration{
- // 示例:
- // {version: 2, name: "repos 加 visibility", run: func(db *sql.DB) error {
- // _, err := db.Exec(`ALTER TABLE repos ADD COLUMN visibility TEXT NOT NULL DEFAULT 'public'`)
- // return err
- // }},
+ {
+ version: 2,
+ name: "发行版与附件表",
+ run: func(e execer) error {
+ for _, stmt := range releasesSchema {
+ if _, err := e.Exec(stmt); err != nil {
+ return err
+ }
+ }
+ return nil
+ },
+ },
}
const schemaMetaTable = `CREATE TABLE IF NOT EXISTS schema_meta (
diff --git a/webroot/static/release-upload.js b/webroot/static/release-upload.js
new file mode 100644
index 0000000..a1d4a82
--- /dev/null
+++ b/webroot/static/release-upload.js
@@ -0,0 +1,148 @@
+/* 发行版附件分片上传:8MB/片,顺序发送,单片失败自动重试,
+ 全程 fetch + Blob 切片,内存占用只有单片大小。 */
+(function () {
+ 'use strict';
+
+ var box = document.getElementById('release-upload');
+ if (!box) return;
+
+ var base = box.getAttribute('data-base') || '';
+ var csrfEl = document.getElementById('upload-csrf');
+ var input = document.getElementById('release-file');
+ var btn = document.getElementById('release-upload-btn');
+ var list = document.getElementById('upload-list');
+ var csrf = csrfEl ? csrfEl.value : '';
+
+ function el(tag, cls, text) {
+ var n = document.createElement(tag);
+ if (cls) n.className = cls;
+ if (text !== undefined) n.textContent = text;
+ return n;
+ }
+
+ function csrfQuery() {
+ return 'csrf=' + encodeURIComponent(csrf);
+ }
+
+ function readJSON(res) {
+ return res.json().then(function (j) {
+ if (!res.ok) {
+ throw new Error(j.error || ('HTTP ' + res.status));
+ }
+ return j;
+ }, function () {
+ throw new Error('HTTP ' + res.status);
+ });
+ }
+
+ /* 带重试的 fetch:网络抖动 / 瞬时 5xx 时最多再试两次。 */
+ function fetchRetry(build, attempts) {
+ function once(n) {
+ return build().catch(function (err) {
+ if (n + 1 >= attempts) throw err;
+ return new Promise(function (resolve) {
+ setTimeout(resolve, 1500);
+ }).then(function () { return once(n + 1); });
+ });
+ }
+ return once(0);
+ }
+
+ function uploadFile(file, row, bar, status) {
+ var initURL = base + '/upload/init?' + csrfQuery();
+ return fetch(initURL, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: file.name, size: file.size })
+ }).then(readJSON).then(function (info) {
+ var chunkSize = info.chunk_size || 8 * 1024 * 1024;
+ var total = Math.max(1, Math.ceil(file.size / chunkSize));
+ var i = 0;
+
+ function next() {
+ if (i >= total) return null;
+ var start = i * chunkSize;
+ var blob = file.slice(start, Math.min(start + chunkSize, file.size));
+ var idx = i;
+ return fetchRetry(function () {
+ return fetch(base + '/upload/' + info.upload_id + '?index=' + idx + '&' + csrfQuery(), {
+ method: 'PUT',
+ body: blob
+ }).then(readJSON);
+ }, 3).then(function () {
+ i++;
+ var pct = Math.round(i / total * 100);
+ bar.value = pct;
+ status.textContent = pct + '%';
+ return next();
+ });
+ }
+
+ return next().then(function () {
+ status.textContent = '合并中…';
+ return fetchRetry(function () {
+ return fetch(base + '/upload/' + info.upload_id + '/complete?' + csrfQuery(), {
+ method: 'POST'
+ }).then(readJSON);
+ }, 3);
+ });
+ });
+ }
+
+ function uploadQueue(files) {
+ var chain = Promise.resolve();
+ files.forEach(function (file) {
+ var row = el('li', 'upload-item');
+ var name = el('span', 'upload-name', file.name + '(' + humanSize(file.size) + ')');
+ var bar = document.createElement('progress');
+ bar.max = 100;
+ bar.value = 0;
+ var status = el('span', 'upload-status', '排队中…');
+ row.appendChild(name);
+ row.appendChild(bar);
+ row.appendChild(status);
+ list.appendChild(row);
+
+ chain = chain.then(function () {
+ status.textContent = '0%';
+ return uploadFile(file, row, bar, status);
+ }).then(function () {
+ row.classList.add('done');
+ bar.value = 100;
+ status.textContent = '完成';
+ }).catch(function (err) {
+ row.classList.add('failed');
+ status.textContent = '失败:' + (err && err.message ? err.message : '未知错误');
+ });
+ });
+ return chain.then(function () {
+ uploading = false;
+ input.disabled = false;
+ btn.disabled = false;
+ // 有完成的项才刷新页面,让附件列表与校验值出现。
+ if (list.querySelector('.upload-item.done')) {
+ setTimeout(function () { location.reload(); }, 800);
+ }
+ });
+ }
+
+ function humanSize(n) {
+ var units = ['B', 'KB', 'MB', 'GB', 'TB'];
+ var f = n, i = 0;
+ while (f >= 1024 && i < units.length - 1) { f /= 1024; i++; }
+ return (i === 0 ? f : f.toFixed(1)) + ' ' + units[i];
+ }
+
+ var uploading = false;
+ btn.addEventListener('click', function () {
+ if (uploading || !input.files || !input.files.length) return;
+ if (!csrf) {
+ window.alert('缺少 CSRF 令牌,请刷新页面重试');
+ return;
+ }
+ uploading = true;
+ input.disabled = true;
+ btn.disabled = true;
+ uploadQueue(Array.prototype.slice.call(input.files));
+ });
+})();
diff --git a/webroot/static/style.css b/webroot/static/style.css
index d3406a7..1a21a3b 100644
--- a/webroot/static/style.css
+++ b/webroot/static/style.css
@@ -489,6 +489,19 @@ legend { font-weight: 700; font-size: .95rem; margin-bottom: 12px; display: flex
.wn-body ul { padding-left: 1.1em; }
.wn-foot { font-size: .8rem; margin-top: 12px; border-top: 1px solid var(--line-2); padding-top: 10px; }
+/* 主页侧栏:发行版板块 */
+.releases-side .rel-badge {
+ display: inline-block; margin-left: 7px; padding: 0 8px; border-radius: 999px;
+ background: #eef3f6; color: var(--ink-3); font-size: .78rem; font-weight: 700; vertical-align: 1px;
+}
+.rel-latest { display: flex; flex-direction: column; gap: 6px; padding: 10px 12px; margin-bottom: 12px; border: 1px solid var(--line-2); border-radius: 10px; background: var(--mint-50); }
+.rel-top { display: flex; align-items: center; gap: 8px; }
+.rel-title { font-size: .92rem; font-weight: 700; color: var(--blue-600); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.rel-title:hover { text-decoration: underline; }
+.rel-meta { display: flex; align-items: baseline; flex-wrap: wrap; gap: 5px; font-size: .8rem; }
+.rel-meta .dot { margin: 0 1px; }
+.rel-foot { display: flex; justify-content: space-between; border-top: 1px solid var(--line-2); padding-top: 10px; font-size: .85rem; }
+
.kv { list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 9px; font-size: .88rem; }
.kv li { display: flex; justify-content: space-between; gap: 10px; align-items: baseline; }
.kv span { color: var(--ink-3); }
@@ -712,4 +725,28 @@ legend { font-weight: 700; font-size: .95rem; margin-bottom: 12px; display: flex
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { animation-duration: .001ms !important; transition-duration: .001ms !important; }
-}
\ No newline at end of file
+}
+/* ---------------------------------------------------------- 发行版 Releases */
+.release-card { margin-bottom: 16px; }
+.release-head { display: flex; flex-wrap: wrap; align-items: baseline; justify-content: space-between; gap: 8px; margin-bottom: 10px; }
+.release-title { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
+.release-name { font-size: 1.05rem; font-weight: 750; color: var(--ink-1, #16232b); text-decoration: none; }
+a.release-name:hover { color: var(--green-700); }
+.tag-latest { background: var(--mint-100); color: var(--green-700); }
+.release-meta { font-size: .85rem; display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
+.release-notes { margin-top: 10px; border-top: 1px solid #e6ecef; padding-top: 10px; }
+.release-edit { margin-top: 14px; border-top: 1px dashed #dfe7ec; padding-top: 12px; }
+.release-edit summary { cursor: pointer; font-weight: 650; color: var(--ink-2, #3d5260); margin-bottom: 12px; }
+.release-edit form + form { margin-top: 12px; }
+.asset-table { width: 100%; border-collapse: collapse; font-size: .92rem; }
+.asset-table th, .asset-table td { text-align: left; padding: 9px 10px; border-bottom: 1px solid #eef2f5; vertical-align: middle; }
+.asset-table th { font-size: .76rem; color: var(--ink-3); text-transform: uppercase; letter-spacing: .04em; }
+.asset-table .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
+.upload-row { display: flex; gap: 10px; align-items: center; margin: 10px 0 4px; }
+.upload-row input[type="file"] { flex: 1; min-width: 0; }
+.upload-list { list-style: none; margin: 8px 0 0; padding: 0; display: grid; gap: 8px; }
+.upload-item { display: flex; align-items: center; gap: 10px; font-size: .88rem; background: #f7fafb; border: 1px solid #e6ecef; border-radius: 10px; padding: 8px 12px; }
+.upload-item .upload-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.upload-item progress { width: 120px; height: 10px; accent-color: #12b886; }
+.upload-item.done .upload-status { color: var(--green-700); font-weight: 700; }
+.upload-item.failed .upload-status { color: var(--danger); }
diff --git a/webroot/templates/layout.html b/webroot/templates/layout.html
index 93b1ac4..413d2f5 100644
--- a/webroot/templates/layout.html
+++ b/webroot/templates/layout.html
@@ -48,6 +48,7 @@
<a class="{{if eq .Tab "code"}}on{{end}}" href="/{{.Repo.Name}}{{if .Ref}}?ref={{.Ref}}{{end}}">代码</a>
<a class="{{if eq .Tab "commits"}}on{{end}}" href="/{{.Repo.Name}}/commits/{{.Ref}}">提交 <span class="cnt">{{.CommitCount}}</span></a>
<a class="{{if eq .Tab "branches"}}on{{end}}" href="/{{.Repo.Name}}/branches">分支 <span class="cnt">{{.BranchCount}}</span></a>
+ <a class="{{if eq .Tab "releases"}}on{{end}}" href="/{{.Repo.Name}}/releases">发行版 <span class="cnt">{{.ReleaseCount}}</span></a>
<a class="{{if eq .Tab "activity"}}on{{end}}" href="/{{.Repo.Name}}/activity">动态</a>
{{if .CanManage}}<a class="{{if eq .Tab "settings"}}on{{end}}" href="/{{.Repo.Name}}/settings">设置</a>{{end}}
</nav>
diff --git a/webroot/templates/repo_activity.html b/webroot/templates/repo_activity.html
index 8cb0dbb..4637630 100644
--- a/webroot/templates/repo_activity.html
+++ b/webroot/templates/repo_activity.html
@@ -8,7 +8,7 @@
<div><h1>{{$repo.Name}}</h1></div>
</div>
</header>
-{{template "repotabs" (dict "Repo" $repo "Ref" .Data.Ref "Tab" "activity" "CanManage" .Data.CanManage "CommitCount" .Data.CommitCount "BranchCount" .Data.BranchCount)}}
+{{template "repotabs" (dict "Repo" $repo "Ref" .Data.Ref "Tab" "activity" "CanManage" .Data.CanManage "CommitCount" .Data.CommitCount "BranchCount" .Data.BranchCount "ReleaseCount" .Data.ReleaseCount)}}
<div class="repo-grid">
<div class="repo-main">
diff --git a/webroot/templates/repo_blob.html b/webroot/templates/repo_blob.html
index 59721a0..75448da 100644
--- a/webroot/templates/repo_blob.html
+++ b/webroot/templates/repo_blob.html
@@ -8,7 +8,7 @@
<div><h1>{{$repo.Name}}</h1></div>
</div>
</header>
-{{template "repotabs" (dict "Repo" $repo "Ref" .Data.Ref "Tab" "code" "CanManage" .Data.CanManage "CommitCount" .Data.CommitCount "BranchCount" .Data.BranchCount)}}
+{{template "repotabs" (dict "Repo" $repo "Ref" .Data.Ref "Tab" "code" "CanManage" .Data.CanManage "CommitCount" .Data.CommitCount "BranchCount" .Data.BranchCount "ReleaseCount" .Data.ReleaseCount)}}
<div class="crumb-bar">
<a class="crumb" href="/{{$repo.Name}}/tree/{{.Data.Ref}}">{{$repo.Name}}</a><span class="sep">/</span>
diff --git a/webroot/templates/repo_branches.html b/webroot/templates/repo_branches.html
index 6ef9470..ab7c8b6 100644
--- a/webroot/templates/repo_branches.html
+++ b/webroot/templates/repo_branches.html
@@ -8,7 +8,7 @@
<div><h1>{{$repo.Name}}</h1></div>
</div>
</header>
-{{template "repotabs" (dict "Repo" $repo "Ref" .Data.Ref "Tab" "branches" "CanManage" .Data.CanManage "CommitCount" .Data.CommitCount "BranchCount" .Data.BranchCount)}}
+{{template "repotabs" (dict "Repo" $repo "Ref" .Data.Ref "Tab" "branches" "CanManage" .Data.CanManage "CommitCount" .Data.CommitCount "BranchCount" .Data.BranchCount "ReleaseCount" .Data.ReleaseCount)}}
<div class="split">
<div class="col-main">
diff --git a/webroot/templates/repo_commits.html b/webroot/templates/repo_commits.html
index 247fffa..8899ce4 100644
--- a/webroot/templates/repo_commits.html
+++ b/webroot/templates/repo_commits.html
@@ -8,7 +8,7 @@
<div><h1>{{$repo.Name}}</h1></div>
</div>
</header>
-{{template "repotabs" (dict "Repo" $repo "Ref" .Data.Ref "Tab" "commits" "CanManage" .Data.CanManage "CommitCount" .Data.CommitCount "BranchCount" .Data.BranchCount)}}
+{{template "repotabs" (dict "Repo" $repo "Ref" .Data.Ref "Tab" "commits" "CanManage" .Data.CanManage "CommitCount" .Data.CommitCount "BranchCount" .Data.BranchCount "ReleaseCount" .Data.ReleaseCount)}}
<div class="repo-grid">
<div class="repo-main">
diff --git a/webroot/templates/repo_home.html b/webroot/templates/repo_home.html
index 55594a4..24abb3a 100644
--- a/webroot/templates/repo_home.html
+++ b/webroot/templates/repo_home.html
@@ -19,7 +19,7 @@
</div>
</header>
-{{template "repotabs" (dict "Repo" $repo "Ref" .Data.Ref "Tab" "code" "CanManage" .Data.CanManage "CommitCount" .Data.CommitCount "BranchCount" .Data.BranchCount)}}
+{{template "repotabs" (dict "Repo" $repo "Ref" .Data.Ref "Tab" "code" "CanManage" .Data.CanManage "CommitCount" .Data.CommitCount "BranchCount" .Data.BranchCount "ReleaseCount" .Data.ReleaseCount)}}
<div class="repo-grid">
<div class="repo-main">
@@ -128,6 +128,33 @@ git push -u origin main</pre>
{{end}}
</ul>
</div>
+
+ <div class="card about releases-side">
+ <h3>发行版<span class="rel-badge">{{num .Data.ReleaseCount}}</span></h3>
+ {{if .Data.LatestRelease}}
+ {{with .Data.LatestRelease}}
+ <div class="rel-latest">
+ <div class="rel-top">
+ {{if .TagName}}<a class="pill" href="/{{$repo.Name}}/commits/{{.TagName}}" title="查看该标签的提交">{{.TagName}}</a>{{end}}
+ <span class="tag tag-latest">最新</span>
+ </div>
+ <a class="rel-title" href="/{{$repo.Name}}/releases/{{.ID}}">{{if .Title}}{{.Title}}{{else}}未命名发行版{{end}}</a>
+ <div class="rel-meta muted">
+ {{if .AuthorDisplay}}{{.AuthorDisplay}}<span class="dot">·</span>{{end}}
+ <span title="{{datetime .CreatedAt}}">{{timeago .CreatedAt}}</span>
+ <span class="dot">·</span>
+ {{num .AssetCount}} 个附件{{if .TotalSize}} · {{humanSize .TotalSize}}{{end}}
+ </div>
+ </div>
+ {{end}}
+ {{else}}
+ <p class="muted small">还没有发行版,发布一个让用户下载构建产物。</p>
+ {{end}}
+ <div class="rel-foot">
+ <a class="quiet" href="/{{$repo.Name}}/releases">查看全部发行版</a>
+ {{if .Data.CanManage}}<a class="quiet" href="/{{$repo.Name}}/releases/new">新建</a>{{end}}
+ </div>
+ </div>
</aside>
</div>
{{end}}
\ No newline at end of file
diff --git a/webroot/templates/repo_release.html b/webroot/templates/repo_release.html
new file mode 100644
index 0000000..7932c50
--- /dev/null
+++ b/webroot/templates/repo_release.html
@@ -0,0 +1,100 @@
+{{define "content"}}
+{{$repo := .Data.Repo}}
+{{$rel := .Data.Release}}
+<header class="repo-head compact">
+ <div class="repo-title">
+ <span class="repo-icon lg" aria-hidden="true">
+ <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 8.5 8 4l4 3 4-3 4 4.5"/><path d="M6 12h12v4.5a3.5 3.5 0 0 1-3.5 3.5h-5A3.5 3.5 0 0 1 6 16.5z"/></svg>
+ </span>
+ <div><h1><a class="quiet" href="/{{$repo.Name}}/releases">发行版</a> · {{$rel.Title}}</h1></div>
+ </div>
+</header>
+{{template "repotabs" (dict "Repo" $repo "Ref" .Data.Ref "Tab" "releases" "CanManage" .Data.CanManage "CommitCount" .Data.CommitCount "BranchCount" .Data.BranchCount "ReleaseCount" .Data.ReleaseCount)}}
+
+<div class="repo-grid">
+ <div class="repo-main">
+ <article class="card release-card">
+ <header class="release-head">
+ <div class="release-title">
+ <span class="release-name">{{$rel.Title}}</span>
+ {{if $rel.TagName}}<a class="pill" href="/{{$repo.Name}}/commits/{{$rel.TagName}}">{{$rel.TagName}}</a>{{end}}
+ </div>
+ <div class="release-meta">
+ <span class="muted">{{$rel.AuthorDisplay}}</span>
+ <span class="dot">·</span>
+ <span class="muted" title="{{datetime $rel.CreatedAt}}">{{timeago $rel.CreatedAt}}</span>
+ </div>
+ </header>
+ {{if $rel.Notes}}<div class="md-body release-notes">{{md $rel.Notes}}</div>{{else}}<p class="muted">暂无发行说明。</p>{{end}}
+ {{if .Data.CanManage}}
+ <details class="release-edit">
+ <summary>编辑本发行版</summary>
+ <form method="post" action="{{.Data.Base}}/edit">
+ <input type="hidden" name="csrf" value="{{.CSRF}}">
+ <label class="field"><span>标签</span><input type="text" name="tag_name" value="{{$rel.TagName}}" maxlength="120"></label>
+ <label class="field"><span>标题</span><input type="text" name="title" value="{{$rel.Title}}" maxlength="200"></label>
+ <label class="field"><span>发行说明(Markdown)</span><textarea name="notes" rows="8">{{$rel.Notes}}</textarea></label>
+ <button class="btn btn-primary" type="submit">保存修改</button>
+ </form>
+ <form method="post" action="{{.Data.Base}}/delete" data-confirm="确定删除该发行版及其全部附件?此操作不可恢复。">
+ <input type="hidden" name="csrf" value="{{.CSRF}}">
+ <button class="btn btn-danger" type="submit">删除发行版</button>
+ </form>
+ </details>
+ {{end}}
+ </article>
+
+ <div class="card">
+ <div class="card-title">附件({{num (len .Data.Assets)}})</div>
+ {{if .Data.Assets}}
+ <table class="asset-table">
+ <thead><tr><th>文件名</th><th>大小</th><th>下载</th><th>SHA256</th>{{if .Data.CanManage}}<th></th>{{end}}</tr></thead>
+ <tbody>
+ {{range .Data.Assets}}
+ <tr>
+ <td><a href="{{$.Data.Base}}/files/{{.ID}}/{{.Filename}}">{{.Filename}}</a></td>
+ <td class="muted">{{humanSize .Size}}</td>
+ <td class="muted">{{num .Downloads}}</td>
+ <td class="muted mono" title="{{.SHA256}}">{{if .SHA256}}{{short .SHA256}}{{else}}—{{end}}</td>
+ {{if $.Data.CanManage}}
+ <td>
+ <form method="post" action="{{$.Data.Base}}/assets/{{.ID}}/delete" data-confirm="删除附件 {{.Filename}}?">
+ <input type="hidden" name="csrf" value="{{$.CSRF}}">
+ <button class="btn btn-mini" type="submit">删除</button>
+ </form>
+ </td>
+ {{end}}
+ </tr>
+ {{end}}
+ </tbody>
+ </table>
+ {{else}}
+ <p class="muted">还没有附件。</p>
+ {{end}}
+ </div>
+ </div>
+
+ <aside class="repo-side">
+ {{if .Data.CanManage}}
+ <div class="card" id="release-upload" data-base="{{.Data.Base}}">
+ <div class="card-title">上传附件</div>
+ <input type="hidden" id="upload-csrf" value="{{.CSRF}}">
+ <p class="muted">支持大文件:浏览器自动按 8MB 分片上传,失败自动重试,刷新页面后可对同一文件重新发起(已传分片会被校验覆盖)。单个附件最大 4GB。</p>
+ <div class="upload-row">
+ <input type="file" id="release-file" multiple aria-label="选择要上传的文件">
+ <button class="btn btn-primary" id="release-upload-btn" type="button">开始上传</button>
+ </div>
+ <ul class="upload-list" id="upload-list"></ul>
+ </div>
+ {{end}}
+ <div class="card about">
+ <h3>直接下载</h3>
+ <p class="muted">附件链接支持 HTTP Range 断点续传,可以用 wget / curl 直接拉取:</p>
+ {{range .Data.Assets}}
+ <pre class="code">curl -LO {{$.Data.OriginURL}}{{$.Data.Base}}/files/{{.ID}}/{{.Filename}}</pre>
+ {{end}}
+ </div>
+ </aside>
+</div>
+<script src="/static/release-upload.js" defer></script>
+{{end}}
diff --git a/webroot/templates/repo_release_new.html b/webroot/templates/repo_release_new.html
new file mode 100644
index 0000000..c2f886e
--- /dev/null
+++ b/webroot/templates/repo_release_new.html
@@ -0,0 +1,43 @@
+{{define "content"}}
+{{$repo := .Data.Repo}}
+<div class="split">
+ <div class="col-main">
+ <div class="card">
+ <h1 class="card-title">新建发行版</h1>
+ <p class="muted">创建后可以在发行版页面继续上传附件(安装包、压缩包等)。</p>
+ <form method="post" action="/{{$repo.Name}}/releases/new" autocomplete="off">
+ <input type="hidden" name="csrf" value="{{.CSRF}}">
+ <label class="field">
+ <span>标签(可选)</span>
+ <input type="text" name="tag_name" list="taglist" maxlength="120" placeholder="例如:v1.0.0">
+ <datalist id="taglist">
+ {{range .Data.Tags}}<option value="{{.Name}}">{{end}}
+ </datalist>
+ <em class="field-hint">填写仓库里已有的 tag,或计划推送的 tag 名称;留空则纯作公告用。</em>
+ </label>
+ <label class="field">
+ <span>标题(可选)</span>
+ <input type="text" name="title" maxlength="200" placeholder="留空时使用标签名作为标题">
+ </label>
+ <label class="field">
+ <span>发行说明(Markdown,可选)</span>
+ <textarea name="notes" rows="10" placeholder="## 新特性 - 支持发行版附件 ## 修复 - 大文件上传中断的问题"></textarea>
+ <em class="field-hint">支持 Markdown,最多 50KB。</em>
+ </label>
+ <button class="btn btn-primary btn-lg" type="submit">创建发行版</button>
+ <a class="btn" href="/{{$repo.Name}}/releases">取消</a>
+ </form>
+ </div>
+ </div>
+ <aside class="col-side">
+ <div class="card tip-card">
+ <h3>发行版包含什么?</h3>
+ <ul class="steps">
+ <li><span class="step">1</span><div><strong>标签</strong>:对应仓库里的一个 git tag,方便回溯代码状态。</div></li>
+ <li><span class="step">2</span><div><strong>发行说明</strong>:这个版本改了什么,支持 Markdown 排版。</div></li>
+ <li><span class="step">3</span><div><strong>附件</strong>:可执行文件、安装包等构建产物,单个最大 4GB,自动分片上传。</div></li>
+ </ul>
+ </div>
+ </aside>
+</div>
+{{end}}
diff --git a/webroot/templates/repo_releases.html b/webroot/templates/repo_releases.html
new file mode 100644
index 0000000..bd9a515
--- /dev/null
+++ b/webroot/templates/repo_releases.html
@@ -0,0 +1,45 @@
+{{define "content"}}
+{{$repo := .Data.Repo}}
+<header class="repo-head compact">
+ <div class="repo-title">
+ <span class="repo-icon lg" aria-hidden="true">
+ <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M4 5.5A1.5 1.5 0 0 1 5.5 4H9l1.5 2H18a1.5 1.5 0 0 1 1.5 1.5v9A1.5 1.5 0 0 1 18 18H5.5A1.5 1.5 0 0 1 4 16.5z"/></svg>
+ </span>
+ <div><h1>{{$repo.Name}}</h1></div>
+ </div>
+</header>
+{{template "repotabs" (dict "Repo" $repo "Ref" .Data.Ref "Tab" "releases" "CanManage" .Data.CanManage "CommitCount" .Data.CommitCount "BranchCount" .Data.BranchCount "ReleaseCount" .Data.ReleaseCount)}}
+
+<div class="section-head">
+ <h2>发行版</h2>
+ {{if .Data.CanManage}}<a class="btn btn-primary" href="/{{$repo.Name}}/releases/new">新建发行版</a>{{end}}
+</div>
+
+{{if .Data.Releases}}
+{{range .Data.Releases}}
+<article class="card release-card">
+ <header class="release-head">
+ <div class="release-title">
+ <a class="release-name" href="/{{$repo.Name}}/releases/{{.ID}}">{{.Title}}</a>
+ {{if .TagName}}<a class="pill" href="/{{$repo.Name}}/commits/{{.TagName}}" title="查看该标签的提交">{{.TagName}}</a>{{end}}
+ <span class="tag tag-latest">最新</span>
+ </div>
+ <div class="release-meta">
+ <span class="muted">{{.AuthorDisplay}}</span>
+ <span class="dot">·</span>
+ <span class="muted" title="{{datetime .CreatedAt}}">{{timeago .CreatedAt}}</span>
+ <span class="dot">·</span>
+ <span class="muted">{{num .AssetCount}} 个附件</span>
+ {{if .TotalSize}}<span class="dot">·</span><span class="muted">{{humanSize .TotalSize}}</span>{{end}}
+ </div>
+ </header>
+ {{if .Notes}}<div class="md-body release-notes">{{md .Notes}}</div>{{end}}
+</article>
+{{end}}
+{{else}}
+<div class="card empty">
+ <h3>还没有发行版</h3>
+ <p class="muted">发布第一个发行版,把构建产物和更新说明分享给团队。{{if .Data.CanManage}}<a href="/{{$repo.Name}}/releases/new">立即创建</a>{{end}}</p>
+</div>
+{{end}}
+{{end}}
diff --git a/webroot/templates/repo_settings.html b/webroot/templates/repo_settings.html
index ebac26b..cffd5e1 100644
--- a/webroot/templates/repo_settings.html
+++ b/webroot/templates/repo_settings.html
@@ -8,7 +8,7 @@
<div><h1>{{$repo.Name}}</h1></div>
</div>
</header>
-{{template "repotabs" (dict "Repo" $repo "Ref" .Data.Ref "Tab" "settings" "CanManage" .Data.CanManage "CommitCount" .Data.CommitCount "BranchCount" .Data.BranchCount)}}
+{{template "repotabs" (dict "Repo" $repo "Ref" .Data.Ref "Tab" "settings" "CanManage" .Data.CanManage "CommitCount" .Data.CommitCount "BranchCount" .Data.BranchCount "ReleaseCount" .Data.ReleaseCount)}}
<div class="split">
<div class="col-main">