收录 main、注释开发快照和完整运行 SHA;开发说明绑定原提交,补记 0.1.1–0.1.25。 进行中同步按仓库合并,完成后重新执行;启动入队,部署脚本读回版本证据。 开发快照独立于正式标签与 Release,既有冲突标签不移动。 已运行:整仓 make verify,Go 673 通过、前端 274 通过,92 个已声明可选跳过,必需跳过 0。 隔离 PostgreSQL 重复同步队列用例及 -race 通过;未更新现有 8088、未修改生产问答。
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
package governance
|
||||
|
||||
import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Development headings cannot replace the formal release baseline.
|
||||
func ExtractDevelopmentNotes(changelog, version string) string {
|
||||
if !SemverValid(version) {
|
||||
return ""
|
||||
}
|
||||
lines := strings.Split(changelog, "\n")
|
||||
prefix := "## 开发快照 snapshot/v" + version + " - "
|
||||
for i, line := range lines {
|
||||
if strings.HasPrefix(line, prefix) {
|
||||
end := len(lines)
|
||||
for j := i + 1; j < len(lines); j++ {
|
||||
if strings.HasPrefix(lines[j], "## ") {
|
||||
end = j
|
||||
break
|
||||
}
|
||||
}
|
||||
return strings.TrimSpace(strings.Join(lines[i+1:end], "\n"))
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -225,10 +225,26 @@ func versionHistorySync(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
versionHistoryError(w, http.StatusInternalServerError, "version_history_unavailable", "构造同步任务失败")
|
||||
return
|
||||
}
|
||||
if queue, ok := config.Store.(interface {
|
||||
EnqueueVersionHistorySync(context.Context, string, string, string, time.Time) (*jobs.Job, error)
|
||||
}); ok {
|
||||
target := ""
|
||||
info := version.Snapshot()
|
||||
if info.IdentityAvailable && info.CommitSHA != nil {
|
||||
target = *info.CommitSHA
|
||||
}
|
||||
job, e := queue.EnqueueVersionHistorySync(r.Context(), config.VersionHistoryRepo, triggeredBy, target, now)
|
||||
if e != nil || job == nil {
|
||||
versionHistoryError(w, 500, "version_history_unavailable", "入队同步任务失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, 202, map[string]any{"job_id": job.ID, "status": job.State})
|
||||
return
|
||||
}
|
||||
requestedID := fmt.Sprintf("version-history-sync-%d", now.UnixNano())
|
||||
job, err := config.Store.Enqueue(r.Context(), jobs.EnqueueRequest{ID: requestedID,
|
||||
Type: VersionHistoryJobType, Payload: payload, AvailableAt: now, MaxAttempts: 3,
|
||||
IdempotencyKey: "version-history.sync:" + config.VersionHistoryRepo}, now)
|
||||
IdempotencyKey: "version-history.sync:" + config.VersionHistoryRepo + ":" + requestedID}, now)
|
||||
if err != nil || job == nil {
|
||||
versionHistoryError(w, http.StatusInternalServerError, "version_history_unavailable", "入队同步任务失败")
|
||||
return
|
||||
|
||||
@@ -237,7 +237,7 @@ func TestVersionHistorySyncRequiresAdminAndEnqueuesOnce(t *testing.T) {
|
||||
if recorder.Code != http.StatusAccepted {
|
||||
t.Fatalf("首次同步应 202,得到 %d(%s)", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if queue.enqueued.Type != VersionHistoryJobType || queue.enqueued.IdempotencyKey != "version-history.sync:Weknora/knowledge-governance" {
|
||||
if queue.enqueued.Type != VersionHistoryJobType || queue.enqueued.IdempotencyKey != "version-history.sync:Weknora/knowledge-governance:"+queue.enqueued.ID {
|
||||
t.Fatalf("入队参数不对:%+v", queue.enqueued)
|
||||
}
|
||||
if queue.enqueued.MaxAttempts != 3 || queue.enqueued.AvailableAt != now {
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/versionhistory"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (s *Store) EnqueueVersionHistorySync(ctx context.Context, repo, actor, target string, now time.Time) (*jobs.Job, error) {
|
||||
if strings.Count(repo, "/") != 1 || strings.TrimSpace(repo) != repo || len(repo) > 200 || actor == "" || len(actor) > 256 || target != "" && !regexp.MustCompile(`^[a-f0-9]{40}$`).MatchString(target) {
|
||||
return nil, errors.New("invalid version synchronization request")
|
||||
}
|
||||
tx, e := s.db.Begin(ctx)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
if _, e = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, "version-history:"+repo); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
// Retire exhausted expired owners. Terminal jobs are history, not a perpetual
|
||||
// idempotency key: a later refresh must be allowed to execute again.
|
||||
if _, e = tx.Exec(ctx, `UPDATE jobs SET state='failed',lease_owner=NULL,lease_until=NULL,updated_at=$3 WHERE type=$1 AND payload->>'repo_key'=$2 AND state='running' AND lease_until<clock_timestamp() AND attempt>=max_attempts`, versionhistory.JobType, repo, now); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
var active string
|
||||
e = tx.QueryRow(ctx, `SELECT id FROM jobs WHERE type=$1 AND payload->>'repo_key'=$2 AND state IN ('pending','running','retry') ORDER BY created_at DESC,id DESC LIMIT 1`, versionhistory.JobType, repo).Scan(&active)
|
||||
if e != nil && !errors.Is(e, pgx.ErrNoRows) {
|
||||
return nil, e
|
||||
}
|
||||
if active != "" {
|
||||
job, e := scanJob(tx.QueryRow(ctx, `SELECT id,type,payload,state,priority,available_at,lease_owner,lease_until,attempt,max_attempts,last_error,idempotency_key,created_at,updated_at FROM jobs WHERE id=$1`, active))
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if e = tx.Commit(ctx); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
return job, nil
|
||||
}
|
||||
var random [16]byte
|
||||
if _, e = rand.Read(random[:]); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
id := "vh-" + hex.EncodeToString(random[:])
|
||||
payload, _ := json.Marshal(map[string]string{"repo_key": repo, "triggered_by": actor, "target_sha": target})
|
||||
job, e := NewStore(tx).Enqueue(ctx, jobs.EnqueueRequest{ID: id, Type: versionhistory.JobType, Payload: payload, AvailableAt: now, MaxAttempts: 3, IdempotencyKey: "version-history:" + repo + ":" + id}, now)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if e = tx.Commit(ctx); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
return job, nil
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/versionhistory"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestVersionHistorySyncQueueCanRefreshAfterCompletion(t *testing.T) {
|
||||
dsn := os.Getenv("KG_VERSION_HISTORY_TEST_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("explicit disposable version-history DB required")
|
||||
}
|
||||
u, e := url.Parse(dsn)
|
||||
if e != nil || u.Hostname() != "127.0.0.1" || !strings.HasPrefix(u.Path, "/kg_version_history_test_") {
|
||||
t.Fatal("refusing shared database")
|
||||
}
|
||||
ctx := context.Background()
|
||||
p, e := pgxpool.New(ctx, dsn)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer p.Close()
|
||||
if e = ApplyMigrations(ctx, p); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
s := NewStore(p)
|
||||
one, e := s.EnqueueVersionHistorySync(ctx, "fixture/repo", "fixture-admin", strings.Repeat("a", 40), time.Now())
|
||||
if e != nil || one == nil {
|
||||
t.Fatal("first sync missing", e)
|
||||
}
|
||||
same, e := s.EnqueueVersionHistorySync(ctx, "fixture/repo", "fixture-admin", strings.Repeat("a", 40), time.Now())
|
||||
if e != nil || same.ID != one.ID {
|
||||
t.Fatal("pending sync not coalesced", e)
|
||||
}
|
||||
claimed, e := s.Claim(ctx, "fixture-worker", []string{versionhistory.JobType}, time.Now(), time.Minute)
|
||||
if e != nil || claimed == nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = s.Complete(ctx, claimed.ID, claimed.LeaseOwner, time.Now()); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
next, e := s.EnqueueVersionHistorySync(ctx, "fixture/repo", "fixture-admin", strings.Repeat("b", 40), time.Now())
|
||||
if e != nil || next == nil || next.ID == one.ID || next.State != "pending" {
|
||||
t.Fatal("completed request was replayed forever instead of starting a new refresh", e)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package versionhistory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"knowledge-governance/internal/governance"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func (s *Syncer) includeDeliveredCommits(ctx context.Context, commits []RawCommit, tags []RawTag) ([]RawCommit, error) {
|
||||
seen := map[string]bool{}
|
||||
for _, c := range commits {
|
||||
seen[c.SHA] = true
|
||||
}
|
||||
refs := append([]string{}, s.targetSHAs...)
|
||||
snapshots := []RawTag{}
|
||||
for _, tag := range tags {
|
||||
if tag.Annotated && strings.HasPrefix(tag.Name, "snapshot/v") && governance.SemverValid(strings.TrimPrefix(tag.Name, "snapshot/v")) {
|
||||
snapshots = append(snapshots, tag)
|
||||
}
|
||||
}
|
||||
sort.Slice(snapshots, func(i, j int) bool {
|
||||
return governance.CompareSemver(strings.TrimPrefix(snapshots[i].Name, "snapshot/v"), strings.TrimPrefix(snapshots[j].Name, "snapshot/v")) > 0
|
||||
})
|
||||
for _, tag := range snapshots {
|
||||
refs = append(refs, tag.TargetSHA)
|
||||
}
|
||||
for _, ref := range refs {
|
||||
if seen[ref] {
|
||||
continue
|
||||
}
|
||||
if !fullSHA.MatchString(ref) {
|
||||
return nil, fmt.Errorf("开发快照缺少完整提交身份")
|
||||
}
|
||||
extra, total, e := s.fetchCommitsAt(ctx, ref)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if total > 0 && len(extra) != total {
|
||||
return nil, codeError{code: ErrorCodeCountMismatch, message: "开发快照提交历史不完整"}
|
||||
}
|
||||
found := false
|
||||
for _, c := range extra {
|
||||
if c.SHA == ref {
|
||||
found = true
|
||||
}
|
||||
if !seen[c.SHA] {
|
||||
seen[c.SHA] = true
|
||||
commits = append(commits, c)
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return nil, codeError{code: ErrorCodeIncompletePages, message: "开发快照目标没有被取回"}
|
||||
}
|
||||
}
|
||||
return commits, nil
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package versionhistory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"knowledge-governance/internal/governance"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestGiteaSnapshotRefIsExplicitAndNotesArePreserved(t *testing.T) {
|
||||
server := fakeGitea(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/api/v1/repos/Weknora/knowledge-governance/commits" {
|
||||
if r.URL.Query().Get("sha") != shaB {
|
||||
t.Error("snapshot commit history silently used default branch")
|
||||
}
|
||||
fmt.Fprintf(w, `[{"sha":%q,"parents":[],"commit":{"message":"fixture"}}]`, shaB)
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/api/v1/repos/Weknora/knowledge-governance/git/refs/tags" {
|
||||
fmt.Fprintf(w, `[{"ref":"refs/tags/snapshot/v0.1.1","object":{"type":"tag","sha":%q}}]`, shaT)
|
||||
return
|
||||
}
|
||||
fmt.Fprintf(w, `{"message":"development notes","object":{"type":"commit","sha":%q}}`, shaB)
|
||||
})
|
||||
c, _ := NewGiteaClient(validConfig(server.URL))
|
||||
if _, _, e := c.ListCommitsAtRef(context.Background(), shaB, 1, 50); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
tags, e := c.ListTags(context.Background())
|
||||
if e != nil || len(tags) != 1 || tags[0].Message != "development notes" {
|
||||
t.Fatal("annotated snapshot notes lost", e)
|
||||
}
|
||||
}
|
||||
func TestDevelopmentVersionsHaveTheirOwnChangelogNotes(t *testing.T) {
|
||||
a, b := shaA, shaB
|
||||
now := time.Now()
|
||||
text := "# Changelog\n\n## [Unreleased]\n\n### Added\n\n- unrelated future work\n\n## 开发快照 snapshot/v0.1.1 - 2026-10-18\n\n### Fixed\n\n- fix specifically delivered here\n\n## [0.1.0] - 2026-10-13\n\n### Added\n\n- baseline\n"
|
||||
result := DeriveVersions(DeriveInput{Commits: []RawCommit{{SHA: a, CommittedAt: now}, {SHA: b, Parents: []string{a}, CommittedAt: now}}, Tags: []RawTag{{Name: "v0.1.0", TargetSHA: a, Annotated: true}}, Changelog: func(string) (string, error) { return text, nil }})
|
||||
for _, v := range result.Records {
|
||||
if v.CommitSHA == b && (v.ReleaseNotes != "### Fixed\n\n- fix specifically delivered here" || v.RecordKind != governance.RecordKindDevelopment) {
|
||||
t.Fatalf("development version lacks its own notes: %q", v.ReleaseNotes)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHistoricDevelopmentArchiveBindsExactCommit(t *testing.T) {
|
||||
archive := "## 开发快照 snapshot/v0.1.1 - 2026-10-18\n\n目标提交:" + shaB + "\n\n### Fixed\n\n- historic delivery notes\n"
|
||||
input := DeriveInput{DeliveryArchive: archive, Commits: []RawCommit{{SHA: shaA}, {SHA: shaB, Parents: []string{shaA}}}, Tags: []RawTag{{Name: "v0.1.0", TargetSHA: shaA, Annotated: true}}, Changelog: func(string) (string, error) { return "## [0.1.0] - 2026-10-13\n\n### Added\n\n- baseline", nil }}
|
||||
result := DeriveVersions(input)
|
||||
for _, v := range result.Records {
|
||||
if v.CommitSHA == shaB && !strings.Contains(v.ReleaseNotes, "historic delivery notes") {
|
||||
t.Fatal("archived notes missing")
|
||||
}
|
||||
}
|
||||
input.DeliveryArchive = strings.ReplaceAll(archive, shaB, strings.Repeat("c", 40))
|
||||
result = DeriveVersions(input)
|
||||
for _, v := range result.Records {
|
||||
if v.CommitSHA == shaB && v.ReleaseNotes != "" {
|
||||
t.Fatal("different commit reused same-number archive notes")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type snapshotRefSource struct {
|
||||
fakeSource
|
||||
other []RawCommit
|
||||
}
|
||||
|
||||
func (s *snapshotRefSource) ListCommitsAtRef(_ context.Context, _ string, page, limit int) ([]RawCommit, int, error) {
|
||||
if page == 1 {
|
||||
return s.other, len(s.other), nil
|
||||
}
|
||||
return nil, len(s.other), nil
|
||||
}
|
||||
func TestSyncIncludesDeliveredSnapshotOutsideMain(t *testing.T) {
|
||||
a := RawCommit{SHA: shaA}
|
||||
b := RawCommit{SHA: shaB, Parents: []string{shaA}}
|
||||
src := &snapshotRefSource{fakeSource: fakeSource{commits: []RawCommit{a}, total: 1, pageSize: 50, head: shaA, tags: []RawTag{{Name: "snapshot/v0.1.1", TargetSHA: shaB, Annotated: true}}}, other: []RawCommit{b, a}}
|
||||
store := &fakeStore{}
|
||||
run, e := newTestSyncer(t, src, store).Sync(context.Background(), "fixture", "admin")
|
||||
if e != nil || len(store.saved) != 1 || len(store.saved[0].records) != 2 || !run.Complete {
|
||||
t.Fatal("delivered non-main snapshot omitted", e, run.FetchedCount)
|
||||
}
|
||||
}
|
||||
@@ -188,6 +188,12 @@ var errGiteaNotFound = newGiteaError(KindNotFound, http.StatusNotFound, "版本
|
||||
|
||||
// ListCommits 读一页提交;同时返回 X-Total-Count(用于完整性对账,不做假 total)。
|
||||
func (c *GiteaClient) ListCommits(ctx context.Context, page, limit int) ([]RawCommit, int, error) {
|
||||
return c.ListCommitsAtRef(ctx, "main", page, limit)
|
||||
}
|
||||
func (c *GiteaClient) ListCommitsAtRef(ctx context.Context, ref string, page, limit int) ([]RawCommit, int, error) {
|
||||
if ref != "main" && !fullSHA.MatchString(ref) {
|
||||
return nil, 0, newGiteaError(KindParse, 0, "版本记录:只接受 main 或完整提交 SHA", nil)
|
||||
}
|
||||
if limit <= 0 || limit > giteaDefaultPageSize {
|
||||
limit = giteaDefaultPageSize
|
||||
}
|
||||
@@ -196,6 +202,7 @@ func (c *GiteaClient) ListCommits(ctx context.Context, page, limit int) ([]RawCo
|
||||
query.Set("page", fmt.Sprintf("%d", page))
|
||||
query.Set("stat", "false")
|
||||
query.Set("verification", "false")
|
||||
query.Set("sha", ref)
|
||||
body, header, err := c.get(ctx, c.apiURL("/commits", query))
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
@@ -322,7 +329,8 @@ func (c *GiteaClient) ListTags(ctx context.Context) ([]RawTag, error) {
|
||||
return nil, err
|
||||
}
|
||||
var annotated struct {
|
||||
Object struct {
|
||||
Message string `json:"message"`
|
||||
Object struct {
|
||||
SHA string `json:"sha"`
|
||||
} `json:"object"`
|
||||
}
|
||||
@@ -333,6 +341,7 @@ func (c *GiteaClient) ListTags(ctx context.Context) ([]RawTag, error) {
|
||||
continue
|
||||
}
|
||||
tag.TargetSHA = annotated.Object.SHA
|
||||
tag.Message = annotated.Message
|
||||
}
|
||||
tags = append(tags, tag)
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ package versionhistory
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
@@ -25,6 +26,7 @@ type RawCommit struct {
|
||||
|
||||
// RawTag 是一个 tag 及其可核验属性;Annotated=false 表示轻量 tag(不算正式版本的证据)。
|
||||
type RawTag struct {
|
||||
Message string
|
||||
Name string
|
||||
TagSHA string
|
||||
TargetSHA string
|
||||
@@ -36,13 +38,14 @@ type ChangelogSource func(sha string) (string, error)
|
||||
|
||||
// DeriveInput 是一次换算的全部输入。
|
||||
type DeriveInput struct {
|
||||
RepoKey string
|
||||
CommitURLBase string // 形如 "<origin>/<owner>/<repo>/commit/",由配置拼好,不接受外部传入
|
||||
TagURLBase string // 形如 "<origin>/<owner>/<repo>/src/tag/";空则不下发 tag 链接
|
||||
Commits []RawCommit
|
||||
Tags []RawTag
|
||||
Changelog ChangelogSource
|
||||
SnapshotID int64
|
||||
DeliveryArchive string
|
||||
RepoKey string
|
||||
CommitURLBase string // 形如 "<origin>/<owner>/<repo>/commit/",由配置拼好,不接受外部传入
|
||||
TagURLBase string // 形如 "<origin>/<owner>/<repo>/src/tag/";空则不下发 tag 链接
|
||||
Commits []RawCommit
|
||||
Tags []RawTag
|
||||
Changelog ChangelogSource
|
||||
SnapshotID int64
|
||||
}
|
||||
|
||||
// DeriveResult 是换算结果。
|
||||
@@ -192,6 +195,25 @@ func DeriveVersions(in DeriveInput) DeriveResult {
|
||||
}
|
||||
if kind == governance.RecordKindRelease {
|
||||
record.ReleaseNotes = governance.ExtractReleaseNotes(changelog, label)
|
||||
} else if kind == governance.RecordKindDevelopment {
|
||||
record.ReleaseNotes = governance.ExtractDevelopmentNotes(changelog, label)
|
||||
if record.ReleaseNotes == "" {
|
||||
archived := governance.ExtractDevelopmentNotes(in.DeliveryArchive, label)
|
||||
if strings.Contains(archived, "目标提交:"+commit.SHA) {
|
||||
record.ReleaseNotes = archived
|
||||
}
|
||||
}
|
||||
if record.ReleaseNotes == "" {
|
||||
for _, tag := range tagsByTarget[commit.SHA] {
|
||||
if tag.Annotated && tag.Name == "snapshot/v"+label {
|
||||
_, body, found := strings.Cut(tag.Message, "\n\n")
|
||||
if found {
|
||||
record.ReleaseNotes = strings.TrimSpace(body)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
records = append(records, record)
|
||||
}
|
||||
|
||||
@@ -130,22 +130,24 @@ type SyncOutcome struct {
|
||||
|
||||
// SyncerConfig 装配同步器。
|
||||
type SyncerConfig struct {
|
||||
Source Source
|
||||
Store SyncStore
|
||||
RepoKey string
|
||||
Changelog string // 提交内的变更记录文件路径,默认 CHANGELOG.md
|
||||
Now func() time.Time
|
||||
MaxPages int
|
||||
Source Source
|
||||
Store SyncStore
|
||||
RepoKey string
|
||||
Changelog string // 提交内的变更记录文件路径,默认 CHANGELOG.md
|
||||
Now func() time.Time
|
||||
MaxPages int
|
||||
TargetSHAs []string
|
||||
}
|
||||
|
||||
// Syncer 抓取远端 main 可达的全部提交并换算版本记录。
|
||||
type Syncer struct {
|
||||
source Source
|
||||
store SyncStore
|
||||
repoKey string
|
||||
changelog string
|
||||
now func() time.Time
|
||||
maxPages int
|
||||
source Source
|
||||
store SyncStore
|
||||
repoKey string
|
||||
changelog string
|
||||
now func() time.Time
|
||||
maxPages int
|
||||
targetSHAs []string
|
||||
}
|
||||
|
||||
const syncerDefaultMaxPages = 200
|
||||
@@ -170,7 +172,12 @@ func NewSyncer(config SyncerConfig) (*Syncer, error) {
|
||||
if maxPages <= 0 {
|
||||
maxPages = syncerDefaultMaxPages
|
||||
}
|
||||
return &Syncer{source: config.Source, store: config.Store, repoKey: config.RepoKey,
|
||||
for _, sha := range config.TargetSHAs {
|
||||
if !fullSHA.MatchString(sha) {
|
||||
return nil, errors.New("版本记录:运行身份必须是完整 SHA")
|
||||
}
|
||||
}
|
||||
return &Syncer{targetSHAs: append([]string{}, config.TargetSHAs...), source: config.Source, store: config.Store, repoKey: config.RepoKey,
|
||||
changelog: changelog, now: now, maxPages: maxPages}, nil
|
||||
}
|
||||
|
||||
@@ -204,9 +211,22 @@ func (s *Syncer) Sync(ctx context.Context, jobID, triggeredBy string) (governanc
|
||||
return fail(err)
|
||||
}
|
||||
|
||||
commits, err = s.includeDeliveredCommits(ctx, commits, tags)
|
||||
if err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
total = len(commits)
|
||||
deliveryArchive := ""
|
||||
if len(s.targetSHAs) > 0 {
|
||||
deliveryArchive, err = s.source.ReadFile(ctx, s.targetSHAs[0], s.changelog)
|
||||
if err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
}
|
||||
derived := DeriveVersions(DeriveInput{RepoKey: s.repoKey, CommitURLBase: s.source.CommitURLBase(),
|
||||
TagURLBase: s.source.TagURLBase(),
|
||||
Commits: commits, Tags: tags, SnapshotID: runID,
|
||||
TagURLBase: s.source.TagURLBase(),
|
||||
DeliveryArchive: deliveryArchive,
|
||||
Commits: commits, Tags: tags, SnapshotID: runID,
|
||||
Changelog: func(sha string) (string, error) {
|
||||
return s.source.ReadFile(ctx, sha, s.changelog)
|
||||
}})
|
||||
@@ -220,6 +240,9 @@ func (s *Syncer) Sync(ctx context.Context, jobID, triggeredBy string) (governanc
|
||||
} else {
|
||||
sourceHead = headSHA(commits) // 读分支失败不致命:退回提交列表最新一条
|
||||
}
|
||||
if len(s.targetSHAs) > 0 {
|
||||
sourceHead = s.targetSHAs[0]
|
||||
}
|
||||
outcome := SyncOutcome{SourceHeadSHA: sourceHead, FetchedCount: len(commits),
|
||||
ExpectedCount: total, Complete: derived.GraphComplete && (total == 0 || len(commits) == total)}
|
||||
if err := s.store.FinishVersionHistorySync(ctx, runID, outcome, s.now().UTC()); err != nil {
|
||||
@@ -232,6 +255,9 @@ func (s *Syncer) Sync(ctx context.Context, jobID, triggeredBy string) (governanc
|
||||
|
||||
// fetchAllCommits 逐页抓取并按 SHA 去重;短页即终止(也防住服务端忽略 page 参数)。
|
||||
func (s *Syncer) fetchAllCommits(ctx context.Context) ([]RawCommit, int, error) {
|
||||
return s.fetchCommitsAt(ctx, "")
|
||||
}
|
||||
func (s *Syncer) fetchCommitsAt(ctx context.Context, ref string) ([]RawCommit, int, error) {
|
||||
pageSize := s.source.PageSize()
|
||||
if pageSize <= 0 {
|
||||
pageSize = giteaDefaultPageSize
|
||||
@@ -240,7 +266,18 @@ func (s *Syncer) fetchAllCommits(ctx context.Context) ([]RawCommit, int, error)
|
||||
commits := make([]RawCommit, 0, pageSize)
|
||||
total := 0
|
||||
for page := 1; page <= s.maxPages; page++ {
|
||||
pageCommits, pageTotal, err := s.source.ListCommits(ctx, page, pageSize)
|
||||
var pageCommits []RawCommit
|
||||
var pageTotal int
|
||||
var err error
|
||||
if ref == "" {
|
||||
pageCommits, pageTotal, err = s.source.ListCommits(ctx, page, pageSize)
|
||||
} else if source, ok := s.source.(interface {
|
||||
ListCommitsAtRef(context.Context, string, int, int) ([]RawCommit, int, error)
|
||||
}); ok {
|
||||
pageCommits, pageTotal, err = source.ListCommitsAtRef(ctx, ref, page, pageSize)
|
||||
} else {
|
||||
return nil, 0, errors.New("版本来源不支持开发快照历史")
|
||||
}
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user