@lbdudc/linea-git 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +47 -2
- package/dist/access.d.ts +18 -0
- package/dist/access.js +18 -0
- package/dist/access.js.map +1 -0
- package/dist/auth.d.ts +11 -0
- package/dist/auth.js +16 -0
- package/dist/auth.js.map +1 -0
- package/dist/changelog/generate.d.ts +18 -0
- package/dist/changelog/generate.js +166 -0
- package/dist/changelog/generate.js.map +1 -0
- package/dist/changelog/index.d.ts +5 -0
- package/dist/changelog/index.js +3 -0
- package/dist/changelog/index.js.map +1 -0
- package/dist/changelog/parse.d.ts +43 -0
- package/dist/changelog/parse.js +91 -0
- package/dist/changelog/parse.js.map +1 -0
- package/dist/changelog/types.d.ts +85 -0
- package/dist/changelog/types.js +2 -0
- package/dist/changelog/types.js.map +1 -0
- package/dist/checkout/credential.d.ts +14 -0
- package/dist/checkout/credential.js +29 -0
- package/dist/checkout/credential.js.map +1 -0
- package/dist/checkout/git.d.ts +78 -0
- package/dist/checkout/git.js +191 -0
- package/dist/checkout/git.js.map +1 -0
- package/dist/checkout/index.d.ts +3 -0
- package/dist/checkout/index.js +4 -0
- package/dist/checkout/index.js.map +1 -0
- package/dist/checkout/sync.d.ts +156 -0
- package/dist/checkout/sync.js +211 -0
- package/dist/checkout/sync.js.map +1 -0
- package/dist/closing.d.ts +1 -0
- package/dist/closing.js +14 -0
- package/dist/closing.js.map +1 -0
- package/dist/config.d.ts +53 -0
- package/dist/config.js +40 -0
- package/dist/config.js.map +1 -0
- package/dist/deletion.d.ts +19 -0
- package/dist/deletion.js +27 -0
- package/dist/deletion.js.map +1 -0
- package/dist/errors.d.ts +26 -0
- package/dist/errors.js +47 -0
- package/dist/errors.js.map +1 -0
- package/dist/factory.d.ts +20 -0
- package/dist/factory.js +46 -0
- package/dist/factory.js.map +1 -0
- package/dist/github/client.d.ts +44 -0
- package/dist/github/client.js +145 -0
- package/dist/github/client.js.map +1 -0
- package/dist/github/config.d.ts +24 -0
- package/dist/github/config.js +11 -0
- package/dist/github/config.js.map +1 -0
- package/dist/github/provider.d.ts +510 -0
- package/dist/github/provider.js +1009 -0
- package/dist/github/provider.js.map +1 -0
- package/dist/gitlab/client.d.ts +50 -0
- package/dist/gitlab/client.js +228 -0
- package/dist/gitlab/client.js.map +1 -0
- package/dist/gitlab/provider.d.ts +487 -0
- package/dist/gitlab/provider.js +719 -0
- package/dist/gitlab/provider.js.map +1 -0
- package/dist/host.d.ts +27 -0
- package/dist/host.js +45 -0
- package/dist/host.js.map +1 -0
- package/dist/index.d.ts +46 -0
- package/dist/index.js +31 -0
- package/dist/index.js.map +1 -0
- package/dist/local/diff.d.ts +3 -0
- package/dist/local/diff.js +43 -0
- package/dist/local/diff.js.map +1 -0
- package/dist/local/git.d.ts +24 -0
- package/dist/local/git.js +51 -0
- package/dist/local/git.js.map +1 -0
- package/dist/local/health.d.ts +36 -0
- package/dist/local/health.js +57 -0
- package/dist/local/health.js.map +1 -0
- package/dist/local/hooks.d.ts +2 -0
- package/dist/local/hooks.js +44 -0
- package/dist/local/hooks.js.map +1 -0
- package/dist/local/http.d.ts +35 -0
- package/dist/local/http.js +160 -0
- package/dist/local/http.js.map +1 -0
- package/dist/local/provider.d.ts +571 -0
- package/dist/local/provider.js +1237 -0
- package/dist/local/provider.js.map +1 -0
- package/dist/local/store.d.ts +136 -0
- package/dist/local/store.js +171 -0
- package/dist/local/store.js.map +1 -0
- package/dist/packages/github-source.d.ts +69 -0
- package/dist/packages/github-source.js +133 -0
- package/dist/packages/github-source.js.map +1 -0
- package/dist/packages/gitlab-source.d.ts +59 -0
- package/dist/packages/gitlab-source.js +214 -0
- package/dist/packages/gitlab-source.js.map +1 -0
- package/dist/packages/index.d.ts +30 -0
- package/dist/packages/index.js +45 -0
- package/dist/packages/index.js.map +1 -0
- package/dist/packages/provider-source.d.ts +34 -0
- package/dist/packages/provider-source.js +57 -0
- package/dist/packages/provider-source.js.map +1 -0
- package/dist/packages/repository-files.d.ts +12 -0
- package/dist/packages/repository-files.js +16 -0
- package/dist/packages/repository-files.js.map +1 -0
- package/dist/provider.d.ts +888 -0
- package/dist/provider.js +29 -0
- package/dist/provider.js.map +1 -0
- package/dist/read-cache.d.ts +5 -0
- package/dist/read-cache.js +101 -0
- package/dist/read-cache.js.map +1 -0
- package/dist/registry/catalog.d.ts +55 -0
- package/dist/registry/catalog.js +143 -0
- package/dist/registry/catalog.js.map +1 -0
- package/dist/registry/kinds.d.ts +21 -0
- package/dist/registry/kinds.js +43 -0
- package/dist/registry/kinds.js.map +1 -0
- package/dist/registry/packages.d.ts +165 -0
- package/dist/registry/packages.js +290 -0
- package/dist/registry/packages.js.map +1 -0
- package/dist/registry/publish.d.ts +35 -0
- package/dist/registry/publish.js +155 -0
- package/dist/registry/publish.js.map +1 -0
- package/dist/registry/release.d.ts +63 -0
- package/dist/registry/release.js +79 -0
- package/dist/registry/release.js.map +1 -0
- package/dist/restoration.d.ts +14 -0
- package/dist/restoration.js +33 -0
- package/dist/restoration.js.map +1 -0
- package/dist/templates.d.ts +8 -0
- package/dist/templates.js +39 -0
- package/dist/templates.js.map +1 -0
- package/dist/testing/contract.d.ts +43 -0
- package/dist/testing/contract.js +713 -0
- package/dist/testing/contract.js.map +1 -0
- package/dist/testing/diff.d.ts +1 -0
- package/dist/testing/diff.js +65 -0
- package/dist/testing/diff.js.map +1 -0
- package/dist/testing/git-http.d.ts +12 -0
- package/dist/testing/git-http.js +308 -0
- package/dist/testing/git-http.js.map +1 -0
- package/dist/testing/github-double.d.ts +151 -0
- package/dist/testing/github-double.js +1129 -0
- package/dist/testing/github-double.js.map +1 -0
- package/dist/testing/gitlab-double.d.ts +161 -0
- package/dist/testing/gitlab-double.js +1554 -0
- package/dist/testing/gitlab-double.js.map +1 -0
- package/dist/testing/index.d.ts +7 -0
- package/dist/testing/index.js +8 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +12 -0
- package/dist/version.js.map +1 -0
- package/package.json +66 -4
|
@@ -0,0 +1,1237 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { spawn } from 'node:child_process';
|
|
6
|
+
import { PassThrough } from 'node:stream';
|
|
7
|
+
import { ACCESS } from '../access.js';
|
|
8
|
+
import { closingIssueNumbers } from '../closing.js';
|
|
9
|
+
import { parseGitDiff } from './diff.js';
|
|
10
|
+
import { LocalError, cleanEnv, git, gitOk, gitText, identity } from './git.js';
|
|
11
|
+
import { LocalStore } from './store.js';
|
|
12
|
+
/** The path segment a name becomes. Never ends in `.git` (that is where a repository's address ends) or starts with a dot. */
|
|
13
|
+
export const slug = (name) => String(name).trim().replace(/\s+/g, '-').replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^[-.]+|-+$/g, '').replace(/(\.git)+$/i, '').replace(/-+$/g, '') || 'unnamed';
|
|
14
|
+
const EMPTY_TREE = '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
|
|
15
|
+
const WRITE_ACCESS = ACCESS.DEVELOPER;
|
|
16
|
+
const CLOSED_KEPT_MS = 90 * 24 * 60 * 60 * 1000;
|
|
17
|
+
/**
|
|
18
|
+
* Reads the output of `git log -z --format=%H%x00%an%x00%aI%x00%s%x00%b`: NUL is the one byte a commit message cannot hold, so a message
|
|
19
|
+
* cannot add a commit or move a field. Five fields a commit, the last one (the body) followed by the NUL that ends the record.
|
|
20
|
+
*/
|
|
21
|
+
const parseLog = (output) => {
|
|
22
|
+
const parts = output.split('\0');
|
|
23
|
+
const commits = [];
|
|
24
|
+
for (let at = 0; at + 4 < parts.length; at += 5) {
|
|
25
|
+
const [sha = '', authorName = '', createdAt = '', title = '', body = ''] = parts.slice(at, at + 5);
|
|
26
|
+
if (!/^[0-9a-f]{40,64}$/.test(sha.replace(/^\n/, '')))
|
|
27
|
+
break;
|
|
28
|
+
const rest = body.trim();
|
|
29
|
+
commits.push({ shortId: sha.replace(/^\n/, '').slice(0, 8), title, authorName, createdAt, webUrl: '', message: rest ? `${title}\n\n${rest}` : title });
|
|
30
|
+
}
|
|
31
|
+
return commits;
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* Repositories kept on the machine LINEA runs on, as bare git repositories: LINEA works with no other git host. A person's token is
|
|
35
|
+
* LINEA's own (a local account); everybody on the server can work in every repository (level 40), the person who made it, and the
|
|
36
|
+
* administrators, own it (level 50).
|
|
37
|
+
*
|
|
38
|
+
* What the other hosts have besides git is kept in `state.json` (see store.ts): groups, topics, members, change requests. There is no
|
|
39
|
+
* CI here: a pipeline is what the host runs, and this one runs none.
|
|
40
|
+
*/
|
|
41
|
+
export class LocalProvider {
|
|
42
|
+
kind = 'local';
|
|
43
|
+
nestsNamespaces = true;
|
|
44
|
+
webhookPath = '/api/webhooks/local';
|
|
45
|
+
store;
|
|
46
|
+
baseUrl;
|
|
47
|
+
redirectUri;
|
|
48
|
+
resolveUser;
|
|
49
|
+
undo = [];
|
|
50
|
+
readOnlyGroups;
|
|
51
|
+
constructor(options) {
|
|
52
|
+
this.store = new LocalStore(options.dataDir);
|
|
53
|
+
this.baseUrl = (options.baseUrl ?? 'http://localhost:3000/git').replace(/\/+$/, '');
|
|
54
|
+
this.redirectUri = options.redirectUri ?? '';
|
|
55
|
+
this.resolveUser = options.resolveUser ?? (() => ({ username: 'local' }));
|
|
56
|
+
this.readOnlyGroups = options.readOnlyGroups ?? [];
|
|
57
|
+
}
|
|
58
|
+
// ── plumbing ─────────────────────────────────────────────────────────────
|
|
59
|
+
remember(undo) {
|
|
60
|
+
this.undo.push(undo);
|
|
61
|
+
}
|
|
62
|
+
async user(token) {
|
|
63
|
+
const user = await this.resolveUser(token);
|
|
64
|
+
if (!user)
|
|
65
|
+
throw new LocalError('The token does not belong to anyone here', 401, 'unauthorized');
|
|
66
|
+
return user;
|
|
67
|
+
}
|
|
68
|
+
namespaceOf(state, id) {
|
|
69
|
+
const found = state.namespaces.find((namespace) => namespace.id === Number(id));
|
|
70
|
+
if (!found)
|
|
71
|
+
throw new LocalError('There is no such group', 404);
|
|
72
|
+
return found;
|
|
73
|
+
}
|
|
74
|
+
repositoryOf(state, id) {
|
|
75
|
+
const found = typeof id === 'string' && Number.isNaN(Number(id))
|
|
76
|
+
? state.repositories.find((repository) => this.pathOf(state, repository) === id)
|
|
77
|
+
: state.repositories.find((repository) => repository.id === Number(id));
|
|
78
|
+
if (!found)
|
|
79
|
+
throw new LocalError('There is no such repository', 404);
|
|
80
|
+
return found;
|
|
81
|
+
}
|
|
82
|
+
pathOf(state, repository) {
|
|
83
|
+
return `${this.namespaceOf(state, repository.namespaceId).path}/${slug(repository.name)}`;
|
|
84
|
+
}
|
|
85
|
+
dirOf(repository) {
|
|
86
|
+
return this.store.repositoryDir(repository.id);
|
|
87
|
+
}
|
|
88
|
+
toRepository(state, repository) {
|
|
89
|
+
const namespace = this.namespaceOf(state, repository.namespaceId);
|
|
90
|
+
const repoPath = this.pathOf(state, repository);
|
|
91
|
+
return {
|
|
92
|
+
id: repository.id,
|
|
93
|
+
name: repository.name,
|
|
94
|
+
path: repoPath,
|
|
95
|
+
description: repository.description,
|
|
96
|
+
webUrl: `${this.baseUrl}/${repoPath}`,
|
|
97
|
+
webIdeUrl: '',
|
|
98
|
+
namespaceId: repository.namespaceId,
|
|
99
|
+
parentNamespaceId: namespace.parentId ?? undefined,
|
|
100
|
+
defaultBranch: repository.defaultBranch,
|
|
101
|
+
topics: [...repository.topics]
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
toNamespace(namespace) {
|
|
105
|
+
return { id: namespace.id, fullPath: namespace.path, name: namespace.name };
|
|
106
|
+
}
|
|
107
|
+
/** The repository and the folder of its git, once the caller is known to be allowed `level` on it. */
|
|
108
|
+
async open(token, id, level = ACCESS.REPORTER) {
|
|
109
|
+
const user = await this.user(token);
|
|
110
|
+
const state = await this.store.read((current) => current);
|
|
111
|
+
const record = this.repositoryOf(state, id);
|
|
112
|
+
if (this.levelFor(state, record, user) < level)
|
|
113
|
+
throw new LocalError('You are not allowed to do that here', 403);
|
|
114
|
+
return { record, dir: this.dirOf(record), user, state };
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* What a person may do in a repository, as a git host's access level: the owner and the administrators can do everything, a member
|
|
118
|
+
* has the level they were given, and everybody else works in it (maintainer) unless it is in a group only its owner writes in.
|
|
119
|
+
* The API and git over HTTP both ask this, so a person can do the same through either.
|
|
120
|
+
*/
|
|
121
|
+
levelFor(state, record, user) {
|
|
122
|
+
if (user.admin || record.owner === user.username)
|
|
123
|
+
return ACCESS.OWNER;
|
|
124
|
+
const member = record.members.find((candidate) => candidate.username === user.username);
|
|
125
|
+
if (member)
|
|
126
|
+
return member.accessLevel;
|
|
127
|
+
return this.isReadOnly(state, record.namespaceId) ? ACCESS.REPORTER : ACCESS.MAINTAINER;
|
|
128
|
+
}
|
|
129
|
+
isReadOnly(state, namespaceId) {
|
|
130
|
+
const found = state.namespaces.find((namespace) => namespace.id === namespaceId);
|
|
131
|
+
return Boolean(found) && this.readOnlyGroups.includes(found.path.split('/')[0]);
|
|
132
|
+
}
|
|
133
|
+
/** The level on a group: the same rule, for creating in it, renaming it and deleting it. */
|
|
134
|
+
levelOnNamespace(state, namespace, user) {
|
|
135
|
+
if (user.admin || namespace.owner === user.username)
|
|
136
|
+
return ACCESS.OWNER;
|
|
137
|
+
return this.isReadOnly(state, namespace.id) ? ACCESS.REPORTER : ACCESS.MAINTAINER;
|
|
138
|
+
}
|
|
139
|
+
/** Whoever owns every repository under a group may also delete or rename it (the person who made a line owns the groups of its products). */
|
|
140
|
+
ownsEverythingUnder(state, ids, user) {
|
|
141
|
+
return state.repositories.filter((repository) => ids.has(repository.namespaceId)).every((repository) => this.levelFor(state, repository, user) >= ACCESS.OWNER);
|
|
142
|
+
}
|
|
143
|
+
async resolveCommit(dir, ref) {
|
|
144
|
+
const result = await git(dir, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]);
|
|
145
|
+
return result.code === 0 ? result.stdout.toString('utf8').trim() : null;
|
|
146
|
+
}
|
|
147
|
+
async mustResolve(dir, ref) {
|
|
148
|
+
const commit = await this.resolveCommit(dir, ref);
|
|
149
|
+
if (!commit)
|
|
150
|
+
throw new LocalError(`There is no "${ref}" in this repository`, 404);
|
|
151
|
+
return commit;
|
|
152
|
+
}
|
|
153
|
+
// ── identity ─────────────────────────────────────────────────────────────
|
|
154
|
+
authConfig() {
|
|
155
|
+
return { kind: 'local', clientId: undefined, redirectUri: this.redirectUri, url: this.baseUrl, authorizeUrl: '', scope: '' };
|
|
156
|
+
}
|
|
157
|
+
async exchangeCode() {
|
|
158
|
+
throw new LocalError('People sign in to LINEA with a password here: there is no code to exchange', 400);
|
|
159
|
+
}
|
|
160
|
+
async refreshToken({ accessToken }) {
|
|
161
|
+
return { accessToken, refreshToken: null };
|
|
162
|
+
}
|
|
163
|
+
async getUser({ token }) {
|
|
164
|
+
const user = await this.user(token);
|
|
165
|
+
return { username: user.username, avatarUrl: user.avatarUrl ?? '' };
|
|
166
|
+
}
|
|
167
|
+
// ── namespaces ───────────────────────────────────────────────────────────
|
|
168
|
+
async listNamespaces({ token }) {
|
|
169
|
+
await this.user(token);
|
|
170
|
+
return (await this.store.read((state) => state.namespaces)).map((namespace) => this.toNamespace(namespace));
|
|
171
|
+
}
|
|
172
|
+
async findNamespace({ token, fullPath }) {
|
|
173
|
+
await this.user(token);
|
|
174
|
+
const found = await this.store.read((state) => state.namespaces.find((namespace) => namespace.path === fullPath));
|
|
175
|
+
return found ? this.toNamespace(found) : null;
|
|
176
|
+
}
|
|
177
|
+
async createNamespace({ token, name, parentId }) {
|
|
178
|
+
const user = await this.user(token);
|
|
179
|
+
const created = await this.store.update((state) => {
|
|
180
|
+
const parent = parentId === undefined || parentId === null ? null : this.namespaceOf(state, parentId);
|
|
181
|
+
if (parent && this.levelOnNamespace(state, parent, user) < WRITE_ACCESS)
|
|
182
|
+
throw new LocalError('You are not allowed to create groups here', 403);
|
|
183
|
+
const fullPath = parent ? `${parent.path}/${slug(name)}` : slug(name);
|
|
184
|
+
if (state.namespaces.some((namespace) => namespace.path === fullPath)) {
|
|
185
|
+
throw new LocalError(`The group "${fullPath}" already exists`, 409, 'already_exists');
|
|
186
|
+
}
|
|
187
|
+
const record = { id: state.next++, name, path: fullPath, parentId: parent?.id ?? null, owner: user.username };
|
|
188
|
+
state.namespaces.push(record);
|
|
189
|
+
return record;
|
|
190
|
+
});
|
|
191
|
+
this.remember(() => this.store.update((state) => { state.namespaces = state.namespaces.filter((namespace) => namespace.id !== created.id); }));
|
|
192
|
+
return this.toNamespace(created);
|
|
193
|
+
}
|
|
194
|
+
async deleteNamespace({ token, id }) {
|
|
195
|
+
const user = await this.user(token);
|
|
196
|
+
const removed = await this.store.update((state) => {
|
|
197
|
+
const root = this.namespaceOf(state, id);
|
|
198
|
+
const ids = this.subtreeOf(state, root.id);
|
|
199
|
+
if (this.levelOnNamespace(state, root, user) < ACCESS.OWNER && !this.ownsEverythingUnder(state, ids, user))
|
|
200
|
+
throw new LocalError('You are not allowed to delete this group', 403);
|
|
201
|
+
const repositories = state.repositories.filter((repository) => ids.has(repository.namespaceId));
|
|
202
|
+
const namespaces = state.namespaces.filter((namespace) => ids.has(namespace.id));
|
|
203
|
+
state.repositories = state.repositories.filter((repository) => !ids.has(repository.namespaceId));
|
|
204
|
+
state.namespaces = state.namespaces.filter((namespace) => !ids.has(namespace.id));
|
|
205
|
+
return { repositories, namespaces };
|
|
206
|
+
});
|
|
207
|
+
const moved = removed.repositories.map((repository) => this.toTrash(repository));
|
|
208
|
+
// until the caller commits its own bookkeeping, this can be undone (`rollback()`): the repositories are in the trash, not gone
|
|
209
|
+
this.remember(() => this.restore({ ...removed, moved }));
|
|
210
|
+
return undefined;
|
|
211
|
+
}
|
|
212
|
+
subtreeOf(state, rootId) {
|
|
213
|
+
const ids = new Set([rootId]);
|
|
214
|
+
for (let grew = true; grew;) {
|
|
215
|
+
grew = false;
|
|
216
|
+
for (const namespace of state.namespaces) {
|
|
217
|
+
if (namespace.parentId !== null && ids.has(namespace.parentId) && !ids.has(namespace.id)) {
|
|
218
|
+
ids.add(namespace.id);
|
|
219
|
+
grew = true;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
return ids;
|
|
224
|
+
}
|
|
225
|
+
async renameNamespace({ token, id, name }) {
|
|
226
|
+
const user = await this.user(token);
|
|
227
|
+
await this.store.update((state) => {
|
|
228
|
+
const namespace = this.namespaceOf(state, id);
|
|
229
|
+
if (this.levelOnNamespace(state, namespace, user) < ACCESS.OWNER && !this.ownsEverythingUnder(state, this.subtreeOf(state, namespace.id), user)) {
|
|
230
|
+
throw new LocalError('You are not allowed to rename this group', 403);
|
|
231
|
+
}
|
|
232
|
+
const parent = namespace.parentId === null ? null : this.namespaceOf(state, namespace.parentId);
|
|
233
|
+
const before = namespace.path;
|
|
234
|
+
const after = parent ? `${parent.path}/${slug(name)}` : slug(name);
|
|
235
|
+
if (after !== before && state.namespaces.some((other) => other.path === after))
|
|
236
|
+
throw new LocalError(`The group "${after}" already exists`, 409, 'already_exists');
|
|
237
|
+
namespace.name = name;
|
|
238
|
+
for (const other of state.namespaces) {
|
|
239
|
+
if (other.id === namespace.id)
|
|
240
|
+
other.path = after;
|
|
241
|
+
else if (other.path.startsWith(`${before}/`))
|
|
242
|
+
other.path = `${after}${other.path.slice(before.length)}`;
|
|
243
|
+
}
|
|
244
|
+
});
|
|
245
|
+
return undefined;
|
|
246
|
+
}
|
|
247
|
+
// ── repositories ─────────────────────────────────────────────────────────
|
|
248
|
+
async createRepository({ token, name, namespaceId, topics = [], defaultBranch = 'main' }) {
|
|
249
|
+
const user = await this.user(token);
|
|
250
|
+
// first the id and the group are settled; the repository exists in the state only once its git does (a cut in between leaves a
|
|
251
|
+
// folder nobody refers to, which costs disk; the other way round it leaves a repository that answers 500)
|
|
252
|
+
const reserved = await this.store.update((state) => {
|
|
253
|
+
let namespace;
|
|
254
|
+
if (namespaceId === undefined || namespaceId === null) {
|
|
255
|
+
// without a group: the person's own
|
|
256
|
+
const own = state.namespaces.find((candidate) => candidate.path === slug(user.username));
|
|
257
|
+
namespace = own ?? (() => {
|
|
258
|
+
const made = { id: state.next++, name: user.username, path: slug(user.username), parentId: null, owner: user.username };
|
|
259
|
+
state.namespaces.push(made);
|
|
260
|
+
return made;
|
|
261
|
+
})();
|
|
262
|
+
}
|
|
263
|
+
else {
|
|
264
|
+
namespace = this.namespaceOf(state, namespaceId);
|
|
265
|
+
}
|
|
266
|
+
if (this.levelOnNamespace(state, namespace, user) < WRITE_ACCESS)
|
|
267
|
+
throw new LocalError('You are not allowed to create repositories here', 403);
|
|
268
|
+
if (state.repositories.some((repository) => repository.namespaceId === namespace.id && slug(repository.name) === slug(name))) {
|
|
269
|
+
throw new LocalError(`The repository "${namespace.path}/${slug(name)}" already exists`, 409, 'already_exists');
|
|
270
|
+
}
|
|
271
|
+
return { id: state.next++, namespaceId: namespace.id };
|
|
272
|
+
});
|
|
273
|
+
const record = {
|
|
274
|
+
id: reserved.id, name, namespaceId: reserved.namespaceId, description: '', topics: [...new Set(topics)], defaultBranch, owner: user.username,
|
|
275
|
+
members: [], changeRequests: [], nextChangeRequest: 1, hooks: [], createdAt: new Date().toISOString()
|
|
276
|
+
};
|
|
277
|
+
const dir = this.dirOf(record);
|
|
278
|
+
try {
|
|
279
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
280
|
+
await gitOk(dir, ['init', '--bare', '--quiet', `--initial-branch=${defaultBranch}`]);
|
|
281
|
+
// a repository starts with one (empty) commit on its first branch, like the hosts that initialise it
|
|
282
|
+
const commit = await gitText(dir, ['commit-tree', EMPTY_TREE, '-m', 'Initial commit'], { env: identity(user.username) });
|
|
283
|
+
await gitOk(dir, ['update-ref', `refs/heads/${defaultBranch}`, commit]);
|
|
284
|
+
await this.store.update((state) => {
|
|
285
|
+
// (the same name could have been taken while git worked)
|
|
286
|
+
if (state.repositories.some((other) => other.namespaceId === record.namespaceId && slug(other.name) === slug(name))) {
|
|
287
|
+
throw new LocalError(`The repository "${slug(name)}" already exists`, 409, 'already_exists');
|
|
288
|
+
}
|
|
289
|
+
this.namespaceOf(state, record.namespaceId);
|
|
290
|
+
state.repositories.push(record);
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
catch (error) {
|
|
294
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
295
|
+
throw error;
|
|
296
|
+
}
|
|
297
|
+
// (undoing a creation removes it for good: there is nothing to keep)
|
|
298
|
+
this.remember(async () => {
|
|
299
|
+
await this.store.update((state) => { state.repositories = state.repositories.filter((repository) => repository.id !== record.id); });
|
|
300
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
301
|
+
});
|
|
302
|
+
const state = await this.store.read((current) => current);
|
|
303
|
+
return this.toRepository(state, record);
|
|
304
|
+
}
|
|
305
|
+
listPendingDeletion() {
|
|
306
|
+
return Promise.resolve([]);
|
|
307
|
+
}
|
|
308
|
+
restoreRepository() {
|
|
309
|
+
return Promise.reject(new LocalError('This host deletes at once: there is nothing to restore', 400));
|
|
310
|
+
}
|
|
311
|
+
restoreNamespace() {
|
|
312
|
+
return Promise.reject(new LocalError('This host deletes at once: there is nothing to restore', 400));
|
|
313
|
+
}
|
|
314
|
+
async deleteRepository({ token, id }) {
|
|
315
|
+
const { record } = await this.open(token, id, ACCESS.OWNER);
|
|
316
|
+
await this.store.update((state) => { state.repositories = state.repositories.filter((repository) => repository.id !== record.id); });
|
|
317
|
+
const moved = [this.toTrash(record)];
|
|
318
|
+
this.remember(() => this.restore({ repositories: [record], namespaces: [], moved }));
|
|
319
|
+
return undefined;
|
|
320
|
+
}
|
|
321
|
+
// ── the trash: what is deleted waits here, for the caller to change its mind (rollback) and for an administrator to find it ──
|
|
322
|
+
get trashDir() {
|
|
323
|
+
return path.join(this.store.dir, 'trash');
|
|
324
|
+
}
|
|
325
|
+
/** Moves the git of a repository out of the way; returns where it went (null when there was nothing). */
|
|
326
|
+
toTrash(record) {
|
|
327
|
+
const from = this.dirOf(record);
|
|
328
|
+
if (!fs.existsSync(from))
|
|
329
|
+
return null;
|
|
330
|
+
fs.mkdirSync(this.trashDir, { recursive: true });
|
|
331
|
+
const to = path.join(this.trashDir, `${record.id}-${Date.now()}.git`);
|
|
332
|
+
fs.renameSync(from, to);
|
|
333
|
+
this.purgeTrash();
|
|
334
|
+
return { from, to };
|
|
335
|
+
}
|
|
336
|
+
/** Forgets what has been in the trash for longer than `maxAgeMs` (a week by default). */
|
|
337
|
+
purgeTrash(maxAgeMs = 7 * 24 * 60 * 60 * 1000) {
|
|
338
|
+
if (!fs.existsSync(this.trashDir))
|
|
339
|
+
return;
|
|
340
|
+
for (const name of fs.readdirSync(this.trashDir)) {
|
|
341
|
+
const entry = path.join(this.trashDir, name);
|
|
342
|
+
try {
|
|
343
|
+
if (Date.now() - fs.statSync(entry).mtimeMs > maxAgeMs)
|
|
344
|
+
fs.rmSync(entry, { recursive: true, force: true });
|
|
345
|
+
}
|
|
346
|
+
catch { /* somebody else took it */ }
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
async restore({ repositories, namespaces, moved }) {
|
|
350
|
+
for (const entry of moved)
|
|
351
|
+
if (entry && fs.existsSync(entry.to) && !fs.existsSync(entry.from))
|
|
352
|
+
fs.renameSync(entry.to, entry.from);
|
|
353
|
+
await this.store.update((state) => {
|
|
354
|
+
for (const namespace of namespaces)
|
|
355
|
+
if (!state.namespaces.some((other) => other.id === namespace.id))
|
|
356
|
+
state.namespaces.push(namespace);
|
|
357
|
+
for (const repository of repositories)
|
|
358
|
+
if (!state.repositories.some((other) => other.id === repository.id))
|
|
359
|
+
state.repositories.push(repository);
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
async renameRepository({ token, id, name }) {
|
|
363
|
+
await this.open(token, id, ACCESS.MAINTAINER);
|
|
364
|
+
return this.store.update((state) => {
|
|
365
|
+
const record = this.repositoryOf(state, id);
|
|
366
|
+
if (state.repositories.some((other) => other.id !== record.id && other.namespaceId === record.namespaceId && slug(other.name) === slug(name))) {
|
|
367
|
+
throw new LocalError(`The repository "${slug(name)}" already exists`, 409, 'already_exists');
|
|
368
|
+
}
|
|
369
|
+
record.name = name;
|
|
370
|
+
return this.toRepository(state, record);
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
async getRepository({ token, id }) {
|
|
374
|
+
const { record, state } = await this.open(token, id);
|
|
375
|
+
return this.toRepository(state, record);
|
|
376
|
+
}
|
|
377
|
+
async findRepository({ token, path: repoPath }) {
|
|
378
|
+
await this.user(token);
|
|
379
|
+
return this.store.read((state) => {
|
|
380
|
+
const wanted = repoPath.replace(/\.git$/, '');
|
|
381
|
+
const found = state.repositories.find((repository) => this.pathOf(state, repository) === wanted);
|
|
382
|
+
return found ? this.toRepository(state, found) : null;
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
async listRepositories({ token, topic }) {
|
|
386
|
+
await this.user(token);
|
|
387
|
+
return this.store.read((state) => state.repositories.filter((repository) => repository.topics.includes(topic)).map((repository) => this.toRepository(state, repository)));
|
|
388
|
+
}
|
|
389
|
+
async addTopic({ token, id, topic }) {
|
|
390
|
+
await this.open(token, id, WRITE_ACCESS);
|
|
391
|
+
await this.store.update((state) => {
|
|
392
|
+
const record = this.repositoryOf(state, id);
|
|
393
|
+
if (!record.topics.includes(topic))
|
|
394
|
+
record.topics.push(topic);
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
async setDefaultBranch({ token, id, branch }) {
|
|
398
|
+
const { record, dir } = await this.open(token, id, ACCESS.MAINTAINER);
|
|
399
|
+
await this.mustResolve(dir, `refs/heads/${branch}`);
|
|
400
|
+
await gitOk(dir, ['symbolic-ref', 'HEAD', `refs/heads/${branch}`]);
|
|
401
|
+
await this.store.update((state) => { this.repositoryOf(state, record.id).defaultBranch = branch; });
|
|
402
|
+
return undefined;
|
|
403
|
+
}
|
|
404
|
+
async getMembers({ token, id }) {
|
|
405
|
+
const { record } = await this.open(token, id);
|
|
406
|
+
const members = new Map([[record.owner, ACCESS.OWNER]]);
|
|
407
|
+
for (const member of record.members)
|
|
408
|
+
members.set(member.username, member.accessLevel);
|
|
409
|
+
return [...members].map(([username, accessLevel]) => ({ username, accessLevel }));
|
|
410
|
+
}
|
|
411
|
+
async getAccessLevel({ token, id, username }) {
|
|
412
|
+
await this.user(token);
|
|
413
|
+
const state = await this.store.read((current) => current);
|
|
414
|
+
const record = state.repositories.find((repository) => repository.id === Number(id) || this.pathOf(state, repository) === id);
|
|
415
|
+
if (!record)
|
|
416
|
+
return 0;
|
|
417
|
+
const user = await this.resolveUser(token);
|
|
418
|
+
if (user?.username === username && user.admin)
|
|
419
|
+
return ACCESS.OWNER;
|
|
420
|
+
return this.levelFor(state, record, { username });
|
|
421
|
+
}
|
|
422
|
+
// ── files, commits, archives ─────────────────────────────────────────────
|
|
423
|
+
async revisionOf(dir, ref, filePath) {
|
|
424
|
+
return gitText(dir, ['log', '-1', '--format=%H', ref, '--', filePath]);
|
|
425
|
+
}
|
|
426
|
+
async getFile({ token, id, path: filePath, ref }) {
|
|
427
|
+
const { dir } = await this.open(token, id);
|
|
428
|
+
const blob = await git(dir, ['cat-file', 'blob', `${ref}:${filePath}`]);
|
|
429
|
+
if (blob.code !== 0)
|
|
430
|
+
throw new LocalError(`There is no file "${filePath}" at ${ref}`, 404);
|
|
431
|
+
return { path: filePath, name: path.posix.basename(filePath), content: blob.stdout.toString('base64'), encoding: 'base64', revision: await this.revisionOf(dir, ref, filePath) };
|
|
432
|
+
}
|
|
433
|
+
getFileRevision(args) {
|
|
434
|
+
return this.getFile(args);
|
|
435
|
+
}
|
|
436
|
+
async readFile({ token, id, path: filePath, ref }) {
|
|
437
|
+
const { dir } = await this.open(token, id);
|
|
438
|
+
const blob = await git(dir, ['cat-file', 'blob', `${ref}:${filePath}`]);
|
|
439
|
+
return blob.code === 0 ? blob.stdout : null;
|
|
440
|
+
}
|
|
441
|
+
async listFiles({ token, id, ref }) {
|
|
442
|
+
const { dir } = await this.open(token, id);
|
|
443
|
+
const listing = await git(dir, ['ls-tree', '-r', '--name-only', '-z', ref]);
|
|
444
|
+
if (listing.code !== 0)
|
|
445
|
+
throw new LocalError(`There is no "${ref}" in this repository`, 404);
|
|
446
|
+
return listing.stdout.toString('utf8').split('\0').filter(Boolean);
|
|
447
|
+
}
|
|
448
|
+
async createFile({ token, id, path: filePath, branch, content }) {
|
|
449
|
+
return this.commit({ token, id, branch, message: `Create ${filePath}`, actions: [{ action: 'create', path: filePath, content }] });
|
|
450
|
+
}
|
|
451
|
+
async saveFile({ token, id, path: filePath, branch, content }) {
|
|
452
|
+
const exists = (await this.readFile({ token, id, path: filePath, ref: branch })) !== null;
|
|
453
|
+
return this.commit({ token, id, branch, message: `Update ${filePath}`, actions: [{ action: exists ? 'update' : 'create', path: filePath, content }] });
|
|
454
|
+
}
|
|
455
|
+
async commit({ token, id, branch, message, actions, track = true }) {
|
|
456
|
+
const { dir, user } = await this.open(token, id, WRITE_ACCESS);
|
|
457
|
+
const head = await this.resolveCommit(dir, `refs/heads/${branch}`);
|
|
458
|
+
if (!head)
|
|
459
|
+
throw new LocalError(`There is no branch "${branch}"`, 404);
|
|
460
|
+
const index = path.join(os.tmpdir(), `linea-local-index-${process.pid}-${crypto.randomBytes(6).toString('hex')}`);
|
|
461
|
+
const env = { GIT_INDEX_FILE: index, ...identity(user.username) };
|
|
462
|
+
try {
|
|
463
|
+
await gitOk(dir, ['read-tree', head], { env });
|
|
464
|
+
for (const action of actions) {
|
|
465
|
+
const present = (await gitText(dir, ['ls-files', '--', action.path], { env })) !== '';
|
|
466
|
+
if (action.action === 'create' && present)
|
|
467
|
+
throw new LocalError(`A file named "${action.path}" already exists`, 400);
|
|
468
|
+
if (action.action !== 'create' && !present)
|
|
469
|
+
throw new LocalError(`There is no file "${action.path}" on ${branch}`, 404);
|
|
470
|
+
if (action.expectedRevision && action.action !== 'create' && await this.revisionOf(dir, head, action.path) !== action.expectedRevision) {
|
|
471
|
+
throw new LocalError(`"${action.path}" changed since you read it`, 409);
|
|
472
|
+
}
|
|
473
|
+
if (action.action === 'delete') {
|
|
474
|
+
// mode 0 takes the entry out of the index (`--force-remove` wants a work tree, and these repositories are bare)
|
|
475
|
+
await gitOk(dir, ['update-index', '--index-info'], { env, input: `0 ${'0'.repeat(40)}\t${action.path}\n` });
|
|
476
|
+
continue;
|
|
477
|
+
}
|
|
478
|
+
const bytes = action.encoding === 'base64' ? Buffer.from(action.content ?? '', 'base64') : Buffer.from(action.content ?? '', 'utf8');
|
|
479
|
+
const blob = await gitText(dir, ['hash-object', '-w', '--stdin'], { env, input: bytes });
|
|
480
|
+
await gitOk(dir, ['update-index', '--add', '--cacheinfo', `100644,${blob},${action.path}`], { env });
|
|
481
|
+
}
|
|
482
|
+
const tree = await gitText(dir, ['write-tree'], { env });
|
|
483
|
+
if (tree === await gitText(dir, ['rev-parse', `${head}^{tree}`]))
|
|
484
|
+
return { id: head };
|
|
485
|
+
const commit = await gitText(dir, ['commit-tree', tree, '-p', head, '-m', message], { env });
|
|
486
|
+
const moved = await git(dir, ['update-ref', `refs/heads/${branch}`, commit, head]);
|
|
487
|
+
if (moved.code !== 0)
|
|
488
|
+
throw new LocalError(`"${branch}" moved while it was being changed`, 409);
|
|
489
|
+
if (track)
|
|
490
|
+
this.remember(() => git(dir, ['update-ref', `refs/heads/${branch}`, head, commit]));
|
|
491
|
+
return { id: commit };
|
|
492
|
+
}
|
|
493
|
+
finally {
|
|
494
|
+
fs.rmSync(index, { force: true });
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
async downloadArchive({ token, id, ref }) {
|
|
498
|
+
const { dir, record } = await this.open(token, id);
|
|
499
|
+
const target = await this.mustResolve(dir, ref ?? record.defaultBranch);
|
|
500
|
+
// inside one folder named after the repository and the commit, as the other hosts do (what reads an archive looks for it)
|
|
501
|
+
const folder = `${slug(record.name)}-${target.slice(0, 8)}/`;
|
|
502
|
+
const child = spawn('git', ['archive', '--format=zip', `--prefix=${folder}`, target], { cwd: dir, env: cleanEnv({ GIT_DIR: dir }), windowsHide: true });
|
|
503
|
+
// a git that fails ends the stream with the error, not with an archive that looks complete
|
|
504
|
+
const out = new PassThrough();
|
|
505
|
+
const errors = [];
|
|
506
|
+
child.stderr.on('data', (chunk) => errors.push(chunk));
|
|
507
|
+
child.stdout.pipe(out, { end: false });
|
|
508
|
+
child.on('error', (error) => out.destroy(error));
|
|
509
|
+
child.on('close', (code) => {
|
|
510
|
+
if (code === 0)
|
|
511
|
+
out.end();
|
|
512
|
+
else
|
|
513
|
+
out.destroy(new LocalError(`git archive failed: ${Buffer.concat(errors).toString('utf8').trim() || `exit ${code}`}`, 500));
|
|
514
|
+
});
|
|
515
|
+
return out;
|
|
516
|
+
}
|
|
517
|
+
async compare({ token, id, from, to }) {
|
|
518
|
+
const { dir } = await this.open(token, id);
|
|
519
|
+
const [source, target] = [await this.resolveCommit(dir, from), await this.resolveCommit(dir, to)];
|
|
520
|
+
if (!source || !target)
|
|
521
|
+
throw new LocalError('There is no such branch to compare', 404);
|
|
522
|
+
const base = (await git(dir, ['merge-base', source, target])).stdout.toString('utf8').trim() || source;
|
|
523
|
+
const log = await git(dir, ['log', '-z', '--format=%H%x00%an%x00%aI%x00%s%x00%b', `${base}..${target}`]);
|
|
524
|
+
const commits = parseLog(log.stdout.toString('utf8'));
|
|
525
|
+
return { commits, files: parseGitDiff(await gitText(dir, ['diff', '-M', '--no-color', '--no-ext-diff', base, target])) };
|
|
526
|
+
}
|
|
527
|
+
async getCommits({ token, id, ref, perPage = 20 }) {
|
|
528
|
+
const { dir } = await this.open(token, id);
|
|
529
|
+
const log = await git(dir, ['log', '-z', `-n${perPage}`, '--format=%H%x00%an%x00%aI%x00%s%x00%b', '--end-of-options', ref]);
|
|
530
|
+
if (log.code !== 0)
|
|
531
|
+
return [];
|
|
532
|
+
return parseLog(log.stdout.toString('utf8'));
|
|
533
|
+
}
|
|
534
|
+
// ── branches and tags ────────────────────────────────────────────────────
|
|
535
|
+
async createBranch({ token, id, branch, ref, track = true }) {
|
|
536
|
+
const { dir } = await this.open(token, id, WRITE_ACCESS);
|
|
537
|
+
if (await this.resolveCommit(dir, `refs/heads/${branch}`))
|
|
538
|
+
throw new LocalError(`The branch "${branch}" already exists`, 400, 'already_exists');
|
|
539
|
+
const commit = await this.mustResolve(dir, ref);
|
|
540
|
+
await gitOk(dir, ['update-ref', `refs/heads/${branch}`, commit]);
|
|
541
|
+
if (track)
|
|
542
|
+
this.remember(() => git(dir, ['update-ref', '-d', `refs/heads/${branch}`]));
|
|
543
|
+
return undefined;
|
|
544
|
+
}
|
|
545
|
+
async listBranches({ token, id }) {
|
|
546
|
+
const { dir } = await this.open(token, id);
|
|
547
|
+
return (await gitText(dir, ['for-each-ref', '--format=%(refname:short)', 'refs/heads'])).split('\n').map((line) => line.trim()).filter(Boolean);
|
|
548
|
+
}
|
|
549
|
+
async getBranch({ token, id, branch }) {
|
|
550
|
+
const { dir } = await this.open(token, id);
|
|
551
|
+
if (!await this.resolveCommit(dir, `refs/heads/${branch}`))
|
|
552
|
+
throw new LocalError(`There is no branch "${branch}"`, 404);
|
|
553
|
+
const [last] = await this.getCommits({ token, id, ref: `refs/heads/${branch}`, perPage: 1 });
|
|
554
|
+
return { name: branch, lastCommit: last ?? null };
|
|
555
|
+
}
|
|
556
|
+
async listTags({ token, id }) {
|
|
557
|
+
const { dir } = await this.open(token, id);
|
|
558
|
+
const refs = await gitText(dir, ['for-each-ref', '--format=%(refname:short)', 'refs/tags']);
|
|
559
|
+
return refs.split('\n').filter(Boolean).map((name) => ({ name }));
|
|
560
|
+
}
|
|
561
|
+
async getTag({ token, id, tag }) {
|
|
562
|
+
const { dir } = await this.open(token, id);
|
|
563
|
+
const shown = await git(dir, ['for-each-ref', '--format=%(objecttype)%00%(contents)', `refs/tags/${tag}`]);
|
|
564
|
+
const text = shown.stdout.toString('utf8');
|
|
565
|
+
if (shown.code !== 0 || text.trim() === '')
|
|
566
|
+
return null;
|
|
567
|
+
const [kind = '', ...contents] = text.split('\0');
|
|
568
|
+
const commitId = await this.mustResolve(dir, `refs/tags/${tag}`);
|
|
569
|
+
return { name: tag, commitId, message: kind === 'tag' ? contents.join('\0').trim() || null : null };
|
|
570
|
+
}
|
|
571
|
+
async createTag({ token, id, tag, ref, message }) {
|
|
572
|
+
const { dir, user } = await this.open(token, id, WRITE_ACCESS);
|
|
573
|
+
if (await this.resolveCommit(dir, `refs/tags/${tag}`))
|
|
574
|
+
throw new LocalError(`The tag "${tag}" already exists`, 409, 'already_exists');
|
|
575
|
+
const commit = await this.mustResolve(dir, ref);
|
|
576
|
+
if (message)
|
|
577
|
+
await gitOk(dir, ['tag', '-a', '-m', message, tag, commit], { env: identity(user.username) });
|
|
578
|
+
else
|
|
579
|
+
await gitOk(dir, ['update-ref', `refs/tags/${tag}`, commit]);
|
|
580
|
+
this.remember(() => git(dir, ['update-ref', '-d', `refs/tags/${tag}`]));
|
|
581
|
+
return undefined;
|
|
582
|
+
}
|
|
583
|
+
// ── releases ─────────────────────────────────────────────────────────────
|
|
584
|
+
// Kept in the state, by tag, next to the issues.
|
|
585
|
+
toRelease(record) {
|
|
586
|
+
// (there is no page for it on this host: the client shows no link for an empty address)
|
|
587
|
+
return { tag: record.tag, name: record.name, description: record.description, createdAt: record.createdAt, url: '', prerelease: record.prerelease };
|
|
588
|
+
}
|
|
589
|
+
async createRelease({ token, id, tag, name, description = '', prerelease = false }) {
|
|
590
|
+
const { record } = await this.open(token, id, WRITE_ACCESS);
|
|
591
|
+
// (the exact tag: a revision such as `v1~1` would resolve to a commit without being a tag)
|
|
592
|
+
if (!await this.getTag({ token, id, tag }))
|
|
593
|
+
throw new LocalError(`There is no tag "${tag}"`, 404);
|
|
594
|
+
const made = await this.store.update((current) => {
|
|
595
|
+
const repository = this.repositoryOf(current, record.id);
|
|
596
|
+
if ((repository.releases ?? []).some((release) => release.tag === tag))
|
|
597
|
+
throw new LocalError(`The release of the tag "${tag}" already exists`, 409, 'already_exists');
|
|
598
|
+
const release = { tag, name: name?.trim() || tag, description, prerelease, createdAt: new Date().toISOString() };
|
|
599
|
+
repository.releases = [...(repository.releases ?? []), release];
|
|
600
|
+
return release;
|
|
601
|
+
});
|
|
602
|
+
this.remember(() => this.store.update((current) => {
|
|
603
|
+
const repository = current.repositories.find((candidate) => candidate.id === record.id);
|
|
604
|
+
if (repository)
|
|
605
|
+
repository.releases = (repository.releases ?? []).filter((release) => release.tag !== tag);
|
|
606
|
+
}));
|
|
607
|
+
return this.toRelease(made);
|
|
608
|
+
}
|
|
609
|
+
async getRelease({ token, id, tag }) {
|
|
610
|
+
const { record } = await this.open(token, id);
|
|
611
|
+
const found = (record.releases ?? []).find((release) => release.tag === tag);
|
|
612
|
+
return found ? this.toRelease(found) : null;
|
|
613
|
+
}
|
|
614
|
+
async listReleases({ token, id }) {
|
|
615
|
+
const { record } = await this.open(token, id);
|
|
616
|
+
return [...(record.releases ?? [])].reverse().map((release) => this.toRelease(release));
|
|
617
|
+
}
|
|
618
|
+
async updateRelease({ token, id, tag, changes }) {
|
|
619
|
+
const { record } = await this.open(token, id, WRITE_ACCESS);
|
|
620
|
+
const updated = await this.store.update((current) => {
|
|
621
|
+
const release = (this.repositoryOf(current, record.id).releases ?? []).find((candidate) => candidate.tag === tag);
|
|
622
|
+
if (!release)
|
|
623
|
+
throw new LocalError(`There is no release of the tag "${tag}"`, 404);
|
|
624
|
+
if (changes.name !== undefined)
|
|
625
|
+
release.name = changes.name.trim() || tag;
|
|
626
|
+
if (changes.description !== undefined)
|
|
627
|
+
release.description = changes.description;
|
|
628
|
+
if (changes.prerelease !== undefined)
|
|
629
|
+
release.prerelease = changes.prerelease;
|
|
630
|
+
return release;
|
|
631
|
+
});
|
|
632
|
+
return this.toRelease(updated);
|
|
633
|
+
}
|
|
634
|
+
// ── change requests ──────────────────────────────────────────────────────
|
|
635
|
+
async conflicts(dir, target, source) {
|
|
636
|
+
const [a, b] = [await this.resolveCommit(dir, `refs/heads/${target}`), await this.resolveCommit(dir, `refs/heads/${source}`)];
|
|
637
|
+
if (!a || !b)
|
|
638
|
+
return false;
|
|
639
|
+
return (await git(dir, ['merge-tree', '--write-tree', a, b])).code === 1;
|
|
640
|
+
}
|
|
641
|
+
async toChangeRequest(dir, web, request) {
|
|
642
|
+
return {
|
|
643
|
+
number: request.number,
|
|
644
|
+
title: request.title,
|
|
645
|
+
sourceBranch: request.sourceBranch,
|
|
646
|
+
targetBranch: request.targetBranch,
|
|
647
|
+
// (there is no page for it on this host: the client shows no link for an empty address)
|
|
648
|
+
webUrl: '',
|
|
649
|
+
hasConflicts: request.state === 'opened' && await this.conflicts(dir, request.targetBranch, request.sourceBranch),
|
|
650
|
+
state: request.state,
|
|
651
|
+
createdAt: request.createdAt
|
|
652
|
+
};
|
|
653
|
+
}
|
|
654
|
+
async createChangeRequest({ token, id, title, sourceBranch, targetBranch }) {
|
|
655
|
+
const { dir, record, state, user } = await this.open(token, id, WRITE_ACCESS);
|
|
656
|
+
await this.mustResolve(dir, `refs/heads/${sourceBranch}`);
|
|
657
|
+
await this.mustResolve(dir, `refs/heads/${targetBranch}`);
|
|
658
|
+
const request = await this.store.update((current) => {
|
|
659
|
+
const repository = this.repositoryOf(current, record.id);
|
|
660
|
+
// the ones that are over are not kept for ever: the state is read whole at every call
|
|
661
|
+
const horizon = Date.now() - CLOSED_KEPT_MS;
|
|
662
|
+
repository.changeRequests = repository.changeRequests.filter((kept) => kept.state === 'opened' || Date.parse(kept.createdAt) > horizon);
|
|
663
|
+
const made = { number: repository.nextChangeRequest++, title, sourceBranch, targetBranch, state: 'opened', createdAt: new Date().toISOString(), author: user.username };
|
|
664
|
+
repository.changeRequests.push(made);
|
|
665
|
+
return made;
|
|
666
|
+
});
|
|
667
|
+
return this.toChangeRequest(dir, this.toRepository(state, record).webUrl, request);
|
|
668
|
+
}
|
|
669
|
+
/** Closes a change request without merging it (it was not wanted). A merged or closed one stays as it is. */
|
|
670
|
+
async closeChangeRequest({ token, id, number }) {
|
|
671
|
+
const { record } = await this.open(token, id, WRITE_ACCESS);
|
|
672
|
+
await this.store.update((state) => {
|
|
673
|
+
const request = this.repositoryOf(state, record.id).changeRequests.find((candidate) => candidate.number === number);
|
|
674
|
+
if (!request)
|
|
675
|
+
throw new LocalError(`There is no change request ${number}`, 404);
|
|
676
|
+
if (request.state === 'opened')
|
|
677
|
+
request.state = 'closed';
|
|
678
|
+
});
|
|
679
|
+
}
|
|
680
|
+
async createOrRenameChangeRequest({ token, id, title, sourceBranch, targetBranch }) {
|
|
681
|
+
const { dir, record, state } = await this.open(token, id, WRITE_ACCESS);
|
|
682
|
+
const target = targetBranch ?? record.defaultBranch;
|
|
683
|
+
const renamed = await this.store.update((current) => {
|
|
684
|
+
const standing = this.repositoryOf(current, record.id).changeRequests.find((request) => request.state === 'opened' && request.sourceBranch === sourceBranch && request.targetBranch === target);
|
|
685
|
+
if (standing)
|
|
686
|
+
standing.title = title;
|
|
687
|
+
return standing ?? null;
|
|
688
|
+
});
|
|
689
|
+
if (renamed)
|
|
690
|
+
return this.toChangeRequest(dir, this.toRepository(state, record).webUrl, renamed);
|
|
691
|
+
return this.createChangeRequest({ token, id, title, sourceBranch, targetBranch: target });
|
|
692
|
+
}
|
|
693
|
+
async listChangeRequests({ token, id, state: wanted = 'opened', targetBranch }) {
|
|
694
|
+
const { dir, record, state } = await this.open(token, id);
|
|
695
|
+
const web = this.toRepository(state, record).webUrl;
|
|
696
|
+
const requests = record.changeRequests.filter((request) => (wanted === 'all' || request.state === wanted) && (!targetBranch || request.targetBranch === targetBranch));
|
|
697
|
+
return Promise.all(requests.map((request) => this.toChangeRequest(dir, web, request)));
|
|
698
|
+
}
|
|
699
|
+
/**
|
|
700
|
+
* Merges a change request. Answers whether it has conflicts (`true`: nothing was merged, it has to be resolved by hand). Anything
|
|
701
|
+
* else that goes wrong is an error, not a conflict: git too old, a repository that cannot be read.
|
|
702
|
+
*/
|
|
703
|
+
async mergeChangeRequest({ token, id, number, deleteSourceBranch = false }) {
|
|
704
|
+
const { dir, record, user } = await this.open(token, id, WRITE_ACCESS);
|
|
705
|
+
const request = record.changeRequests.find((candidate) => candidate.number === number);
|
|
706
|
+
if (!request)
|
|
707
|
+
throw new LocalError(`There is no change request ${number}`, 404);
|
|
708
|
+
if (request.state !== 'opened')
|
|
709
|
+
return false;
|
|
710
|
+
const targetRef = `refs/heads/${request.targetBranch}`;
|
|
711
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
712
|
+
const [target, source] = [await this.mustResolve(dir, targetRef), await this.mustResolve(dir, `refs/heads/${request.sourceBranch}`)];
|
|
713
|
+
// already in the target: nothing to merge, only to close
|
|
714
|
+
const contained = (await git(dir, ['merge-base', '--is-ancestor', source, target])).code === 0;
|
|
715
|
+
if (!contained) {
|
|
716
|
+
const merged = await git(dir, ['merge-tree', '--write-tree', target, source]);
|
|
717
|
+
if (merged.code === 1)
|
|
718
|
+
return true;
|
|
719
|
+
if (merged.code !== 0)
|
|
720
|
+
throw new LocalError(`git merge-tree failed (it needs git 2.38 or newer): ${merged.stderr.trim() || `exit ${merged.code}`}`, 500);
|
|
721
|
+
const tree = merged.stdout.toString('utf8').split('\n')[0]?.trim() ?? '';
|
|
722
|
+
const commit = await gitText(dir, ['commit-tree', tree, '-p', target, '-p', source, '-m', `Merge branch '${request.sourceBranch}' into '${request.targetBranch}'`], { env: identity(user.username) });
|
|
723
|
+
// the target moves only if nobody moved it meanwhile; if they did, it is merged again over what is there now
|
|
724
|
+
const moved = await git(dir, ['update-ref', targetRef, commit, target]);
|
|
725
|
+
if (moved.code !== 0)
|
|
726
|
+
continue;
|
|
727
|
+
}
|
|
728
|
+
if (deleteSourceBranch)
|
|
729
|
+
await git(dir, ['update-ref', '-d', `refs/heads/${request.sourceBranch}`]);
|
|
730
|
+
await this.store.update((current) => {
|
|
731
|
+
const standing = this.repositoryOf(current, record.id).changeRequests.find((candidate) => candidate.number === number);
|
|
732
|
+
if (standing)
|
|
733
|
+
standing.state = 'merged';
|
|
734
|
+
});
|
|
735
|
+
return false;
|
|
736
|
+
}
|
|
737
|
+
throw new LocalError(`"${request.targetBranch}" kept moving while the change request was merged: try again`, 409);
|
|
738
|
+
}
|
|
739
|
+
// ── issues ───────────────────────────────────────────────────────────────
|
|
740
|
+
// Kept in the state next to the change requests. Labels and milestones are free text here: there is no list to choose from, so the
|
|
741
|
+
// ones offered are the ones the issues already use.
|
|
742
|
+
capabilities() {
|
|
743
|
+
return {
|
|
744
|
+
issues: { labels: true, milestones: true, assignees: true, closingWords: true },
|
|
745
|
+
templates: { editable: true },
|
|
746
|
+
mergeRequests: { labels: true, reviewers: true, approvals: false, resolvableThreads: true, squash: true },
|
|
747
|
+
deletion: { namespaceIsRepository: false, delayed: false },
|
|
748
|
+
releases: { prerelease: true }
|
|
749
|
+
};
|
|
750
|
+
}
|
|
751
|
+
toIssue(record) {
|
|
752
|
+
return {
|
|
753
|
+
number: record.number, title: record.title, description: record.description, state: record.state, author: record.author,
|
|
754
|
+
assignees: [...record.assignees], labels: [...record.labels], milestone: record.milestone,
|
|
755
|
+
createdAt: record.createdAt, updatedAt: record.updatedAt, closedAt: record.closedAt,
|
|
756
|
+
// (there is no page for it on this host: the client shows no link for an empty address)
|
|
757
|
+
webUrl: '', commentCount: record.comments.length
|
|
758
|
+
};
|
|
759
|
+
}
|
|
760
|
+
issueOf(record, number) {
|
|
761
|
+
const found = (record.issues ?? []).find((candidate) => candidate.number === number);
|
|
762
|
+
if (!found)
|
|
763
|
+
throw new LocalError(`There is no issue ${number}`, 404);
|
|
764
|
+
return found;
|
|
765
|
+
}
|
|
766
|
+
cleanList(values) {
|
|
767
|
+
return [...new Set((values ?? []).map((value) => String(value).trim()).filter(Boolean))];
|
|
768
|
+
}
|
|
769
|
+
async listIssues({ token, id, filter = {} }) {
|
|
770
|
+
const { record } = await this.open(token, id);
|
|
771
|
+
const { state: wanted = 'opened', author, assignee, labels = [], milestone, search } = filter;
|
|
772
|
+
const perPage = Math.min(Math.max(filter.perPage ?? 20, 1), 100);
|
|
773
|
+
const page = Math.max(filter.page ?? 1, 1);
|
|
774
|
+
const needle = search?.trim().toLowerCase();
|
|
775
|
+
const matching = (record.issues ?? [])
|
|
776
|
+
.filter((issue) => (wanted === 'all' || issue.state === wanted)
|
|
777
|
+
&& (!author || issue.author === author)
|
|
778
|
+
&& (!assignee || issue.assignees.includes(assignee))
|
|
779
|
+
&& labels.every((label) => issue.labels.includes(label))
|
|
780
|
+
&& (!milestone || issue.milestone === milestone)
|
|
781
|
+
&& (!needle || issue.title.toLowerCase().includes(needle) || issue.description.toLowerCase().includes(needle)))
|
|
782
|
+
.sort((a, b) => b.number - a.number);
|
|
783
|
+
const items = matching.slice((page - 1) * perPage, page * perPage).map((issue) => this.toIssue(issue));
|
|
784
|
+
return { items, page, perPage, hasMore: matching.length > page * perPage };
|
|
785
|
+
}
|
|
786
|
+
async getIssue({ token, id, number }) {
|
|
787
|
+
const { record } = await this.open(token, id);
|
|
788
|
+
return this.toIssue(this.issueOf(record, number));
|
|
789
|
+
}
|
|
790
|
+
async createIssue({ token, id, title, description = '', labels, assignees, milestone }) {
|
|
791
|
+
const { record, user } = await this.open(token, id);
|
|
792
|
+
if (!title.trim())
|
|
793
|
+
throw new LocalError('An issue needs a title', 400);
|
|
794
|
+
const made = await this.store.update((current) => {
|
|
795
|
+
const repository = this.repositoryOf(current, record.id);
|
|
796
|
+
const now = new Date().toISOString();
|
|
797
|
+
const issue = {
|
|
798
|
+
number: repository.nextIssue ?? 1, title: title.trim(), description, state: 'opened', author: user.username,
|
|
799
|
+
assignees: this.cleanList(assignees), labels: this.cleanList(labels), milestone: milestone?.trim() || null,
|
|
800
|
+
createdAt: now, updatedAt: now, closedAt: null, comments: [], nextComment: 1
|
|
801
|
+
};
|
|
802
|
+
repository.nextIssue = issue.number + 1;
|
|
803
|
+
repository.issues = [...(repository.issues ?? []), issue];
|
|
804
|
+
return issue;
|
|
805
|
+
});
|
|
806
|
+
return this.toIssue(made);
|
|
807
|
+
}
|
|
808
|
+
async updateIssue({ token, id, number, changes }) {
|
|
809
|
+
const { record, state, user } = await this.open(token, id);
|
|
810
|
+
const level = this.levelFor(state, record, user);
|
|
811
|
+
const updated = await this.store.update((current) => {
|
|
812
|
+
const issue = this.issueOf(this.repositoryOf(current, record.id), number);
|
|
813
|
+
// anyone who can read may open an issue and write on it; changing one is for who can push, and for who wrote it
|
|
814
|
+
if (level < WRITE_ACCESS && issue.author !== user.username)
|
|
815
|
+
throw new LocalError('You are not allowed to do that here', 403);
|
|
816
|
+
if (changes.title !== undefined) {
|
|
817
|
+
if (!changes.title.trim())
|
|
818
|
+
throw new LocalError('An issue needs a title', 400);
|
|
819
|
+
issue.title = changes.title.trim();
|
|
820
|
+
}
|
|
821
|
+
if (changes.description !== undefined)
|
|
822
|
+
issue.description = changes.description;
|
|
823
|
+
if (changes.labels !== undefined)
|
|
824
|
+
issue.labels = this.cleanList(changes.labels);
|
|
825
|
+
if (changes.assignees !== undefined)
|
|
826
|
+
issue.assignees = this.cleanList(changes.assignees);
|
|
827
|
+
if (changes.milestone !== undefined)
|
|
828
|
+
issue.milestone = changes.milestone?.trim() || null;
|
|
829
|
+
if (changes.state !== undefined && changes.state !== issue.state) {
|
|
830
|
+
issue.state = changes.state;
|
|
831
|
+
issue.closedAt = changes.state === 'closed' ? new Date().toISOString() : null;
|
|
832
|
+
}
|
|
833
|
+
issue.updatedAt = new Date().toISOString();
|
|
834
|
+
return issue;
|
|
835
|
+
});
|
|
836
|
+
return this.toIssue(updated);
|
|
837
|
+
}
|
|
838
|
+
async listTemplates({ token, id, kind }) {
|
|
839
|
+
const { record } = await this.open(token, id);
|
|
840
|
+
return [...(record.templates?.[kind] ?? [])].sort((a, b) => a.name.localeCompare(b.name)).map((template) => ({ name: template.name, content: template.content }));
|
|
841
|
+
}
|
|
842
|
+
async saveTemplate({ token, id, kind, name, content }) {
|
|
843
|
+
const { record } = await this.open(token, id, ACCESS.MAINTAINER);
|
|
844
|
+
const clean = name.trim();
|
|
845
|
+
if (!clean)
|
|
846
|
+
throw new LocalError('A template needs a name', 400);
|
|
847
|
+
await this.store.update((current) => {
|
|
848
|
+
const repository = this.repositoryOf(current, record.id);
|
|
849
|
+
const templates = repository.templates ?? { issue: [], mergeRequest: [] };
|
|
850
|
+
const others = templates[kind].filter((template) => template.name !== clean);
|
|
851
|
+
repository.templates = { ...templates, [kind]: [...others, { name: clean, content }] };
|
|
852
|
+
});
|
|
853
|
+
return { name: clean, content };
|
|
854
|
+
}
|
|
855
|
+
async deleteTemplate({ token, id, kind, name }) {
|
|
856
|
+
const { record } = await this.open(token, id, ACCESS.MAINTAINER);
|
|
857
|
+
if (!(record.templates?.[kind] ?? []).some((template) => template.name === name))
|
|
858
|
+
throw new LocalError(`There is no template ${name}`, 404);
|
|
859
|
+
await this.store.update((current) => {
|
|
860
|
+
const repository = this.repositoryOf(current, record.id);
|
|
861
|
+
const templates = repository.templates ?? { issue: [], mergeRequest: [] };
|
|
862
|
+
repository.templates = { ...templates, [kind]: templates[kind].filter((template) => template.name !== name) };
|
|
863
|
+
});
|
|
864
|
+
}
|
|
865
|
+
async closeIssues(repositoryId, numbers) {
|
|
866
|
+
if (!numbers.length)
|
|
867
|
+
return [];
|
|
868
|
+
return this.store.update((current) => {
|
|
869
|
+
const repository = this.repositoryOf(current, repositoryId);
|
|
870
|
+
const closed = [];
|
|
871
|
+
const now = new Date().toISOString();
|
|
872
|
+
for (const issue of repository.issues ?? []) {
|
|
873
|
+
if (!numbers.includes(issue.number) || issue.state === 'closed')
|
|
874
|
+
continue;
|
|
875
|
+
issue.state = 'closed';
|
|
876
|
+
issue.closedAt = now;
|
|
877
|
+
issue.updatedAt = now;
|
|
878
|
+
closed.push(issue.number);
|
|
879
|
+
}
|
|
880
|
+
return closed;
|
|
881
|
+
});
|
|
882
|
+
}
|
|
883
|
+
async closeIssuesOfPush({ repositoryId, before, after }) {
|
|
884
|
+
const dir = this.store.repositoryDir(repositoryId);
|
|
885
|
+
const range = before ? `${before}..${after}` : after;
|
|
886
|
+
const log = await git(dir, ['log', '--max-count=500', '--format=%B%x00', range]);
|
|
887
|
+
if (log.code !== 0)
|
|
888
|
+
return [];
|
|
889
|
+
return this.closeIssues(repositoryId, closingIssueNumbers(...log.stdout.toString('utf8').split('\0')));
|
|
890
|
+
}
|
|
891
|
+
async defaultBranchHead(repositoryId) {
|
|
892
|
+
const record = await this.store.read((state) => this.repositoryOf(state, repositoryId));
|
|
893
|
+
const head = await git(this.store.repositoryDir(repositoryId), ['rev-parse', '--verify', '--quiet', `refs/heads/${record.defaultBranch}`]);
|
|
894
|
+
return head.code === 0 ? head.stdout.toString('utf8').trim() : null;
|
|
895
|
+
}
|
|
896
|
+
toComment(record) {
|
|
897
|
+
return { id: record.id, author: record.author, body: record.body, createdAt: record.createdAt, updatedAt: record.updatedAt };
|
|
898
|
+
}
|
|
899
|
+
async listIssueComments({ token, id, number }) {
|
|
900
|
+
const { record } = await this.open(token, id);
|
|
901
|
+
return this.issueOf(record, number).comments.map((comment) => this.toComment(comment));
|
|
902
|
+
}
|
|
903
|
+
async addIssueComment({ token, id, number, body }) {
|
|
904
|
+
const { record, user } = await this.open(token, id);
|
|
905
|
+
if (!body.trim())
|
|
906
|
+
throw new LocalError('A comment cannot be empty', 400);
|
|
907
|
+
const made = await this.store.update((current) => {
|
|
908
|
+
const issue = this.issueOf(this.repositoryOf(current, record.id), number);
|
|
909
|
+
const now = new Date().toISOString();
|
|
910
|
+
const comment = { id: issue.nextComment, author: user.username, body, createdAt: now, updatedAt: now };
|
|
911
|
+
issue.nextComment += 1;
|
|
912
|
+
issue.comments.push(comment);
|
|
913
|
+
issue.updatedAt = now;
|
|
914
|
+
return comment;
|
|
915
|
+
});
|
|
916
|
+
return this.toComment(made);
|
|
917
|
+
}
|
|
918
|
+
async listLabels({ token, id }) {
|
|
919
|
+
const { record } = await this.open(token, id);
|
|
920
|
+
return [...new Set((record.issues ?? []).flatMap((issue) => issue.labels))].sort().map((name) => ({ name }));
|
|
921
|
+
}
|
|
922
|
+
async listMilestones({ token, id }) {
|
|
923
|
+
const { record } = await this.open(token, id);
|
|
924
|
+
const titles = [...new Set((record.issues ?? []).flatMap((issue) => issue.milestone ? [issue.milestone] : []))].sort();
|
|
925
|
+
return titles.map((title) => ({ title, state: 'opened' }));
|
|
926
|
+
}
|
|
927
|
+
// ── merge requests (the pages of them) ──────────────────────────────────
|
|
928
|
+
async toMergeRequest(dir, web, request) {
|
|
929
|
+
const head = await this.resolveCommit(dir, `refs/heads/${request.sourceBranch}`);
|
|
930
|
+
const threads = request.threads ?? [];
|
|
931
|
+
return {
|
|
932
|
+
number: request.number, title: request.title, description: request.description ?? '', state: request.state, author: request.author,
|
|
933
|
+
sourceBranch: request.sourceBranch, targetBranch: request.targetBranch, labels: [...(request.labels ?? [])], reviewers: [...(request.reviewers ?? [])], assignees: [],
|
|
934
|
+
createdAt: request.createdAt, updatedAt: request.updatedAt ?? request.createdAt, mergedAt: request.mergedAt ?? null,
|
|
935
|
+
// (there is no page for it on this host: the client shows no link for an empty address)
|
|
936
|
+
webUrl: '',
|
|
937
|
+
hasConflicts: request.state === 'opened' && await this.conflicts(dir, request.targetBranch, request.sourceBranch),
|
|
938
|
+
headSha: head ?? undefined,
|
|
939
|
+
commentCount: threads.reduce((sum, thread) => sum + thread.comments.length, 0)
|
|
940
|
+
};
|
|
941
|
+
}
|
|
942
|
+
requestOf(record, number) {
|
|
943
|
+
const found = record.changeRequests.find((candidate) => candidate.number === number);
|
|
944
|
+
if (!found)
|
|
945
|
+
throw new LocalError(`There is no merge request ${number}`, 404);
|
|
946
|
+
return found;
|
|
947
|
+
}
|
|
948
|
+
async listMergeRequests({ token, id, filter = {} }) {
|
|
949
|
+
const { dir, record, state } = await this.open(token, id);
|
|
950
|
+
const web = this.toRepository(state, record).webUrl;
|
|
951
|
+
const { state: wanted = 'opened', author, reviewer, labels = [], search, sourceBranch, targetBranch } = filter;
|
|
952
|
+
const perPage = Math.min(Math.max(filter.perPage ?? 20, 1), 100);
|
|
953
|
+
const page = Math.max(filter.page ?? 1, 1);
|
|
954
|
+
const needle = search?.trim().toLowerCase();
|
|
955
|
+
const matching = record.changeRequests
|
|
956
|
+
.filter((request) => (wanted === 'all' || request.state === wanted)
|
|
957
|
+
&& (!author || request.author === author)
|
|
958
|
+
&& (!reviewer || (request.reviewers ?? []).includes(reviewer))
|
|
959
|
+
&& labels.every((label) => (request.labels ?? []).includes(label))
|
|
960
|
+
&& (!sourceBranch || request.sourceBranch === sourceBranch)
|
|
961
|
+
&& (!targetBranch || request.targetBranch === targetBranch)
|
|
962
|
+
&& (!needle || request.title.toLowerCase().includes(needle) || (request.description ?? '').toLowerCase().includes(needle)))
|
|
963
|
+
.sort((a, b) => b.number - a.number);
|
|
964
|
+
const items = await Promise.all(matching.slice((page - 1) * perPage, page * perPage).map((request) => this.toMergeRequest(dir, web, request)));
|
|
965
|
+
return { items, page, perPage, hasMore: matching.length > page * perPage };
|
|
966
|
+
}
|
|
967
|
+
async getMergeRequest({ token, id, number }) {
|
|
968
|
+
const { dir, record, state } = await this.open(token, id);
|
|
969
|
+
return this.toMergeRequest(dir, this.toRepository(state, record).webUrl, this.requestOf(record, number));
|
|
970
|
+
}
|
|
971
|
+
async createMergeRequest({ token, id, title, description = '', sourceBranch, targetBranch, labels, reviewers }) {
|
|
972
|
+
if (!title.trim())
|
|
973
|
+
throw new LocalError('A merge request needs a title', 400);
|
|
974
|
+
const { dir, record, state, user } = await this.open(token, id, WRITE_ACCESS);
|
|
975
|
+
await this.mustResolve(dir, `refs/heads/${sourceBranch}`);
|
|
976
|
+
await this.mustResolve(dir, `refs/heads/${targetBranch}`);
|
|
977
|
+
const made = await this.store.update((current) => {
|
|
978
|
+
const repository = this.repositoryOf(current, record.id);
|
|
979
|
+
if (repository.changeRequests.some((request) => request.state === 'opened' && request.sourceBranch === sourceBranch && request.targetBranch === targetBranch)) {
|
|
980
|
+
throw new LocalError('Another open merge request already exists for this source branch', 409, 'already_exists');
|
|
981
|
+
}
|
|
982
|
+
const now = new Date().toISOString();
|
|
983
|
+
const request = {
|
|
984
|
+
number: repository.nextChangeRequest++, title: title.trim(), sourceBranch, targetBranch, state: 'opened', createdAt: now, updatedAt: now,
|
|
985
|
+
description, author: user.username, labels: this.cleanList(labels), reviewers: this.cleanList(reviewers), threads: [], nextThread: 1, nextComment: 1
|
|
986
|
+
};
|
|
987
|
+
repository.changeRequests.push(request);
|
|
988
|
+
return request;
|
|
989
|
+
});
|
|
990
|
+
return this.toMergeRequest(dir, this.toRepository(state, record).webUrl, made);
|
|
991
|
+
}
|
|
992
|
+
async updateMergeRequest({ token, id, number, changes }) {
|
|
993
|
+
const { dir, record, state, user } = await this.open(token, id);
|
|
994
|
+
const level = this.levelFor(state, record, user);
|
|
995
|
+
const updated = await this.store.update((current) => {
|
|
996
|
+
const request = this.requestOf(this.repositoryOf(current, record.id), number);
|
|
997
|
+
if (level < WRITE_ACCESS && request.author !== user.username)
|
|
998
|
+
throw new LocalError('You are not allowed to do that here', 403);
|
|
999
|
+
if (changes.title !== undefined) {
|
|
1000
|
+
if (!changes.title.trim())
|
|
1001
|
+
throw new LocalError('A merge request needs a title', 400);
|
|
1002
|
+
request.title = changes.title.trim();
|
|
1003
|
+
}
|
|
1004
|
+
if (changes.description !== undefined)
|
|
1005
|
+
request.description = changes.description;
|
|
1006
|
+
if (changes.labels !== undefined)
|
|
1007
|
+
request.labels = this.cleanList(changes.labels);
|
|
1008
|
+
if (changes.reviewers !== undefined)
|
|
1009
|
+
request.reviewers = this.cleanList(changes.reviewers);
|
|
1010
|
+
if (changes.state === 'closed' && request.state === 'opened')
|
|
1011
|
+
request.state = 'closed';
|
|
1012
|
+
if (changes.state === 'opened' && request.state === 'closed')
|
|
1013
|
+
request.state = 'opened';
|
|
1014
|
+
request.updatedAt = new Date().toISOString();
|
|
1015
|
+
return request;
|
|
1016
|
+
});
|
|
1017
|
+
return this.toMergeRequest(dir, this.toRepository(state, record).webUrl, updated);
|
|
1018
|
+
}
|
|
1019
|
+
async getMergeRequestDiff({ token, id, number }) {
|
|
1020
|
+
const { dir, record } = await this.open(token, id);
|
|
1021
|
+
const request = this.requestOf(record, number);
|
|
1022
|
+
const [target, source] = [await this.resolveCommit(dir, `refs/heads/${request.targetBranch}`), await this.resolveCommit(dir, `refs/heads/${request.sourceBranch}`)];
|
|
1023
|
+
if (!target || !source)
|
|
1024
|
+
return [];
|
|
1025
|
+
// what the branch brought since it left the target, not what the target did meanwhile
|
|
1026
|
+
const base = (await git(dir, ['merge-base', target, source])).stdout.toString('utf8').trim() || target;
|
|
1027
|
+
return parseGitDiff(await gitText(dir, ['diff', '-M', '--no-color', '--no-ext-diff', base, source]));
|
|
1028
|
+
}
|
|
1029
|
+
toThread(thread) {
|
|
1030
|
+
return {
|
|
1031
|
+
id: thread.id, resolvable: Boolean(thread.position), resolved: thread.resolved,
|
|
1032
|
+
position: thread.position ? { ...thread.position } : undefined,
|
|
1033
|
+
comments: thread.comments.map((comment) => this.toComment(comment))
|
|
1034
|
+
};
|
|
1035
|
+
}
|
|
1036
|
+
async listMergeRequestThreads({ token, id, number }) {
|
|
1037
|
+
const { record } = await this.open(token, id);
|
|
1038
|
+
return (this.requestOf(record, number).threads ?? []).map((thread) => this.toThread(thread));
|
|
1039
|
+
}
|
|
1040
|
+
async addMergeRequestComment({ token, id, number, body, position, threadId }) {
|
|
1041
|
+
if (!body.trim())
|
|
1042
|
+
throw new LocalError('A comment cannot be empty', 400);
|
|
1043
|
+
const { record, user } = await this.open(token, id);
|
|
1044
|
+
const made = await this.store.update((current) => {
|
|
1045
|
+
const request = this.requestOf(this.repositoryOf(current, record.id), number);
|
|
1046
|
+
const now = new Date().toISOString();
|
|
1047
|
+
const comment = { id: request.nextComment ?? 1, author: user.username, body, createdAt: now, updatedAt: now };
|
|
1048
|
+
request.nextComment = comment.id + 1;
|
|
1049
|
+
request.threads ??= [];
|
|
1050
|
+
let thread = threadId === undefined ? undefined : request.threads.find((candidate) => candidate.id === Number(threadId));
|
|
1051
|
+
if (threadId !== undefined && !thread)
|
|
1052
|
+
throw new LocalError(`There is no thread ${threadId}`, 404);
|
|
1053
|
+
if (!thread) {
|
|
1054
|
+
thread = { id: request.nextThread ?? 1, resolved: false, comments: [], ...(position ? { position: { path: position.path, line: position.line, side: position.side } } : {}) };
|
|
1055
|
+
request.nextThread = thread.id + 1;
|
|
1056
|
+
request.threads.push(thread);
|
|
1057
|
+
}
|
|
1058
|
+
thread.comments.push(comment);
|
|
1059
|
+
request.updatedAt = now;
|
|
1060
|
+
return thread;
|
|
1061
|
+
});
|
|
1062
|
+
return this.toThread(made);
|
|
1063
|
+
}
|
|
1064
|
+
async setThreadResolved({ token, id, number, threadId, resolved }) {
|
|
1065
|
+
const { record } = await this.open(token, id);
|
|
1066
|
+
const made = await this.store.update((current) => {
|
|
1067
|
+
const thread = (this.requestOf(this.repositoryOf(current, record.id), number).threads ?? []).find((candidate) => candidate.id === Number(threadId));
|
|
1068
|
+
if (!thread)
|
|
1069
|
+
throw new LocalError(`There is no thread ${threadId}`, 404);
|
|
1070
|
+
if (!thread.position)
|
|
1071
|
+
throw new LocalError('Only a thread about the code can be resolved', 400);
|
|
1072
|
+
thread.resolved = resolved;
|
|
1073
|
+
return thread;
|
|
1074
|
+
});
|
|
1075
|
+
return this.toThread(made);
|
|
1076
|
+
}
|
|
1077
|
+
async mergeMergeRequest({ token, id, number, options = {} }) {
|
|
1078
|
+
const { dir, record, user } = await this.open(token, id, WRITE_ACCESS);
|
|
1079
|
+
const request = this.requestOf(record, number);
|
|
1080
|
+
if (request.state !== 'opened')
|
|
1081
|
+
return true;
|
|
1082
|
+
const targetRef = `refs/heads/${request.targetBranch}`;
|
|
1083
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
1084
|
+
const [target, source] = [await this.mustResolve(dir, targetRef), await this.mustResolve(dir, `refs/heads/${request.sourceBranch}`)];
|
|
1085
|
+
const contained = (await git(dir, ['merge-base', '--is-ancestor', source, target])).code === 0;
|
|
1086
|
+
if (!contained) {
|
|
1087
|
+
const merged = await git(dir, ['merge-tree', '--write-tree', target, source]);
|
|
1088
|
+
if (merged.code === 1)
|
|
1089
|
+
return true;
|
|
1090
|
+
if (merged.code !== 0)
|
|
1091
|
+
throw new LocalError(`git merge-tree failed (it needs git 2.38 or newer): ${merged.stderr.trim() || `exit ${merged.code}`}`, 500);
|
|
1092
|
+
const tree = merged.stdout.toString('utf8').split('\n')[0]?.trim() ?? '';
|
|
1093
|
+
// a squash leaves one commit on the target, whose only parent is the target: the branch's own history is not kept
|
|
1094
|
+
const parents = options.squash ? ['-p', target] : ['-p', target, '-p', source];
|
|
1095
|
+
const message = options.message ?? (options.squash ? `${request.title} (!${request.number})` : `Merge branch '${request.sourceBranch}' into '${request.targetBranch}'`);
|
|
1096
|
+
const commit = await gitText(dir, ['commit-tree', tree, ...parents, '-m', message], { env: identity(user.username) });
|
|
1097
|
+
const moved = await git(dir, ['update-ref', targetRef, commit, target]);
|
|
1098
|
+
if (moved.code !== 0)
|
|
1099
|
+
continue;
|
|
1100
|
+
}
|
|
1101
|
+
if (options.deleteSourceBranch)
|
|
1102
|
+
await git(dir, ['update-ref', '-d', `refs/heads/${request.sourceBranch}`]);
|
|
1103
|
+
await this.store.update((current) => {
|
|
1104
|
+
const standing = this.requestOf(this.repositoryOf(current, record.id), number);
|
|
1105
|
+
standing.state = 'merged';
|
|
1106
|
+
standing.mergedAt = new Date().toISOString();
|
|
1107
|
+
standing.updatedAt = standing.mergedAt;
|
|
1108
|
+
});
|
|
1109
|
+
if (request.targetBranch === record.defaultBranch) {
|
|
1110
|
+
const messages = await git(dir, ['log', '--max-count=500', '--format=%B%x00', `${target}..${source}`]);
|
|
1111
|
+
const commits = messages.code === 0 ? messages.stdout.toString('utf8').split('\0') : [];
|
|
1112
|
+
await this.closeIssues(record.id, closingIssueNumbers(request.title, request.description, ...commits));
|
|
1113
|
+
}
|
|
1114
|
+
return false;
|
|
1115
|
+
}
|
|
1116
|
+
throw new LocalError(`"${request.targetBranch}" kept moving while the merge request was merged: try again`, 409);
|
|
1117
|
+
}
|
|
1118
|
+
async approveMergeRequest(_args) {
|
|
1119
|
+
throw new LocalError('This host has no approvals', 400);
|
|
1120
|
+
}
|
|
1121
|
+
// ── CI and hooks ─────────────────────────────────────────────────────────
|
|
1122
|
+
async listChangeRequestPipelines(_args) {
|
|
1123
|
+
return [];
|
|
1124
|
+
}
|
|
1125
|
+
async getCiRunners(_args) {
|
|
1126
|
+
return { supported: false, instanceRunners: null, runners: [] };
|
|
1127
|
+
}
|
|
1128
|
+
async setInstanceRunners(_args) {
|
|
1129
|
+
// this host runs no pipelines
|
|
1130
|
+
}
|
|
1131
|
+
async getLatestPipeline(_args) {
|
|
1132
|
+
return null;
|
|
1133
|
+
}
|
|
1134
|
+
async listPipelines(_args) {
|
|
1135
|
+
return [];
|
|
1136
|
+
}
|
|
1137
|
+
async getPipelineJobs(_args) {
|
|
1138
|
+
return [];
|
|
1139
|
+
}
|
|
1140
|
+
async retryPipeline(_args) {
|
|
1141
|
+
// this host runs no pipelines
|
|
1142
|
+
}
|
|
1143
|
+
async enablePipelines(_args) {
|
|
1144
|
+
return false; // this host runs no pipelines
|
|
1145
|
+
}
|
|
1146
|
+
async disablePipelines(_args) {
|
|
1147
|
+
return false; // this host runs no pipelines
|
|
1148
|
+
}
|
|
1149
|
+
async pipelinesEnabled(_args) {
|
|
1150
|
+
return null; // this host runs no pipelines
|
|
1151
|
+
}
|
|
1152
|
+
async cancelPipeline(_args) {
|
|
1153
|
+
// this host runs no pipelines
|
|
1154
|
+
}
|
|
1155
|
+
async cancelJob(_args) {
|
|
1156
|
+
// this host runs no pipelines
|
|
1157
|
+
}
|
|
1158
|
+
async getJobTrace(_args) {
|
|
1159
|
+
return '';
|
|
1160
|
+
}
|
|
1161
|
+
async ensureWebhook({ token, id, url, secret, branch }) {
|
|
1162
|
+
const { record } = await this.open(token, id, ACCESS.MAINTAINER);
|
|
1163
|
+
return this.store.update((state) => {
|
|
1164
|
+
const repository = this.repositoryOf(state, record.id);
|
|
1165
|
+
const index = repository.hooks.findIndex((hook) => hook.url === url);
|
|
1166
|
+
if (index >= 0)
|
|
1167
|
+
return { status: 'already_exists', hookId: index + 1 };
|
|
1168
|
+
repository.hooks.push({ url, secret, branch: branch ?? null });
|
|
1169
|
+
return { status: 'created', hookId: repository.hooks.length };
|
|
1170
|
+
});
|
|
1171
|
+
}
|
|
1172
|
+
verifyWebhook({ headers, rawBody, secret }) {
|
|
1173
|
+
const given = headers['x-linea-signature'] ?? headers['X-Linea-Signature'];
|
|
1174
|
+
if (!given)
|
|
1175
|
+
return false;
|
|
1176
|
+
const expected = `sha256=${crypto.createHmac('sha256', secret).update(rawBody).digest('hex')}`;
|
|
1177
|
+
return given.length === expected.length && crypto.timingSafeEqual(Buffer.from(given), Buffer.from(expected));
|
|
1178
|
+
}
|
|
1179
|
+
parsePushEvent({ body }) {
|
|
1180
|
+
if (body?.repositoryId === undefined || typeof body?.ref !== 'string' || !body.ref.startsWith('refs/heads/'))
|
|
1181
|
+
return null;
|
|
1182
|
+
return { repositoryId: body.repositoryId, branch: body.ref.slice('refs/heads/'.length) };
|
|
1183
|
+
}
|
|
1184
|
+
/** Gives a person a level (reporter 20 .. maintainer 40) in a repository, or changes it. Only its owner (or an administrator) may; the owner's own level is not changed. */
|
|
1185
|
+
async setMember({ token, id, username, accessLevel }) {
|
|
1186
|
+
const { record } = await this.open(token, id, ACCESS.OWNER);
|
|
1187
|
+
if (![ACCESS.GUEST, ACCESS.REPORTER, ACCESS.DEVELOPER, ACCESS.MAINTAINER].includes(accessLevel))
|
|
1188
|
+
throw new LocalError(`${accessLevel} is not a level a member can have`, 400);
|
|
1189
|
+
if (record.owner === username)
|
|
1190
|
+
throw new LocalError('The owner of a repository is always its owner', 400);
|
|
1191
|
+
await this.store.addMember({ repositoryId: record.id, username, accessLevel });
|
|
1192
|
+
}
|
|
1193
|
+
/** Takes a person's level away: they go back to what everybody has here (or nothing, in a group only its owner writes in). */
|
|
1194
|
+
async removeMember({ token, id, username }) {
|
|
1195
|
+
const { record } = await this.open(token, id, ACCESS.OWNER);
|
|
1196
|
+
await this.store.update((state) => {
|
|
1197
|
+
const repository = this.repositoryOf(state, record.id);
|
|
1198
|
+
repository.members = repository.members.filter((member) => member.username !== username);
|
|
1199
|
+
});
|
|
1200
|
+
}
|
|
1201
|
+
/**
|
|
1202
|
+
* Hands everything one person owns to another name (a person who leaves, a rename): the groups and repositories they made, and the
|
|
1203
|
+
* places they were a member of. Names that nobody can sign in with (`deleted:ana`) leave them to the administrators.
|
|
1204
|
+
*/
|
|
1205
|
+
async transferOwnership({ from, to }) {
|
|
1206
|
+
return this.store.update((state) => {
|
|
1207
|
+
let namespaces = 0;
|
|
1208
|
+
let repositories = 0;
|
|
1209
|
+
for (const namespace of state.namespaces)
|
|
1210
|
+
if (namespace.owner === from) {
|
|
1211
|
+
namespace.owner = to;
|
|
1212
|
+
namespaces += 1;
|
|
1213
|
+
}
|
|
1214
|
+
for (const repository of state.repositories) {
|
|
1215
|
+
if (repository.owner === from) {
|
|
1216
|
+
repository.owner = to;
|
|
1217
|
+
repositories += 1;
|
|
1218
|
+
}
|
|
1219
|
+
const kept = repository.members.filter((member) => member.username !== to);
|
|
1220
|
+
repository.members = kept.map((member) => (member.username === from ? { ...member, username: to } : member));
|
|
1221
|
+
}
|
|
1222
|
+
return { namespaces, repositories };
|
|
1223
|
+
});
|
|
1224
|
+
}
|
|
1225
|
+
// ── unit of work, errors ─────────────────────────────────────────────────
|
|
1226
|
+
async rollback() {
|
|
1227
|
+
while (this.undo.length)
|
|
1228
|
+
await this.undo.pop()();
|
|
1229
|
+
}
|
|
1230
|
+
isAuthError(error) {
|
|
1231
|
+
return error?.status === 401;
|
|
1232
|
+
}
|
|
1233
|
+
isAlreadyExistsError(error) {
|
|
1234
|
+
return error?.code === 'already_exists';
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
//# sourceMappingURL=provider.js.map
|