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 gr, err := git.PlainOpen(repoPath)
31 if err != nil {
32 writeError(w, xrpcerr.NewXrpcError(
33 xrpcerr.WithTag("RepoNotFound"),
34 xrpcerr.WithMessage("repository not found"),
35 ), http.StatusNotFound)
36 return
37 }
38
39 branches, _ := gr.Branches()
40
41 offset := 0
42 if cursor != "" {
43 if o, err := strconv.Atoi(cursor); err == nil && o >= 0 && o < len(branches) {
44 offset = o
45 }
46 }
47
48 end := offset + limit
49 if end > len(branches) {
50 end = len(branches)
51 }
52
53 paginatedBranches := branches[offset:end]
54
55 // Create response using existing types.RepoBranchesResponse
56 response := types.RepoBranchesResponse{
57 Branches: paginatedBranches,
58 }
59
60 // Write JSON response directly
61 w.Header().Set("Content-Type", "application/json")
62 if err := json.NewEncoder(w).Encode(response); err != nil {
63 x.Logger.Error("failed to encode response", "error", err)
64 writeError(w, xrpcerr.NewXrpcError(
65 xrpcerr.WithTag("InternalServerError"),
66 xrpcerr.WithMessage("failed to encode response"),
67 ), http.StatusInternalServerError)
68 return
69 }
70}