This repository has no description
1package repo
2
3import (
4 "errors"
5 "fmt"
6 "maps"
7 "net/http"
8 "net/url"
9 "slices"
10 "sort"
11 "strings"
12 "sync"
13 "time"
14
15 "context"
16 "encoding/json"
17
18 "github.com/bluesky-social/indigo/atproto/syntax"
19 indigoxrpc "github.com/bluesky-social/indigo/xrpc"
20 "github.com/go-git/go-git/v5/plumbing"
21 "tangled.org/core/api/tangled"
22 "tangled.org/core/appview/commitverify"
23 "tangled.org/core/appview/db"
24 "tangled.org/core/appview/models"
25 "tangled.org/core/appview/pages"
26 "tangled.org/core/appview/pages/markup"
27 "tangled.org/core/types"
28
29 "github.com/go-chi/chi/v5"
30 "github.com/go-enry/go-enry/v2"
31 "github.com/samber/lo"
32)
33
34func (rp *Repo) Index(w http.ResponseWriter, r *http.Request) {
35 l := rp.logger.With("handler", "RepoIndex")
36
37 ref := chi.URLParam(r, "ref")
38 ref, _ = url.PathUnescape(ref)
39
40 f, err := rp.repoResolver.Resolve(r)
41 if err != nil {
42 l.Error("failed to fully resolve repo", "err", err)
43 return
44 }
45
46 user := rp.oauth.GetMultiAccountUser(r)
47
48 if user != nil {
49 userDid := user.Did
50 repoDid := f.RepoDid
51 go func() {
52 if err := db.UpsertRecentLink(rp.db, userDid, models.RecentLinkTypeRepo, repoDid); err != nil {
53 l.Error("failed to upsert recent link", "err", err)
54 }
55 }()
56 }
57
58 // Build index response from multiple XRPC calls
59 result, err := rp.buildIndexResponse(r.Context(), f, ref)
60 if err != nil {
61 l.Error("failed to build index response", "err", err)
62 rp.pages.RepoIndexPage(w, pages.RepoIndexParams{
63 BaseParams: pages.BaseParamsFromContext(r.Context()),
64 KnotUnreachable: true,
65 RepoInfo: rp.repoResolver.GetRepoInfo(r, user),
66 })
67 return
68 }
69
70 tagMap := make(map[string][]string)
71 for _, tag := range result.Tags {
72 hash := tag.Hash
73 if tag.Tag != nil {
74 hash = tag.Tag.Target.String()
75 }
76 tagMap[hash] = append(tagMap[hash], tag.Name)
77 }
78
79 for _, branch := range result.Branches {
80 hash := branch.Hash
81 tagMap[hash] = append(tagMap[hash], branch.Name)
82 }
83
84 sortFiles(result.Files)
85
86 slices.SortFunc(result.Branches, func(a, b types.Branch) int {
87 if a.Name == result.Ref {
88 return -1
89 }
90 if a.IsDefault {
91 return -1
92 }
93 if b.IsDefault {
94 return 1
95 }
96 if a.Commit != nil && b.Commit != nil {
97 if a.Commit.Committer.When.Before(b.Commit.Committer.When) {
98 return 1
99 } else {
100 return -1
101 }
102 }
103 return strings.Compare(a.Name, b.Name) * -1
104 })
105
106 commitCount := len(result.Commits)
107 branchCount := len(result.Branches)
108 tagCount := len(result.Tags)
109 fileCount := len(result.Files)
110
111 commitCount, branchCount, tagCount = balanceIndexItems(commitCount, branchCount, tagCount, fileCount)
112 commitsTrunc := result.Commits[:min(commitCount, len(result.Commits))]
113 tagsTrunc := result.Tags[:min(tagCount, len(result.Tags))]
114 branchesTrunc := result.Branches[:min(branchCount, len(result.Branches))]
115
116 var shas []string
117 for _, c := range commitsTrunc {
118 shas = append(shas, c.Hash.String())
119 }
120 type pipelineResult struct {
121 pipelines map[string]types.Pipeline
122 err error
123 }
124 pipelineCh := make(chan pipelineResult, 1)
125 go func() {
126 p, err := getPipelineStatuses(r.Context(), f, shas)
127 pipelineCh <- pipelineResult{p, err}
128 }()
129
130 emails := uniqueEmails(commitsTrunc)
131 emailToDidMap, err := db.GetEmailToDid(rp.db, emails, true)
132 if err != nil {
133 l.Error("failed to get email to did map", "err", err)
134 }
135
136 vc, err := commitverify.GetVerifiedCommits(rp.db, emailToDidMap, commitsTrunc)
137 if err != nil {
138 l.Error("failed to GetVerifiedObjectCommits", "err", err)
139 }
140
141 var languageInfo []types.RepoLanguageDetails
142 if !result.IsEmpty {
143 langs, err := rp.getLanguageInfo(r.Context(), syntax.DID(f.RepoDid), result.Ref)
144 if err != nil {
145 l.Warn("failed to compute language percentages", "err", err)
146 // non-fatal
147 } else if ref == "" { // when request didn't specified ref, we are fetching default branch.
148 if err := func(repo syntax.DID, ref string, langs []*tangled.GitTempListLanguages_Language) error {
149 current := lo.SliceToMap(langs, func(lang *tangled.GitTempListLanguages_Language) (string, int64) {
150 return lang.Name, lang.Size
151 })
152
153 existing, err := db.GetRepoLanguages(rp.db, repo, ref)
154 if err != nil {
155 return err
156 }
157 if maps.Equal(current, existing) {
158 return nil
159 }
160
161 tx, err := rp.db.Begin()
162 if err != nil {
163 return err
164 }
165 defer tx.Rollback()
166
167 mlangs := lo.Map(langs, func(lang *tangled.GitTempListLanguages_Language, _ int) models.RepoLanguage {
168 return models.RepoLanguage{
169 RepoDid: repo,
170 Ref: ref,
171 IsDefaultRef: true,
172 Language: lang.Name,
173 Bytes: lang.Size,
174 }
175 })
176
177 if err := db.UpdateRepoLanguages(tx, repo, ref, mlangs); err != nil {
178 return err
179 }
180
181 return tx.Commit()
182 }(syntax.DID(f.RepoDid), result.Ref, langs); err != nil {
183 l.Error("failed to populate appview repo languages index", "err", err)
184 // non-fatal
185 }
186 languageInfo = makeLanguageStats(langs)
187 }
188 }
189
190 pr := <-pipelineCh
191 if pr.err != nil {
192 l.Error("failed to fetch pipeline statuses", "err", pr.err)
193 // non-fatal
194 }
195 pipelines := pr.pipelines
196
197 rp.pages.RepoIndexPage(w, pages.RepoIndexParams{
198 BaseParams: pages.BaseParamsFromContext(r.Context()),
199 RepoInfo: rp.repoResolver.GetRepoInfo(r, user),
200 TagMap: tagMap,
201 RepoIndexResponse: *result,
202 CommitsTrunc: commitsTrunc,
203 TagsTrunc: tagsTrunc,
204 // ForkInfo: forkInfo, // TODO: reinstate this after xrpc properly lands
205 BranchesTrunc: branchesTrunc,
206 EmailToDid: emailToDidMap,
207 VerifiedCommits: vc,
208 Languages: languageInfo,
209 Pipelines: pipelines,
210 })
211}
212
213func (rp *Repo) getLanguageInfo(
214 ctx context.Context,
215 repoId syntax.DID,
216 ref string,
217) ([]*tangled.GitTempListLanguages_Language, error) {
218 // non-fatal, fetch langs from knotmirror via XRPC
219 xrpcc := &indigoxrpc.Client{
220 Host: rp.config.KnotMirror.Url,
221 Client: http.DefaultClient,
222 }
223 out, err := tangled.GitTempListLanguages(ctx, xrpcc, ref, repoId.String())
224 if err != nil {
225 return nil, fmt.Errorf("calling knotmirror git.listLanguages: %w", err)
226 }
227
228 if out == nil || out.Languages == nil {
229 return nil, nil
230 }
231
232 return out.Languages, nil
233}
234
235func makeLanguageStats(langs []*tangled.GitTempListLanguages_Language) []types.RepoLanguageDetails {
236 if len(langs) == 0 {
237 return nil
238 }
239 var total int64
240 for _, lang := range langs {
241 total += lang.Size
242 }
243
244 var languageStats []types.RepoLanguageDetails
245 for _, l := range langs {
246 languageStats = append(languageStats, types.RepoLanguageDetails{
247 Name: l.Name,
248 Color: enry.GetColor(l.Name),
249 Percentage: float32(l.Size) / float32(total) * 100,
250 })
251 }
252
253 sort.Slice(languageStats, func(i, j int) bool {
254 if languageStats[i].Name == enry.OtherLanguage {
255 return false
256 }
257 if languageStats[j].Name == enry.OtherLanguage {
258 return true
259 }
260 if languageStats[i].Percentage != languageStats[j].Percentage {
261 return languageStats[i].Percentage > languageStats[j].Percentage
262 }
263 return languageStats[i].Name < languageStats[j].Name
264 })
265 return languageStats
266}
267
268// buildIndexResponse creates a RepoIndexResponse by combining multiple xrpc calls in parallel
269func (rp *Repo) buildIndexResponse(ctx context.Context, repo *models.Repo, ref string) (*types.RepoIndexResponse, error) {
270 xrpcc := &indigoxrpc.Client{Host: rp.config.KnotMirror.Url}
271
272 branchesBytes, err := tangled.GitTempListBranches(ctx, xrpcc, "", 0, repo.RepoDid)
273 if err != nil {
274 return nil, fmt.Errorf("calling knotmirror git.listBranches: %w", err)
275 }
276
277 var branchesResp types.RepoBranchesResponse
278 if err := json.Unmarshal(branchesBytes, &branchesResp); err != nil {
279 return nil, fmt.Errorf("failed to unmarshal branches response: %w", err)
280 }
281
282 // if no ref specified, use default branch or first available
283 if ref == "" {
284 for _, branch := range branchesResp.Branches {
285 if branch.IsDefault {
286 ref = branch.Name
287 break
288 }
289 }
290 }
291
292 // if ref is still empty, this means the default branch is not set
293 if ref == "" {
294 return &types.RepoIndexResponse{
295 IsEmpty: true,
296 Branches: branchesResp.Branches,
297 }, nil
298 }
299
300 // now run the remaining queries in parallel
301 var wg sync.WaitGroup
302 var errs error
303
304 var (
305 tagsResp types.RepoTagsResponse
306 treeResp *tangled.GitTempGetTree_Output
307 logResp types.RepoLogResponse
308 readmeContent string
309 readmeFileName string
310 )
311
312 // tags
313 wg.Go(func() {
314 tagsBytes, err := tangled.GitTempListTags(ctx, xrpcc, "", 0, repo.RepoDid)
315 if err != nil {
316 errs = errors.Join(errs, fmt.Errorf("failed to call git.ListTags: %w", err))
317 return
318 }
319
320 if err := json.Unmarshal(tagsBytes, &tagsResp); err != nil {
321 errs = errors.Join(errs, fmt.Errorf("failed to unmarshal git.ListTags: %w", err))
322 }
323 })
324
325 // tree/files
326 wg.Go(func() {
327 resp, err := tangled.GitTempGetTree(ctx, xrpcc, "", ref, repo.RepoDid)
328 if err != nil {
329 errs = errors.Join(errs, fmt.Errorf("failed to call git.GetTree: %w", err))
330 return
331 }
332 treeResp = resp
333
334 for _, file := range resp.Files {
335 if markup.IsReadmeFile(file.Name, file.Mode) {
336 readmeFileName = file.Name
337 break
338 }
339 }
340
341 if readmeFileName != "" {
342 bytes, err := tangled.GitTempGetBlob(ctx, xrpcc, readmeFileName, ref, repo.RepoDid)
343 if err != nil {
344 errs = errors.Join(errs, fmt.Errorf("failed to call git.getBlob: %w", err))
345 return
346 }
347 readmeContent = string(bytes)
348 }
349 })
350
351 // commits
352 wg.Go(func() {
353 logBytes, err := tangled.GitTempListCommits(ctx, xrpcc, "", 50, ref, repo.RepoDid)
354 if err != nil {
355 errs = errors.Join(errs, fmt.Errorf("failed to call git.ListCommits: %w", err))
356 return
357 }
358
359 if err := json.Unmarshal(logBytes, &logResp); err != nil {
360 errs = errors.Join(errs, fmt.Errorf("failed to unmarshal git.ListCommits: %w", err))
361 }
362 })
363
364 wg.Wait()
365
366 if errs != nil {
367 return nil, errs
368 }
369
370 var files []types.NiceTree
371 if treeResp != nil && treeResp.Files != nil {
372 for _, file := range treeResp.Files {
373 niceFile := types.NiceTree{
374 Name: file.Name,
375 Mode: file.Mode,
376 Size: file.Size,
377 }
378
379 if file.Last_commit != nil {
380 when, _ := time.Parse(time.RFC3339, file.Last_commit.When)
381 niceFile.LastCommit = &types.LastCommitInfo{
382 Hash: plumbing.NewHash(file.Last_commit.Hash),
383 Message: file.Last_commit.Message,
384 When: when,
385 }
386 }
387 files = append(files, niceFile)
388 }
389 }
390
391 result := &types.RepoIndexResponse{
392 IsEmpty: false,
393 Ref: ref,
394 Readme: readmeContent,
395 ReadmeFileName: readmeFileName,
396 Commits: logResp.Commits,
397 Files: files,
398 Branches: branchesResp.Branches,
399 Tags: tagsResp.Tags,
400 TotalCommits: logResp.Total,
401 }
402
403 return result, nil
404}