1package webhook
2
3import (
4 "context"
5
6 "github.com/charmbracelet/soft-serve/pkg/config"
7 "github.com/charmbracelet/soft-serve/pkg/db"
8 "github.com/charmbracelet/soft-serve/pkg/proto"
9 "github.com/charmbracelet/soft-serve/pkg/store"
10)
11
12// RepositoryEvent is a repository payload.
13type RepositoryEvent struct {
14 Common
15
16 // Action is the repository event action.
17 Action RepositoryEventAction `json:"action" url:"action"`
18}
19
20// RepositoryEventAction is a repository event action.
21type RepositoryEventAction string
22
23const (
24 // RepositoryEventActionDelete is a repository deleted event.
25 RepositoryEventActionDelete RepositoryEventAction = "delete"
26 // RepositoryEventActionRename is a repository renamed event.
27 RepositoryEventActionRename RepositoryEventAction = "rename"
28 // RepositoryEventActionVisibilityChange is a repository visibility changed event.
29 RepositoryEventActionVisibilityChange RepositoryEventAction = "visibility_change"
30 // RepositoryEventActionDefaultBranchChange is a repository default branch changed event.
31 RepositoryEventActionDefaultBranchChange RepositoryEventAction = "default_branch_change"
32)
33
34// NewRepositoryEvent sends a repository event.
35func NewRepositoryEvent(ctx context.Context, user proto.User, repo proto.Repository, action RepositoryEventAction) (RepositoryEvent, error) {
36 var event Event
37 switch action { //nolint:exhaustive
38 case RepositoryEventActionVisibilityChange:
39 event = EventRepositoryVisibilityChange
40 default:
41 event = EventRepository
42 }
43
44 payload := RepositoryEvent{
45 Action: action,
46 Common: Common{
47 EventType: event,
48 Repository: Repository{
49 ID: repo.ID(),
50 Name: repo.Name(),
51 Description: repo.Description(),
52 ProjectName: repo.ProjectName(),
53 Private: repo.IsPrivate(),
54 CreatedAt: repo.CreatedAt(),
55 UpdatedAt: repo.UpdatedAt(),
56 },
57 Sender: User{
58 ID: user.ID(),
59 Username: user.Username(),
60 },
61 },
62 }
63
64 cfg := config.FromContext(ctx)
65 payload.Repository.HTTPURL = repoURL(cfg.HTTP.PublicURL, repo.Name())
66 payload.Repository.SSHURL = repoURL(cfg.SSH.PublicURL, repo.Name())
67 payload.Repository.GitURL = repoURL(cfg.Git.PublicURL, repo.Name())
68
69 // Find repo owner.
70 dbx := db.FromContext(ctx)
71 datastore := store.FromContext(ctx)
72 owner, err := datastore.GetUserByID(ctx, dbx, repo.UserID())
73 if err != nil {
74 return RepositoryEvent{}, db.WrapError(err) //nolint:wrapcheck
75 }
76
77 payload.Repository.Owner.ID = owner.ID
78 payload.Repository.Owner.Username = owner.Username
79 payload.Repository.DefaultBranch, _ = getDefaultBranch(repo)
80
81 return payload, nil
82}