This repository has no description
0

Configure Feed

Select the types of activity you want to include in your feed.

core / appview / pulls / single.go
13 kB 433 lines
1package pulls 2 3import ( 4 "fmt" 5 "net/http" 6 "slices" 7 "strconv" 8 9 "tangled.org/core/api/tangled" 10 "tangled.org/core/appview/db" 11 "tangled.org/core/appview/models" 12 "tangled.org/core/appview/pages" 13 "tangled.org/core/appview/xrpcclient" 14 "tangled.org/core/orm" 15 "tangled.org/core/patchutil" 16 "tangled.org/core/types" 17 18 "github.com/bluesky-social/indigo/atproto/syntax" 19 indigoxrpc "github.com/bluesky-social/indigo/xrpc" 20 "github.com/go-chi/chi/v5" 21) 22 23// htmx fragment 24func (s *Pulls) PullActions(w http.ResponseWriter, r *http.Request) { 25 l := s.logger.With("handler", "PullActions") 26 27 switch r.Method { 28 case http.MethodGet: 29 user := s.oauth.GetMultiAccountUser(r) 30 if user != nil { 31 l = l.With("user", user.Did) 32 } 33 34 f, err := s.repoResolver.Resolve(r) 35 if err != nil { 36 l.Error("failed to get repo and knot", "err", err) 37 return 38 } 39 40 pull, ok := r.Context().Value("pull").(*models.Pull) 41 if !ok { 42 l.Error("failed to get pull") 43 s.pages.Notice(w, "pull-error", "Failed to edit patch. Try again later.") 44 return 45 } 46 l = l.With("pull_id", pull.PullId, "pull_owner", pull.OwnerDid) 47 48 // can be nil if this pull is not stacked 49 stack, _ := r.Context().Value("stack").(models.Stack) 50 51 roundNumberStr := chi.URLParam(r, "round") 52 roundNumber, err := strconv.Atoi(roundNumberStr) 53 if err != nil { 54 roundNumber = pull.LastRoundNumber() 55 } 56 if roundNumber >= len(pull.Submissions) { 57 http.Error(w, "bad round id", http.StatusBadRequest) 58 l.Error("failed to parse round id", "err", err, "round_number", roundNumber) 59 return 60 } 61 62 mergeCheckResponse := s.mergeCheck(r, f, pull, stack) 63 branchDeleteStatus := s.branchDeleteStatus(r, f, pull) 64 resubmitResult := pages.Unknown 65 if user.Did == pull.OwnerDid { 66 resubmitResult = s.resubmitCheck(r, f, pull, stack) 67 } 68 69 s.pages.PullActionsFragment(w, pages.PullActionsParams{ 70 LoggedInUser: user, 71 RepoInfo: s.repoResolver.GetRepoInfo(r, user), 72 Pull: pull, 73 RoundNumber: roundNumber, 74 MergeCheck: mergeCheckResponse, 75 ResubmitCheck: resubmitResult, 76 BranchDeleteStatus: branchDeleteStatus, 77 Stack: stack, 78 }) 79 return 80 } 81} 82 83func (s *Pulls) repoPullHelper(w http.ResponseWriter, r *http.Request, interdiff bool) { 84 l := s.logger.With("handler", "repoPullHelper", "interdiff", interdiff) 85 86 user := s.oauth.GetMultiAccountUser(r) 87 if user != nil { 88 l = l.With("user", user.Did) 89 } 90 91 f, err := s.repoResolver.Resolve(r) 92 if err != nil { 93 l.Error("failed to get repo and knot", "err", err) 94 return 95 } 96 97 pull, ok := r.Context().Value("pull").(*models.Pull) 98 if !ok { 99 l.Error("failed to get pull") 100 s.pages.Notice(w, "pull-error", "Failed to edit patch. Try again later.") 101 return 102 } 103 l = l.With("pull_id", pull.PullId, "pull_owner", pull.OwnerDid) 104 105 backlinks, err := db.GetBacklinks(s.db, pull.AtUri()) 106 if err != nil { 107 l.Error("failed to get pull backlinks", "err", err) 108 s.pages.Notice(w, "pull-error", "Failed to get pull. Try again later.") 109 return 110 } 111 112 roundId := chi.URLParam(r, "round") 113 roundIdInt := pull.LastRoundNumber() 114 if r, err := strconv.Atoi(roundId); err == nil { 115 roundIdInt = r 116 } 117 if roundIdInt >= len(pull.Submissions) { 118 http.Error(w, "bad round id", http.StatusBadRequest) 119 l.Error("failed to parse round id", "err", err, "round_number", roundIdInt) 120 return 121 } 122 123 var diffOpts types.DiffOpts 124 if d := r.URL.Query().Get("diff"); d == "split" { 125 diffOpts.Split = true 126 } 127 128 // can be nil if this pull is not stacked 129 stack, _ := r.Context().Value("stack").(models.Stack) 130 131 mergeCheckResponse := s.mergeCheck(r, f, pull, stack) 132 branchDeleteStatus := s.branchDeleteStatus(r, f, pull) 133 resubmitResult := pages.Unknown 134 if user != nil && user.Did == pull.OwnerDid { 135 resubmitResult = s.resubmitCheck(r, f, pull, stack) 136 } 137 138 m := make(map[string]models.Pipeline) 139 140 var shas []string 141 for _, s := range pull.Submissions { 142 shas = append(shas, s.SourceRev) 143 } 144 for _, p := range stack { 145 shas = append(shas, p.LatestSha()) 146 } 147 148 ps, err := db.GetPipelineStatuses( 149 s.db, 150 len(shas), 151 orm.FilterEq("p.repo_did", f.RepoDid), 152 orm.FilterIn("p.sha", shas), 153 ) 154 if err != nil { 155 l.Error("failed to fetch pipeline statuses", "err", err) 156 // non-fatal 157 } 158 159 for _, p := range ps { 160 m[p.Sha] = p 161 } 162 163 entities := []syntax.ATURI{pull.AtUri()} 164 reactions, err := db.ListReactionDisplayDataMap(s.db, entities, 20) 165 if err != nil { 166 l.Error("failed to get pull reactions", "err", err) 167 } 168 169 var userReactions map[syntax.ATURI]map[models.ReactionKind]bool 170 if user != nil { 171 userReactions, err = db.ListReactionStatusMap(s.db, entities, syntax.DID(user.Did)) 172 if err != nil { 173 s.logger.Error("failed to get user reactions", "err", err) 174 } 175 } 176 177 labelDefs, err := db.GetLabelDefinitions( 178 s.db, 179 orm.FilterIn("at_uri", f.Labels), 180 orm.FilterContains("scope", tangled.RepoPullNSID), 181 ) 182 if err != nil { 183 l.Error("failed to fetch labels", "err", err) 184 s.pages.Error503(w) 185 return 186 } 187 188 defs := make(map[string]*models.LabelDefinition) 189 for _, l := range labelDefs { 190 defs[l.AtUri().String()] = &l 191 } 192 193 vouchRelationships := make(map[syntax.DID]*models.VouchRelationship) 194 vouchSkips := make(map[syntax.DID]bool) 195 if user != nil { 196 participants := pull.Participants() 197 vouchRelationships, err = db.GetVouchRelationshipsBatch(s.db, syntax.DID(user.Did), participants) 198 if err != nil { 199 l.Error("failed to fetch vouch relationships", "err", err) 200 } 201 ownerDid := syntax.DID(pull.OwnerDid) 202 skipped, err := db.IsVouchSkipped(s.db, user.Did, pull.OwnerDid) 203 if err != nil { 204 l.Error("failed to check vouch skip", "err", err) 205 } 206 vouchSkips[ownerDid] = skipped 207 } 208 209 patch := pull.Submissions[roundIdInt].CombinedPatch() 210 var diff types.DiffRenderer 211 diff = patchutil.AsNiceDiff(patch, pull.TargetBranch) 212 213 if interdiff { 214 currentPatch, err := patchutil.AsDiff(pull.Submissions[roundIdInt].CombinedPatch()) 215 if err != nil { 216 l.Error("failed to interdiff; current patch malformed", "err", err, "round_number", roundIdInt) 217 s.pages.Notice(w, fmt.Sprintf("interdiff-error-%d", roundIdInt), "Failed to calculate interdiff; current patch is invalid.") 218 return 219 } 220 221 previousPatch, err := patchutil.AsDiff(pull.Submissions[roundIdInt-1].CombinedPatch()) 222 if err != nil { 223 l.Error("failed to interdiff; previous patch malformed", "err", err, "round_number", roundIdInt) 224 s.pages.Notice(w, fmt.Sprintf("interdiff-error-%d", roundIdInt), "Failed to calculate interdiff; previous patch is invalid.") 225 return 226 } 227 228 diff = patchutil.Interdiff(previousPatch, currentPatch) 229 } 230 231 err = s.pages.RepoSinglePull(w, pages.RepoSinglePullParams{ 232 LoggedInUser: user, 233 RepoInfo: s.repoResolver.GetRepoInfo(r, user), 234 Pull: pull, 235 Stack: stack, 236 Backlinks: backlinks, 237 BranchDeleteStatus: branchDeleteStatus, 238 MergeCheck: mergeCheckResponse, 239 ResubmitCheck: resubmitResult, 240 Pipelines: m, 241 Diff: diff, 242 DiffOpts: diffOpts, 243 ActiveRound: roundIdInt, 244 IsInterdiff: interdiff, 245 246 Reactions: reactions, 247 UserReacted: userReactions, 248 249 LabelDefs: defs, 250 VouchRelationships: vouchRelationships, 251 VouchSkips: vouchSkips, 252 }) 253 if err != nil { 254 l.Error("failed to render page", "err", err) 255 } 256} 257 258func (s *Pulls) RepoSinglePull(w http.ResponseWriter, r *http.Request) { 259 l := s.logger.With("handler", "RepoSinglePull") 260 261 pull, ok := r.Context().Value("pull").(*models.Pull) 262 if !ok { 263 l.Error("failed to get pull") 264 s.pages.Notice(w, "pull-error", "Failed to edit patch. Try again later.") 265 return 266 } 267 268 http.Redirect(w, r, r.URL.String()+fmt.Sprintf("/round/%d", pull.LastRoundNumber()), http.StatusFound) 269} 270 271func (s *Pulls) mergeCheck(r *http.Request, f *models.Repo, pull *models.Pull, stack models.Stack) types.MergeCheckResponse { 272 if pull.State == models.PullMerged { 273 return types.MergeCheckResponse{} 274 } 275 276 xrpcc := s.knotClient(f.Knot) 277 278 // combine patches of substack 279 subStack := stack.Below(pull) 280 // collect the portion of the stack that is mergeable 281 mergeable := subStack.Mergeable() 282 // combine each patch 283 patch := mergeable.CombinedPatch() 284 285 resp, err := tangled.RepoMergeCheck( 286 r.Context(), 287 xrpcc, 288 &tangled.RepoMergeCheck_Input{ 289 Did: f.Did, 290 Name: f.Name, 291 Branch: pull.TargetBranch, 292 Patch: patch, 293 }, 294 ) 295 if xrpcerr := xrpcclient.HandleXrpcErr(err); xrpcerr != nil { 296 s.logger.Error("failed to check for mergeability", "xrpcerr", xrpcerr, "err", err, "pull_id", pull.PullId, "target_branch", pull.TargetBranch) 297 return types.MergeCheckResponse{ 298 Error: fmt.Sprintf("failed to check merge status: %s", xrpcerr.Error()), 299 } 300 } 301 302 return mergeCheckResponseFrom(resp) 303} 304 305func mergeCheckResponseFrom(resp *tangled.RepoMergeCheck_Output) types.MergeCheckResponse { 306 conflicts := make([]types.ConflictInfo, len(resp.Conflicts)) 307 for i, c := range resp.Conflicts { 308 conflicts[i] = types.ConflictInfo{Filename: c.Filename, Reason: c.Reason} 309 } 310 out := types.MergeCheckResponse{ 311 IsConflicted: resp.Is_conflicted, 312 Conflicts: conflicts, 313 } 314 if resp.Message != nil { 315 out.Message = *resp.Message 316 } 317 if resp.Error != nil { 318 out.Error = *resp.Error 319 } 320 return out 321} 322 323func (s *Pulls) branchDeleteStatus(r *http.Request, repo *models.Repo, pull *models.Pull) *models.BranchDeleteStatus { 324 if pull.State != models.PullMerged { 325 return nil 326 } 327 328 user := s.oauth.GetMultiAccountUser(r) 329 if user == nil { 330 return nil 331 } 332 333 var branch string 334 // check if the branch exists 335 // NOTE: appview could cache branches/tags etc. for every repo by listening for gitRefUpdates 336 if pull.IsBranchBased() { 337 branch = pull.PullSource.Branch 338 } else if pull.IsForkBased() { 339 branch = pull.PullSource.Branch 340 repo = pull.PullSource.Repo 341 } else { 342 return nil 343 } 344 345 // deleted fork 346 if repo == nil { 347 return nil 348 } 349 350 // user can only delete branch if they are a collaborator in the repo that the branch belongs to 351 perms := s.enforcer.GetPermissionsInRepo(user.Did, repo.Knot, repo.RepoIdentifier()) 352 if !slices.Contains(perms, "repo:push") { 353 return nil 354 } 355 356 xrpcc := &indigoxrpc.Client{Host: s.config.KnotMirror.Url} 357 resp, err := tangled.GitTempGetBranch(r.Context(), xrpcc, branch, repo.RepoDid) 358 if xrpcerr := xrpcclient.HandleXrpcErr(err); xrpcerr != nil { 359 s.logger.Error("failed to get branch", "xrpcerr", xrpcerr, "err", err) 360 return nil 361 } 362 363 return &models.BranchDeleteStatus{ 364 Repo: repo, 365 Branch: resp.Name, 366 } 367} 368 369func (s *Pulls) resubmitCheck(r *http.Request, repo *models.Repo, pull *models.Pull, stack models.Stack) pages.ResubmitResult { 370 if pull.State == models.PullMerged || pull.State == models.PullAbandoned || pull.PullSource == nil { 371 return pages.Unknown 372 } 373 374 var sourceRepoDid string 375 if pull.PullSource.RepoDid != nil { 376 sourceRepoDid = string(*pull.PullSource.RepoDid) 377 } else { 378 sourceRepoDid = repo.RepoDid 379 } 380 381 xrpcc := &indigoxrpc.Client{Host: s.config.KnotMirror.Url} 382 branchResp, err := tangled.GitTempGetBranch(r.Context(), xrpcc, pull.PullSource.Branch, sourceRepoDid) 383 if err != nil { 384 if xrpcerr := xrpcclient.HandleXrpcErr(err); xrpcerr != nil { 385 s.logger.Error("failed to call XRPC repo.branches", "xrpcerr", xrpcerr, "err", err, "pull_id", pull.PullId, "branch", pull.PullSource.Branch) 386 return pages.Unknown 387 } 388 s.logger.Error("failed to reach knotserver", "err", err, "pull_id", pull.PullId) 389 return pages.Unknown 390 } 391 392 targetBranch := branchResp 393 394 top := stack[0] 395 latestSourceRev := top.LatestSha() 396 397 if latestSourceRev != targetBranch.Hash { 398 return pages.ShouldResubmit 399 } 400 401 return pages.ShouldNotResubmit 402} 403 404func (s *Pulls) RepoPullPatch(w http.ResponseWriter, r *http.Request) { 405 s.repoPullHelper(w, r, false) 406} 407 408func (s *Pulls) RepoPullInterdiff(w http.ResponseWriter, r *http.Request) { 409 s.repoPullHelper(w, r, true) 410} 411 412func (s *Pulls) RepoPullPatchRaw(w http.ResponseWriter, r *http.Request) { 413 l := s.logger.With("handler", "RepoPullPatchRaw") 414 415 pull, ok := r.Context().Value("pull").(*models.Pull) 416 if !ok { 417 l.Error("failed to get pull") 418 s.pages.Notice(w, "pull-error", "Failed to edit patch. Try again later.") 419 return 420 } 421 l = l.With("pull_id", pull.PullId) 422 423 roundId := chi.URLParam(r, "round") 424 roundIdInt, err := strconv.Atoi(roundId) 425 if err != nil || roundIdInt >= len(pull.Submissions) { 426 http.Error(w, "bad round id", http.StatusBadRequest) 427 l.Error("failed to parse round id", "err", err, "round_id_str", roundId) 428 return 429 } 430 431 w.Header().Set("Content-Type", "text/plain; charset=utf-8") 432 w.Write([]byte(pull.Submissions[roundIdInt].Patch)) 433}