v0.24.0 166837a

convert.go RawHistoryFolder

1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package rpc
4
5import (
6	"encoding/base64"
7	"fmt"
8	"slices"
9	"time"
10
11	"google.golang.org/protobuf/types/known/timestamppb"
12
13	pb "bnema.dev/ermite-api/gen/ermite"
14	"bnema.dev/ermite/internal/domain"
15	"bnema.dev/ermite/internal/ports"
16)
17
18// This file maps domain values to the messages of the contract and back.
19// Messages are DTOs: the domain never leaks into them, nor they into the
20// domain.
21
22func timestamp(t time.Time) *timestamppb.Timestamp {
23	if t.IsZero() {
24		return nil
25	}
26	return timestamppb.New(t)
27}
28
29func goTime(ts *timestamppb.Timestamp) time.Time {
30	if ts == nil {
31		return time.Time{}
32	}
33	return ts.AsTime()
34}
35
36func visibilityToPB(v domain.Visibility) pb.Visibility {
37	switch v {
38	case domain.VisibilityPublic:
39		return pb.Visibility_VISIBILITY_PUBLIC
40	case domain.VisibilityPrivate:
41		return pb.Visibility_VISIBILITY_PRIVATE
42	}
43	return pb.Visibility_VISIBILITY_UNSPECIFIED
44}
45
46// visibilityFromPB maps a visibility of a request. Unspecified is the empty
47// domain.Visibility, which the use cases treat as "default".
48func visibilityFromPB(v pb.Visibility) (domain.Visibility, error) {
49	switch v {
50	case pb.Visibility_VISIBILITY_UNSPECIFIED:
51		return "", nil
52	case pb.Visibility_VISIBILITY_PUBLIC:
53		return domain.VisibilityPublic, nil
54	case pb.Visibility_VISIBILITY_PRIVATE:
55		return domain.VisibilityPrivate, nil
56	}
57	return "", fmt.Errorf("%w: %v", domain.ErrInvalidVisibility, v)
58}
59
60func repoToPB(v ports.RepoView) *pb.Repo {
61	settings := v.Settings
62	if settings.IsZero() {
63		settings = domain.DefaultRepoSettings()
64	}
65	return &pb.Repo{
66		Name:          v.Name.String(),
67		Description:   v.Description,
68		Topics:        v.Topics,
69		Visibility:    visibilityToPB(v.Visibility),
70		DefaultBranch: v.DefaultBranch,
71		CreatedAt:     timestamp(v.CreatedAt),
72		PushedAt:      timestamp(v.PushedAt),
73		Settings:      settingsToPB(settings),
74	}
75}
76
77func settingsToPB(s domain.RepoSettings) *pb.RepoSettings {
78	out := &pb.RepoSettings{FailingChecksBlock: s.FailingChecksBlock}
79	for _, m := range s.AllowedMergeModes {
80		out.AllowedMergeModes = append(out.AllowedMergeModes, mergeModeToPB(m))
81	}
82	return out
83}
84
85func mergeModeToPB(m domain.MergeMode) pb.MergeMode {
86	switch m {
87	case domain.MergeModeFastForward:
88		return pb.MergeMode_MERGE_MODE_FAST_FORWARD
89	case domain.MergeModeSquash:
90		return pb.MergeMode_MERGE_MODE_SQUASH
91	}
92	return pb.MergeMode_MERGE_MODE_UNSPECIFIED
93}
94
95// mergeModeFromPB maps a mode of a merge request: unspecified is the empty
96// domain.MergeMode, which the use case reads as fast-forward.
97func mergeModeFromPB(m pb.MergeMode) (domain.MergeMode, error) {
98	switch m {
99	case pb.MergeMode_MERGE_MODE_UNSPECIFIED:
100		return "", nil
101	case pb.MergeMode_MERGE_MODE_FAST_FORWARD:
102		return domain.MergeModeFastForward, nil
103	case pb.MergeMode_MERGE_MODE_SQUASH:
104		return domain.MergeModeSquash, nil
105	}
106	return "", fmt.Errorf("%w: merge mode %v", domain.ErrInvalid, m)
107}
108
109// mergeModesFromPB maps the allowed modes of the settings, where unspecified
110// is rejected.
111func mergeModesFromPB(in []pb.MergeMode) ([]domain.MergeMode, error) {
112	out := make([]domain.MergeMode, 0, len(in))
113	for _, m := range in {
114		mode, err := mergeModeFromPB(m)
115		if err != nil {
116			return nil, err
117		}
118		if mode == "" {
119			return nil, fmt.Errorf("%w: MERGE_MODE_UNSPECIFIED is not a merge mode", domain.ErrInvalid)
120		}
121		out = append(out, mode)
122	}
123	return out, nil
124}
125
126var scopeToPB = map[domain.Scope]pb.Scope{
127	domain.ScopeRepoRead:       pb.Scope_SCOPE_REPO_READ,
128	domain.ScopeRepoWrite:      pb.Scope_SCOPE_REPO_WRITE,
129	domain.ScopeRepoAdmin:      pb.Scope_SCOPE_REPO_ADMIN,
130	domain.ScopeMRWrite:        pb.Scope_SCOPE_MR_WRITE,
131	domain.ScopeMRMerge:        pb.Scope_SCOPE_MR_MERGE,
132	domain.ScopeCIWrite:        pb.Scope_SCOPE_CI_WRITE,
133	domain.ScopeSecretsWrite:   pb.Scope_SCOPE_SECRETS_WRITE,
134	domain.ScopeRunnerRegister: pb.Scope_SCOPE_RUNNER_REGISTER,
135	domain.ScopeTokenAdmin:     pb.Scope_SCOPE_TOKEN_ADMIN,
136}
137
138func scopeFromPB(s pb.Scope) (domain.Scope, error) {
139	for d, p := range scopeToPB {
140		if p == s {
141			return d, nil
142		}
143	}
144	return "", fmt.Errorf("%w: %v", domain.ErrInvalidScope, s)
145}
146
147func tokenToPB(t domain.Token) *pb.Token {
148	out := &pb.Token{
149		Id:         t.ID,
150		Label:      t.Label,
151		ExpiresAt:  timestamp(t.ExpiresAt),
152		CreatedAt:  timestamp(t.CreatedAt),
153		LastUsedAt: timestamp(t.LastUsedAt),
154	}
155	for _, s := range t.Scopes {
156		out.Scopes = append(out.Scopes, scopeToPB[s])
157	}
158	for _, r := range t.Repos {
159		out.Repos = append(out.Repos, r.String())
160	}
161	out.BranchPrefixes = slices.Clone(t.BranchPrefixes)
162	return out
163}
164
165func refKindToPB(k domain.RefKind) pb.RefKind {
166	switch k {
167	case domain.RefKindBranch:
168		return pb.RefKind_REF_KIND_BRANCH
169	case domain.RefKindTag:
170		return pb.RefKind_REF_KIND_TAG
171	case domain.RefKindHead:
172		return pb.RefKind_REF_KIND_HEAD
173	}
174	return pb.RefKind_REF_KIND_UNSPECIFIED
175}
176
177func refKindFromPB(k pb.RefKind) (domain.RefKind, error) {
178	switch k {
179	case pb.RefKind_REF_KIND_BRANCH:
180		return domain.RefKindBranch, nil
181	case pb.RefKind_REF_KIND_TAG:
182		return domain.RefKindTag, nil
183	case pb.RefKind_REF_KIND_HEAD:
184		return domain.RefKindHead, nil
185	}
186	return "", fmt.Errorf("%w: %v", domain.ErrInvalidRefKind, k)
187}
188
189func refToPB(r domain.Ref) *pb.Ref {
190	return &pb.Ref{
191		Name:      r.Name,
192		ShortName: r.ShortName,
193		Kind:      refKindToPB(r.Kind),
194		Id:        r.ID.String(),
195		CommitId:  r.CommitID.String(),
196	}
197}
198
199func entryKindToPB(k domain.EntryKind) pb.EntryKind {
200	switch k {
201	case domain.EntryFile:
202		return pb.EntryKind_ENTRY_KIND_FILE
203	case domain.EntryExecutable:
204		return pb.EntryKind_ENTRY_KIND_EXECUTABLE
205	case domain.EntryDirectory:
206		return pb.EntryKind_ENTRY_KIND_DIRECTORY
207	case domain.EntrySymlink:
208		return pb.EntryKind_ENTRY_KIND_SYMLINK
209	case domain.EntrySubmodule:
210		return pb.EntryKind_ENTRY_KIND_SUBMODULE
211	}
212	return pb.EntryKind_ENTRY_KIND_UNSPECIFIED
213}
214
215func signatureToPB(s domain.Signature) *pb.Signature {
216	return &pb.Signature{Name: s.Name, Email: s.Email, Time: timestamp(s.Time)}
217}
218
219func commitToPB(c domain.Commit) *pb.Commit {
220	out := &pb.Commit{
221		Id:        c.ID.String(),
222		Author:    signatureToPB(c.Author),
223		Committer: signatureToPB(c.Committer),
224		Summary:   c.Summary,
225		Message:   c.Message,
226	}
227	for _, p := range c.Parents {
228		out.ParentIds = append(out.ParentIds, p.String())
229	}
230	return out
231}
232
233func treeEntryToPB(e domain.TreeEntry) *pb.TreeEntry {
234	out := &pb.TreeEntry{
235		Name: e.Name,
236		Path: e.Path,
237		Kind: entryKindToPB(e.Kind),
238		Mode: e.Mode,
239		Id:   e.ID.String(),
240		Size: e.Size,
241	}
242	if e.LastCommit != nil {
243		out.LastCommit = commitToPB(*e.LastCommit)
244	}
245	return out
246}
247
248func blobInfoToPB(b domain.BlobInfo) *pb.BlobInfo {
249	return &pb.BlobInfo{
250		Id:        b.ID.String(),
251		Path:      b.Path,
252		Size:      b.Size,
253		Binary:    b.Binary,
254		MediaType: b.MediaType,
255		Mode:      b.Mode,
256	}
257}
258
259func fileStatusToPB(s domain.FileStatus) pb.FileStatus {
260	switch s {
261	case domain.FileAdded:
262		return pb.FileStatus_FILE_STATUS_ADDED
263	case domain.FileDeleted:
264		return pb.FileStatus_FILE_STATUS_DELETED
265	case domain.FileModified:
266		return pb.FileStatus_FILE_STATUS_MODIFIED
267	case domain.FileRenamed:
268		return pb.FileStatus_FILE_STATUS_RENAMED
269	case domain.FileCopied:
270		return pb.FileStatus_FILE_STATUS_COPIED
271	case domain.FileTypeChanged:
272		return pb.FileStatus_FILE_STATUS_TYPE_CHANGED
273	}
274	return pb.FileStatus_FILE_STATUS_UNSPECIFIED
275}
276
277func lineKindToPB(k domain.LineKind) pb.LineKind {
278	switch k {
279	case domain.LineContext:
280		return pb.LineKind_LINE_KIND_CONTEXT
281	case domain.LineAddition:
282		return pb.LineKind_LINE_KIND_ADDITION
283	case domain.LineDeletion:
284		return pb.LineKind_LINE_KIND_DELETION
285	}
286	return pb.LineKind_LINE_KIND_UNSPECIFIED
287}
288
289func hunkToPB(h domain.Hunk) *pb.Hunk {
290	out := &pb.Hunk{
291		OldStart: int32(h.OldStart), OldLines: int32(h.OldLines),
292		NewStart: int32(h.NewStart), NewLines: int32(h.NewLines),
293		Header: h.Header,
294		Lines:  make([]*pb.Line, 0, len(h.Lines)),
295	}
296	for _, l := range h.Lines {
297		out.Lines = append(out.Lines, &pb.Line{
298			Kind:           lineKindToPB(l.Kind),
299			OldNumber:      int32(l.OldNumber),
300			NewNumber:      int32(l.NewNumber),
301			Text:           l.Text,
302			NoNewlineAtEof: l.NoNewlineAtEOF,
303		})
304	}
305	return out
306}
307
308func fileDiffToPB(f domain.FileDiff) *pb.FileDiff {
309	out := &pb.FileDiff{
310		OldPath: f.OldPath, NewPath: f.NewPath,
311		Status:  fileStatusToPB(f.Status),
312		OldMode: f.OldMode, NewMode: f.NewMode,
313		OldId: f.OldID.String(), NewId: f.NewID.String(),
314		Binary:     f.Binary,
315		Additions:  int32(f.Additions),
316		Deletions:  int32(f.Deletions),
317		Similarity: int32(f.Similarity),
318		Truncated:  f.Truncated,
319	}
320	for _, h := range f.Hunks {
321		out.Hunks = append(out.Hunks, hunkToPB(h))
322	}
323	return out
324}
325
326func diffStatsToPB(s domain.DiffStats) *pb.DiffStats {
327	return &pb.DiffStats{
328		FilesChanged: int32(s.FilesChanged),
329		Additions:    int32(s.Additions),
330		Deletions:    int32(s.Deletions),
331	}
332}
333
334func diffToPB(d domain.Diff) *pb.Diff {
335	out := &pb.Diff{Truncated: d.Truncated}
336	for _, f := range d.Files {
337		out.Files = append(out.Files, fileDiffToPB(f))
338	}
339	return out
340}
341
342func commitDetailToPB(d domain.CommitDetail) *pb.GetCommitResponse {
343	return &pb.GetCommitResponse{
344		Commit: commitToPB(d.Commit),
345		Stats:  diffStatsToPB(d.Stats),
346		Diff:   diffToPB(d.Diff),
347	}
348}
349
350// oidToPB turns the zero object id of a ref update (no object) into "".
351func oidToPB(oid string) string {
352	if oid == domain.ZeroOID {
353		return ""
354	}
355	return oid
356}
357
358func refUpdatesToPB(updates []domain.RefUpdate) []*pb.RefUpdate {
359	out := make([]*pb.RefUpdate, 0, len(updates))
360	for _, u := range updates {
361		out = append(out, &pb.RefUpdate{Ref: u.Ref, OldId: oidToPB(u.Old), NewId: oidToPB(u.New)})
362	}
363	return out
364}
365
366// watchEventToPB maps one item of a watch; nil when the event has no
367// representation in the contract.
368func watchEventToPB(we ports.WatchEvent) *pb.Event {
369	if we.Gap {
370		return &pb.Event{Kind: &pb.Event_Gap{Gap: &pb.Gap{}}}
371	}
372	out := &pb.Event{Id: we.ID}
373	switch ev := we.Event.(type) {
374	case domain.RepoCreated:
375		out.Time = timestamp(ev.At)
376		out.Kind = &pb.Event_RepoCreated{RepoCreated: &pb.RepoCreated{Repo: repoOrName(we, ev.Repo, ev.Visibility)}}
377	case domain.RepoUpdated:
378		out.Time = timestamp(ev.At)
379		out.Kind = &pb.Event_RepoUpdated{RepoUpdated: &pb.RepoUpdated{Repo: repoOrName(we, ev.Repo, "")}}
380	case domain.RepoDeleted:
381		out.Time = timestamp(ev.At)
382		out.Kind = &pb.Event_RepoDeleted{RepoDeleted: &pb.RepoDeleted{Repo: ev.Repo.String()}}
383	case domain.PushEvent:
384		out.Time = timestamp(ev.At)
385		out.Kind = &pb.Event_Pushed{Pushed: &pb.Pushed{Repo: ev.Repo.String(), RefUpdates: refUpdatesToPB(ev.Updates)}}
386	case domain.MergeRequestOpened:
387		out.Time = timestamp(ev.At)
388		out.Kind = &pb.Event_MergeRequestOpened{MergeRequestOpened: &pb.MergeRequestOpened{MergeRequest: mergeRequestToPB(ev.MergeRequest)}}
389	case domain.MergeRequestMerged:
390		out.Time = timestamp(ev.At)
391		out.Kind = &pb.Event_MergeRequestMerged{MergeRequestMerged: &pb.MergeRequestMerged{MergeRequest: mergeRequestToPB(ev.MergeRequest)}}
392	case domain.MergeRequestClosed:
393		out.Time = timestamp(ev.At)
394		out.Kind = &pb.Event_MergeRequestClosed{MergeRequestClosed: &pb.MergeRequestClosed{MergeRequest: mergeRequestToPB(ev.MergeRequest)}}
395	case domain.CommentAdded:
396		out.Time = timestamp(ev.At)
397		out.Kind = &pb.Event_CommentAdded{CommentAdded: &pb.CommentAdded{Repo: ev.Repo.String(), Number: ev.Number, Comment: commentToPB(ev.Comment)}}
398	case domain.RunUpdated:
399		out.Time = timestamp(ev.At)
400		out.Kind = runEventToPB(ev)
401	case domain.JobUpdated:
402		out.Time = timestamp(ev.At)
403		out.Kind = jobEventToPB(ev)
404	default:
405		return nil
406	}
407	return out
408}
409
410func repoOrName(we ports.WatchEvent, name domain.RepoName, vis domain.Visibility) *pb.Repo {
411	if we.Repo != nil {
412		return repoToPB(*we.Repo)
413	}
414	return &pb.Repo{Name: name.String(), Visibility: visibilityToPB(vis)}
415}
416
417// passkeysToPB converts passkeys; the credential id is base64url without
418// padding, the form RemovePasskey takes back. Key material never leaves.
419func passkeysToPB(list []domain.Passkey) []*pb.Passkey {
420	out := make([]*pb.Passkey, 0, len(list))
421	for _, p := range list {
422		out = append(out, &pb.Passkey{
423			Id:         base64.RawURLEncoding.EncodeToString(p.ID),
424			Name:       p.Name,
425			CreatedAt:  timestamp(p.CreatedAt),
426			LastUsedAt: timestamp(p.LastUsedAt),
427			Synced:     p.BackupState,
428		})
429	}
430	return out
431}

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 3

Tags 44

↑↓ moveenter openesc close