1package xrpc
2
3import (
4 "encoding/json"
5 "net/http"
6 "strconv"
7
8 "tangled.sh/tangled.sh/core/knotserver/git"
9 "tangled.sh/tangled.sh/core/types"
10 xrpcerr "tangled.sh/tangled.sh/core/xrpc/errors"
11)
12
13func (x *Xrpc) RepoBranches(w http.ResponseWriter, r *http.Request) {
14 repo := r.URL.Query().Get("repo")
15 repoPath, err := x.parseRepoParam(repo)
16 if err != nil {
17 writeError(w, err.(xrpcerr.XrpcError), http.StatusBadRequest)
18 return
19 }
20
21 cursor := r.URL.Query().Get("cursor")
22
23 // limit := 50 // default
24 // if limitStr := r.URL.Query().Get("limit"); limitStr != "" {
25 // if l, err := strconv.Atoi(limitStr); err == nil && l > 0 && l <= 100 {
26 // limit = l
27 // }
28 // }
29
30 limit := 500
31
32 gr, err := git.PlainOpen(repoPath)
33 if err != nil {
34 writeError(w, xrpcerr.NewXrpcError(
35 xrpcerr.WithTag("RepoNotFound"),
36 xrpcerr.WithMessage("repository not found"),
37 ), http.StatusNotFound)
38 return
39 }
40
41 branches, _ := gr.Branches()
42
43 offset := 0
44 if cursor != "" {
45 if o, err := strconv.Atoi(cursor); err == nil && o >= 0 && o < len(branches) {
46 offset = o
47 }
48 }
49
50 end := offset + limit
51 if end > len(branches) {
52 end = len(branches)
53 }
54
55 paginatedBranches := branches[offset:end]
56
57 // Create response using existing types.RepoBranchesResponse
58 response := types.RepoBranchesResponse{
59 Branches: paginatedBranches,
60 }
61
62 // Write JSON response directly
63 w.Header().Set("Content-Type", "application/json")
64 if err := json.NewEncoder(w).Encode(response); err != nil {
65 x.Logger.Error("failed to encode response", "error", err)
66 writeError(w, xrpcerr.NewXrpcError(
67 xrpcerr.WithTag("InternalServerError"),
68 xrpcerr.WithMessage("failed to encode response"),
69 ), http.StatusInternalServerError)
70 return
71 }
72}