v0.8.0 eaf4295

repos_write.go RawHistoryFolder

1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package usecase
4
5import (
6	"context"
7	"errors"
8	"fmt"
9	"unicode"
10	"unicode/utf8"
11
12	"github.com/bnema/zerowrap"
13
14	"bnema.dev/ermite/internal/domain"
15	"bnema.dev/ermite/internal/ports"
16)
17
18// MaxDescriptionLen is the longest repository description, in bytes.
19const MaxDescriptionLen = 500
20
21// validateDescription accepts a one-line description of valid UTF-8.
22func validateDescription(s string) error {
23	if len(s) > MaxDescriptionLen {
24		return fmt.Errorf("%w: description is longer than %d bytes", domain.ErrInvalid, MaxDescriptionLen)
25	}
26	if !utf8.ValidString(s) {
27		return fmt.Errorf("%w: description is not valid UTF-8", domain.ErrInvalid)
28	}
29	for _, c := range s {
30		if unicode.IsControl(c) {
31			return fmt.Errorf("%w: description must be one line without control characters", domain.ErrInvalid)
32		}
33	}
34	return nil
35}
36
37// View adds the default branch to a repository the caller has already been
38// allowed to see. A repository without a directory has no default branch.
39func (r *Repos) View(ctx context.Context, repo domain.Repo) (ports.RepoView, error) {
40	branch, err := r.git.HeadBranch(ctx, repo.Name)
41	if err != nil && !errors.Is(err, domain.ErrNotFound) {
42		return ports.RepoView{}, fmt.Errorf("read default branch of %q: %w", repo.Name, err)
43	}
44	return ports.RepoView{Repo: repo, DefaultBranch: branch}, nil
45}
46
47// Update changes the description, the visibility, the default branch and the
48// merge settings of a repository, and publishes RepoUpdated. The principal needs repo:admin on it
49// (see adminAccess for what the others learn) and no branch prefixes. At least one field must be set,
50// else domain.ErrInvalid. A default branch that does not exist gives
51// domain.ErrPreconditionFailed; nothing is written before every check passed.
52// The metadata is written first, then HEAD, and RepoUpdated is published after
53// both. When only the HEAD move fails, RepoUpdated is still published for the
54// stored metadata and the HEAD error is returned.
55func (r *Repos) Update(ctx context.Context, p domain.Principal, name domain.RepoName, params ports.UpdateRepoParams) (domain.Repo, error) {
56	repo, err := lookupRepo(ctx, r.meta, name)
57	if err != nil {
58		return domain.Repo{}, err
59	}
60	if err := adminAccess(p, repo); err != nil {
61		return domain.Repo{}, err
62	}
63	before := repo
64	if params.Description == nil && params.Visibility == nil && params.DefaultBranch == nil &&
65		params.AllowedMergeModes == nil && params.FailingChecksBlock == nil {
66		return domain.Repo{}, fmt.Errorf("%w: nothing to update", domain.ErrInvalid)
67	}
68	if params.AllowedMergeModes != nil {
69		modes, err := domain.NormalizeMergeModes(*params.AllowedMergeModes)
70		if err != nil {
71			return domain.Repo{}, err
72		}
73		params.AllowedMergeModes = &modes
74	}
75	if params.Description != nil {
76		if err := validateDescription(*params.Description); err != nil {
77			return domain.Repo{}, err
78		}
79	}
80	if params.Visibility != nil {
81		if _, err := domain.ParseVisibility(params.Visibility.String()); err != nil {
82			return domain.Repo{}, err
83		}
84	}
85	if params.DefaultBranch != nil {
86		if *params.DefaultBranch == "" {
87			return domain.Repo{}, fmt.Errorf("%w: default branch is empty", domain.ErrInvalid)
88		}
89		ok, err := r.git.HasBranch(ctx, name, *params.DefaultBranch)
90		if err != nil {
91			return domain.Repo{}, fmt.Errorf("check branch %q of %q: %w", *params.DefaultBranch, name, err)
92		}
93		if !ok {
94			return domain.Repo{}, fmt.Errorf("%w: branch %q does not exist", domain.ErrPreconditionFailed, *params.DefaultBranch)
95		}
96	}
97
98	// Metadata first, then HEAD. The two writes are not atomic: when moving
99	// HEAD fails after the metadata was stored, the stored change is still
100	// published as RepoUpdated (a repository made private must be withdrawn
101	// from the watchers) and the call then fails with the HEAD error. The
102	// branch was checked above, so the remaining causes are a vanished
103	// repository or an I/O failure.
104	metaDone := false
105	if params.Description != nil || params.Visibility != nil || params.AllowedMergeModes != nil || params.FailingChecksBlock != nil {
106		if repo, err = r.updateMeta(ctx, name, params); err != nil {
107			return domain.Repo{}, err
108		}
109		metaDone = true
110	}
111	var headErr error
112	if params.DefaultBranch != nil {
113		if err := r.git.SetDefaultBranch(ctx, name, *params.DefaultBranch); err != nil {
114			headErr = fmt.Errorf("set default branch of %q: %w", name, err)
115			if !metaDone {
116				return domain.Repo{}, headErr
117			}
118		}
119	}
120
121	log := zerowrap.FromCtx(ctx)
122	log.Info().
123		Str("repo", name.String()).
124		Bool("description", params.Description != nil).
125		Bool("visibility", params.Visibility != nil).
126		Bool("default_branch", params.DefaultBranch != nil).
127		Bool("settings", params.AllowedMergeModes != nil || params.FailingChecksBlock != nil).
128		Str("principal", p.Label()).Str("token_id", p.TokenID()).
129		Msg("repository updated")
130	r.bus.Publish(ctx, domain.RepoUpdated{
131		Repo: name, At: r.clock.Now().UTC(),
132		Visibility: repo.Visibility, Previous: before.Visibility, CreatedAt: repo.CreatedAt,
133	})
134	if headErr != nil {
135		return domain.Repo{}, headErr
136	}
137	return repo, nil
138}
139
140// updateMeta applies the metadata fields, retrying when a write (a push
141// recording pushed_at) gets in between.
142func (r *Repos) updateMeta(ctx context.Context, name domain.RepoName, params ports.UpdateRepoParams) (domain.Repo, error) {
143	for range pushRetries {
144		repo, err := r.meta.Get(ctx, name)
145		if err != nil {
146			return domain.Repo{}, err
147		}
148		if params.Description != nil {
149			repo.Description = *params.Description
150		}
151		if params.Visibility != nil {
152			repo.Visibility = *params.Visibility
153		}
154		if repo.Settings.IsZero() {
155			repo.Settings = domain.DefaultRepoSettings()
156		}
157		if params.AllowedMergeModes != nil {
158			repo.Settings.AllowedMergeModes = *params.AllowedMergeModes
159		}
160		if params.FailingChecksBlock != nil {
161			repo.Settings.FailingChecksBlock = *params.FailingChecksBlock
162		}
163		err = r.meta.Update(ctx, repo)
164		if errors.Is(err, domain.ErrConflict) {
165			continue
166		}
167		if err != nil {
168			return domain.Repo{}, fmt.Errorf("update repository %q: %w", name, err)
169		}
170		return repo, nil
171	}
172	return domain.Repo{}, fmt.Errorf("update repository %q: %w", name, domain.ErrConflict)
173}
174
175// Delete moves the repository directory to the trash, removes its metadata
176// and publishes RepoDeleted. The principal needs repo:admin on it (see
177// adminAccess) and no branch prefixes. A repository whose directory is already gone, left by a
178// delete that failed half way, loses its metadata.
179func (r *Repos) Delete(ctx context.Context, p domain.Principal, name domain.RepoName) error {
180	repo, err := lookupRepo(ctx, r.meta, name)
181	if err != nil {
182		return err
183	}
184	if err := adminAccess(p, repo); err != nil {
185		return err
186	}
187	log := zerowrap.FromCtx(ctx)
188	switch err := r.git.Trash(ctx, name); {
189	case errors.Is(err, domain.ErrNotFound):
190		log.Warn().Str("repo", name.String()).Msg("repository directory already gone, removing its metadata")
191	case err != nil:
192		return fmt.Errorf("trash repository %q: %w", name, err)
193	}
194	var runIDs []int64
195	if r.ci != nil {
196		// Listed before the records go: the logs are found by run id.
197		if ids, err := r.ci.RunIDs(ctx, name); err == nil {
198			runIDs = ids
199		} else {
200			log.Warn().Err(err).Str("repo", name.String()).Msg("list the CI runs of the repository; their logs are left to the sweep")
201		}
202	}
203	if err := r.meta.Delete(ctx, name); err != nil {
204		return fmt.Errorf("delete metadata of %q: %w", name, err)
205	}
206	if len(runIDs) > 0 {
207		if err := r.ci.RemoveLogs(context.WithoutCancel(ctx), runIDs); err != nil {
208			log.Warn().Err(err).Str("repo", name.String()).Msg("remove the CI logs of the repository; the sweep will")
209		}
210	}
211	log.Info().Str("repo", name.String()).Str("principal", p.Label()).Str("token_id", p.TokenID()).Msg("repository deleted")
212	r.bus.Publish(ctx, domain.RepoDeleted{Repo: name, Visibility: repo.Visibility, At: r.clock.Now().UTC(), CreatedAt: repo.CreatedAt})
213	return nil
214}

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 2

Tags 44

↑↓ moveenter openesc close