Forge

Jessie / forge public

Self-hosted git - made by qwen 3.8 27b

Initial commit

Author
Jessie <xicyneo@gmail.com> ·
Commit
0c9688e915a57f9ff4013517aa4e5d3355b7b5b3
Parents
none (first commit)

Browse files at this commit

118 changed files: +18715 −0

added .dockerignore +14 −0View file
@@ -0,0 +1,14 @@
1 **/bin/
2 **/obj/
3 .git/
4 .idea/
5 .artifacts/
6 *.user
7 forge.Tests/
8
9 # Local runtime data. Listed file by file: forge/Data (source) differs only in case.
10 forge/data/forge.db*
11 forge/data/repos/
12 forge/data/tmp/
13 forge/data/keys/
14 forge/data/.config/
added .gitignore +11 −0View file
@@ -0,0 +1,11 @@
1 bin/
2 obj/
3 .idea/
4 *.user
5
6 # Forge runtime data (SQLite database and bare repositories)
7 forge/data/forge.db*
8 forge/data/repos/
9 forge/data/tmp/
10 .artifacts/
11 forge/data/keys/
added Dockerfile +36 −0View file
@@ -0,0 +1,36 @@
1 # syntax=docker/dockerfile:1
2
3 # ---- build ----
4 FROM mcr.microsoft.com/dotnet/sdk:11.0 AS build
5 WORKDIR /src
6
7 # Restore first so the package layer is cached until the project file changes.
8 COPY forge/forge.csproj forge/
9 RUN dotnet restore forge/forge.csproj
10
11 COPY forge/ forge/
12 RUN dotnet publish forge/forge.csproj -c Release -o /app --no-restore -p:UseAppHost=false
13
14 # ---- runtime ----
15 FROM mcr.microsoft.com/dotnet/aspnet:11.0 AS runtime
16
17 # Forge runs the git executable for everything (needs 2.40+; it checks at startup).
18 RUN apt-get update \
19 && apt-get install -y --no-install-recommends git ca-certificates \
20 && rm -rf /var/lib/apt/lists/*
21
22 WORKDIR /app
23 COPY --from=build /app .
24
25 # Data folder owned by the image's non-root user, so a fresh named volume inherits that ownership.
26 RUN mkdir -p /data && chown $APP_UID:$APP_UID /data
27 VOLUME /data
28
29 ENV ASPNETCORE_URLS=http://+:8080 \
30 ASPNETCORE_ENVIRONMENT=Production \
31 ASPNETCORE_FORWARDEDHEADERS_ENABLED=true \
32 Forge__DataPath=/data
33
34 USER $APP_UID
35 EXPOSE 8080
36 ENTRYPOINT ["dotnet", "forge.dll"]
added README.md +99 −0View file
@@ -0,0 +1,99 @@
1 # Forge
2
3 Forge is a self-hosted Git server with a web interface. It is built with ASP.NET Core (Blazor Server) and uses real bare Git repositories on disk, so any Git client can clone and push to it over HTTP(S).
4
5 ## Features
6
7 - **Repositories:** create repos, browse files and folders, view blobs with syntax highlighting, and render Markdown previews.
8 - **History:** commit list and commit details, branch and tag pages, compare any two refs, and a file-level diff view.
9 - **Pull requests:** open, review and merge pull requests, with merge-conflict detection (`git merge-tree`) and branch protection rules.
10 - **Search:** find repositories, file names and file contents.
11 - **Activity:** weekly commit counts and contributors per repository.
12 - **Git over HTTP:** clone and push with the smart HTTP protocol. Authentication uses personal access tokens (read-only or read/write).
13 - **Webhooks:** signed deliveries for pushes and pull request events, with delivery status and retries.
14 - **Atom feeds:** commit feeds for each repository.
15 - **Accounts:** sign-up through a first-run setup page, login with rate limiting, and per-user repository access.
16 - **Languages:** English and Slovak. The language is chosen in the footer and remembered in a cookie, with the browser's `Accept-Language` as the fallback.
17
18 ## Requirements
19
20 - [.NET SDK](https://dotnet.microsoft.com/download) with the version targeted in `forge/forge.csproj`
21 - Git 2.40 or newer (Forge uses `git merge-tree --merge-base`). Forge checks the version at startup and refuses to run with an older one.
22
23 ## Getting started
24
25 ```bash
26 dotnet run --project forge
27 ```
28
29 The default development profile listens on `http://localhost:5207`. On first run, open `/setup` to create the administrator account. Then create a repository at `/new`.
30
31 To clone a repository from Forge, use the URL shown on the repository page (`<BaseUrl>/<owner>/<name>.git`). Git asks for credentials: use your username, and a personal access token created at `/settings/tokens` as the password.
32
33 ## Configuration
34
35 Settings live in `forge/appsettings.json` under the `Forge` section. Any of them can be overridden with environment variables (for example `Forge__BaseUrl`) or with user secrets during development.
36
37 | Setting | Default | Meaning |
38 | --- | --- | --- |
39 | `Forge:DataPath` | `data` | Folder for `forge.db` and the `repos/` directory. Relative paths resolve against the working directory. |
40 | `Forge:BaseUrl` | `http://localhost:5207` | Public URL of the site. Used for clone URLs, feeds and webhook payloads. Must be an absolute http or https URL. |
41 | `Forge:MaxPushSizeMb` | `500` | Largest push Forge accepts, in megabytes. |
42 | `Forge:GitPath` | `git` | Git executable, a name on `PATH` or an absolute path. |
43
44 Set `BaseUrl` to the address users actually visit. Using `https://` also makes the session and CSRF cookies `Secure`.
45
46 ## Deploying with Docker
47
48 The `Dockerfile` builds an image with the app and git, running as a non-root user on port 8080, with all data in the `/data` volume. With Docker Compose:
49
50 1. Set `Forge__BaseUrl` in `compose.yaml` to the public address of the server.
51 2. Run `docker compose up -d --build`.
52 3. Open `/setup` to create the administrator account.
53
54 `compose.yaml` publishes the port on `127.0.0.1` only, for a reverse proxy that terminates HTTPS. Forwarded headers (`X-Forwarded-For`, `X-Forwarded-Proto`) are honored, so rate limiting sees real client addresses. Allow request bodies as large as `Forge:MaxPushSizeMb` in the proxy (for nginx, `client_max_body_size`), and pass WebSocket upgrades through, which Blazor Server uses.
55
56 To update, pull the new code and run `docker compose up -d --build` again. Migrations run at startup.
57
58 ## Data and storage
59
60 - `forge.db` is a SQLite database managed with Entity Framework Core. Migrations run automatically at startup.
61 - `repos/` holds the bare Git repositories.
62 - `keys/` holds the keys that protect login cookies. Losing them signs everyone out.
63 - Both live under `Forge:DataPath`. Back up that folder to back up the server.
64
65 ## Project layout
66
67 ```
68 forge/ ASP.NET Core application
69 Components/ Shared Blazor components and layout
70 Features/ Feature folders: Auth, Browse, History, Pulls, Repos, SmartHttp, Webhooks
71 Git/ Thin wrapper around the git executable and its output parsers
72 Data/ EF Core model, DbContext and migrations
73 Localization/ Translation files (sk.json; English is the source language)
74 wwwroot/ Static assets (CSS, JavaScript, syntax highlighting)
75 forge.Tests/ xUnit tests, including end-to-end tests that run the app and real Git
76 ```
77
78 ## Development
79
80 ```bash
81 dotnet build forge.slnx
82 dotnet test forge.Tests
83 ```
84
85 Adding a language means adding a JSON file to `forge/Localization/`, named after its culture code (for example `de.json`). Keys are the English strings exactly as they appear in the code.
86
87 Database schema changes are made with the EF Core tools in `dotnet-tools.json`:
88
89 ```bash
90 dotnet ef migrations add <Name> --project forge
91 ```
92
93 ## Security notes
94
95 - Passwords are hashed with ASP.NET Core Identity's `PasswordHasher`.
96 - Access tokens are used as the Git password. Read-only tokens cannot push.
97 - Responses set a strict Content-Security-Policy, `X-Frame-Options: DENY` and `nosniff`.
98 - Form posts are rate limited per client address. Rendered Markdown is sanitized.
99 - Webhook receivers are not followed on redirect, so signed payloads are never re-sent to another address.
added compose.yaml +18 −0View file
@@ -0,0 +1,18 @@
1 services:
2 forge:
3 build: .
4 image: forge
5 restart: unless-stopped
6 ports:
7 # Only on localhost: put a reverse proxy (Caddy, nginx, Traefik) in front for HTTPS.
8 # Use "8080:8080" instead to expose it directly.
9 - "127.0.0.1:8080:8080"
10 environment:
11 # The address users actually visit. https:// also makes cookies Secure.
12 Forge__BaseUrl: https://git.example.com
13 Forge__MaxPushSizeMb: 500
14 volumes:
15 - forge-data:/data
16
17 volumes:
18 forge-data:
added dotnet-tools.json +13 −0View file
@@ -0,0 +1,13 @@
1 {
2 "version": 1,
3 "isRoot": true,
4 "tools": {
5 "dotnet-ef": {
6 "version": "11.0.0",
7 "commands": [
8 "dotnet-ef"
9 ],
10 "rollForward": false
11 }
12 }
13 }
added forge.Tests/AdvancedMergeTests.cs +502 −0View file
@@ -0,0 +1,502 @@
1 using System.Net;
2 using System.Text;
3 using Forge.Data;
4 using Forge.Features.History;
5 using Forge.Features.SmartHttp;
6 using Forge.Tests.Support;
7 using Microsoft.EntityFrameworkCore;
8 using Microsoft.Extensions.DependencyInjection;
9
10 namespace Forge.Tests;
11
12 public class DiffRowTests
13 {
14 [Fact]
15 public void Compare_marks_what_lies_between_the_common_start_and_end()
16 {
17 var (old, @new) = DiffRows.Compare(" var total = count + 1;", " var total = count + 20;");
18 Assert.Equal(new ChangeRange(24, 25), old);
19 Assert.Equal(new ChangeRange(24, 26), @new);
20
21 // A pure insertion leaves an empty range on the old side.
22 (old, @new) = DiffRows.Compare("call(a);", "call(a, b);");
23 Assert.Equal(new ChangeRange(6, 6), old);
24 Assert.Equal(new ChangeRange(6, 9), @new);
25 }
26
27 [Fact]
28 public void Compare_gives_up_when_only_indentation_is_shared()
29 {
30 Assert.Equal((null, null), DiffRows.Compare(" left", " north"));
31 Assert.Equal((null, null), DiffRows.Compare("same", "same"));
32 Assert.Equal((null, null), DiffRows.Compare("abc", "xyz"));
33 }
34
35 [Fact]
36 public void Pair_lines_up_removed_and_added_lines()
37 {
38 var hunk = new Git.DiffHunk { Header = "@@ -1,4 +1,4 @@" };
39 hunk.Lines.AddRange(
40 [
41 new(Git.DiffLineKind.Context, 1, 1, "keep"),
42 new(Git.DiffLineKind.Deleted, 2, null, "old a"),
43 new(Git.DiffLineKind.Deleted, 3, null, "old b"),
44 new(Git.DiffLineKind.Added, null, 2, "new a"),
45 new(Git.DiffLineKind.NoNewline, null, null, ""),
46 new(Git.DiffLineKind.Context, 4, 3, "end"),
47 ]);
48
49 var rows = DiffRows.Pair(hunk);
50
51 Assert.Equal(4, rows.Count);
52 Assert.Equal(("keep", "keep"), (rows[0].Left!.Line.Text, rows[0].Right!.Line.Text));
53 Assert.Equal(("old a", "new a"), (rows[1].Left!.Line.Text, rows[1].Right!.Line.Text));
54 Assert.NotNull(rows[1].Left!.Change);
55 Assert.Equal("old b", rows[2].Left!.Line.Text);
56 Assert.Null(rows[2].Right);
57 Assert.Equal("end", rows[3].Right!.Line.Text);
58 }
59 }
60
61 public class PushGuardTests
62 {
63 private static byte[] Request(params string[] commands)
64 {
65 var body = new MemoryStream();
66 foreach (var command in commands)
67 {
68 body.Write(SmartHttpEndpoints.PktLine(command));
69 }
70
71 body.Write("0000PACK...rest of the push"u8);
72 return body.ToArray();
73 }
74
75 [Fact]
76 public async Task Command_list_is_read_and_the_stream_replays_everything()
77 {
78 var a = new string('a', 40);
79 var b = new string('b', 40);
80 var request = Request($"{a} {b} refs/heads/main\0report-status side-band-64k\n", $"{b} {a} refs/tags/v1\n");
81
82 var (refs, consumed, understood) = await PushGuard.ReadCommandsAsync(new MemoryStream(request), default);
83 Assert.True(understood);
84 Assert.Equal(["refs/heads/main", "refs/tags/v1"], refs);
85 Assert.EndsWith("0000", Encoding.ASCII.GetString(consumed));
86
87 BranchProtection[] rules = [new() { Pattern = "main" }, new() { Pattern = "release/*", BlockPush = true }];
88 var (input, options) = await PushGuard.InspectAsync(new MemoryStream(request), rules, default);
89 Assert.Equal(
90 ["-c", "receive.hideRefs=refs/heads/release/", "-c", "receive.denyNonFastForwards=true", "-c", "receive.denyDeletes=true"],
91 options);
92 var replayed = new MemoryStream();
93 await input.CopyToAsync(replayed);
94 Assert.Equal(request, replayed.ToArray());
95 }
96
97 [Fact]
98 public async Task Pushes_that_miss_protected_branches_are_left_alone_and_garbage_fails_closed()
99 {
100 var a = new string('a', 40);
101 BranchProtection[] rules = [new() { Pattern = "main" }];
102
103 var (_, options) = await PushGuard.InspectAsync(new MemoryStream(Request($"{a} {a} refs/heads/topic\n")), rules, default);
104 Assert.Empty(options);
105
106 (_, options) = await PushGuard.InspectAsync(new MemoryStream("zzzz not pkt-lines"u8.ToArray()), rules, default);
107 Assert.Contains("receive.denyNonFastForwards=true", options);
108 }
109
110 [Theory]
111 [InlineData("main", "main", true)]
112 [InlineData("main", "main2", false)]
113 [InlineData("main", "feature/main", false)]
114 [InlineData("release/*", "release/1.0", true)]
115 [InlineData("release/*", "release/1.0/hotfix", true)]
116 [InlineData("release/*", "release", false)]
117 [InlineData("release/*", "releases/1.0", false)]
118 public void Protection_patterns_match_names_and_prefixes(string pattern, string branch, bool expected) =>
119 Assert.Equal(expected, BranchRules.Matches(pattern, branch));
120 }
121
122 public class AdvancedMergeTests(ForgeHost host) : IClassFixture<ForgeHost>
123 {
124 private Task<T> DbAsync<T>(Func<ForgeDb, Task<T>> query) =>
125 host.WithScopeAsync(sp => query(sp.GetRequiredService<ForgeDb>()));
126
127 [Fact]
128 public async Task Diff_has_a_file_index_side_by_side_layout_and_within_line_changes()
129 {
130 var s = await BranchScenario.CreateAsync(host, "diff-view", diverge: true);
131 using var client = host.CreateClient();
132 var url = s.Page("compare/main...feature/x");
133
134 var unified = await client.GetStringAsync(url);
135 Assert.Contains("href=\"#diff-0\"", unified);
136 Assert.Contains("id=\"diff-1\"", unified);
137 Assert.DoesNotContain("class=\"diff split\"", unified);
138 // "two" became "TWO from feature": nothing but indentation-free text in common, so the whole line is the change.
139 Assert.Contains($"href=\"/jessie/diff-view/blob/{s.FeatureSha}/b.txt\"", unified);
140 Assert.Contains("/lib/highlight/highlight.min.js", unified);
141 Assert.Contains("href=\"" + url + "?view=split\"", unified);
142
143 var split = await client.GetStringAsync(url + "?view=split");
144 Assert.Contains("class=\"diff split\"", split);
145 Assert.Contains("TWO from feature", split);
146 // The other options keep the chosen layout.
147 Assert.Contains("href=\"" + url + "?view=split&amp;w=1\"", split);
148 Assert.Contains("href=\"/jessie/diff-view/compare/main..feature/x?view=split\"", split);
149
150 // Two dots compare the tips directly, so main's own file shows up (as removed); three dots leave it out.
151 var direct = await client.GetStringAsync(s.Page("compare/main..feature/x"));
152 Assert.Contains("only on main", direct);
153 Assert.DoesNotContain("only on main", unified);
154 }
155
156 [Fact]
157 public async Task Commit_page_marks_the_changed_part_of_a_line_and_can_ignore_whitespace()
158 {
159 var s = await BranchScenario.CreateAsync(host, "intraline");
160 await File.WriteAllTextAsync(Path.Combine(s.Work, "calc.cs"), "class Calc\n{\n int total = count + 1;\n}\n");
161 await host.Git.MustAsync(s.Work, "add", "-A");
162 await host.Git.MustAsync(s.Work, "commit", "-m", "Add calc");
163 await File.WriteAllTextAsync(Path.Combine(s.Work, "calc.cs"), "class Calc\n{\n int total = count + 20;\n}\n");
164 await host.Git.MustAsync(s.Work, "commit", "-am", "Change the increment");
165 var changed = await host.Git.MustAsync(s.Work, "rev-parse", "HEAD");
166 await File.WriteAllTextAsync(Path.Combine(s.Work, "calc.cs"), "class Calc\n{\n int total = count + 20;\n}\n");
167 await host.Git.MustAsync(s.Work, "commit", "-am", "Reindent");
168 var reindented = await host.Git.MustAsync(s.Work, "rev-parse", "HEAD");
169 await host.Git.MustAsync(s.Work, "push", s.Url, "main");
170 using var client = host.CreateClient();
171
172 var page = await client.GetStringAsync(s.Page($"commit/{changed}"));
173 Assert.Contains("data-lang=\"csharp\"", page);
174 Assert.Contains("<span class=\"chg\">1</span>", page);
175 Assert.Contains("<span class=\"chg\">20</span>", page);
176 Assert.Contains("data-cs=\"24\" data-ce=\"26\"", page);
177
178 var withWhitespace = await ForgeHost.TextAsync(await client.GetAsync(s.Page($"commit/{reindented}")));
179 Assert.Contains("1 changed file", withWhitespace);
180 var ignoring = await ForgeHost.TextAsync(await client.GetAsync(s.Page($"commit/{reindented}?w=1")));
181 Assert.Contains("0 changed files", ignoring);
182 }
183
184 [Fact]
185 public async Task Rebase_replays_the_commits_on_top_of_the_base_keeping_their_authors()
186 {
187 var s = await BranchScenario.CreateAsync(host, "rebase", diverge: true);
188 using var owner = await host.CreateSignedInClientAsync();
189
190 var merged = await ForgeHost.PostFormAsync(owner, s.Page("compare/main...feature/x"), "merge", new() { ["Method"] = "rebase" });
191 Assert.Equal(HttpStatusCode.Redirect, merged.StatusCode);
192
193 var log = (await s.ServerAsync("log", "--format=%s|%an|%cn|%P", "server/main")).Split('\n');
194 Assert.Equal(4, log.Length);
195 Assert.StartsWith("More feature work|Test Author|jessie|", log[0]);
196 Assert.StartsWith("Feature work|Test Author|jessie|", log[1]);
197 Assert.Equal($"Main moves on|Test Author|Test Author|{await host.Git.MustAsync(s.Work, "rev-parse", s.MainSha + "~1")}", log[2]);
198 // Linear: every commit has exactly one parent, and the feature's first commit now sits on main's tip.
199 Assert.EndsWith("|" + s.MainSha, log[1]);
200 Assert.All(log.Take(3), line => Assert.DoesNotContain(' ', line.Split('|')[3]));
201 Assert.Equal("new file\nsecond line", await host.Git.MustAsync(s.Work, "show", "server/main:b.txt"));
202 Assert.Equal("only on main", await host.Git.MustAsync(s.Work, "show", "server/main:c.txt"));
203 // The feature branch itself is not rewritten.
204 Assert.Equal(s.FeatureSha, await host.Git.MustAsync(s.Work, "rev-parse", "server/feature/x"));
205 }
206
207 [Fact]
208 public async Task Commits_can_be_reverted_and_cherry_picked_from_their_page()
209 {
210 var s = await BranchScenario.CreateAsync(host, "apply", diverge: true);
211 using var owner = await host.CreateSignedInClientAsync();
212 using var anonymous = host.CreateClient();
213 var featureFirst = await host.Git.MustAsync(s.Work, "rev-parse", s.FeatureSha + "~1");
214
215 // Cherry-pick the feature's first commit onto main.
216 var picked = await ForgeHost.PostFormAsync(owner, s.Page($"commit/{featureFirst}"), "apply-commit", new() { ["Branch"] = "main", ["Action"] = "pick" });
217 Assert.Equal(HttpStatusCode.Redirect, picked.StatusCode);
218 Assert.Equal("Feature work|Test Author|jessie", await s.ServerAsync("log", "-1", "--format=%s|%an|%cn", "server/main"));
219 Assert.Contains($"(cherry picked from commit {featureFirst})", await host.Git.MustAsync(s.Work, "log", "-1", "--format=%B", "server/main"));
220 Assert.Equal("new file", await host.Git.MustAsync(s.Work, "show", "server/main:b.txt"));
221 var pickedSha = await host.Git.MustAsync(s.Work, "rev-parse", "server/main");
222
223 // Picking it again changes nothing and says so.
224 var again = await ForgeHost.PostFormAsync(owner, s.Page($"commit/{featureFirst}"), "apply-commit", new() { ["Branch"] = "main", ["Action"] = "pick" });
225 Assert.Contains("already contains this change", await ForgeHost.TextAsync(again));
226
227 // Revert it.
228 var reverted = await ForgeHost.PostFormAsync(owner, s.Page($"commit/{pickedSha}"), "apply-commit", new() { ["Branch"] = "main", ["Action"] = "revert" });
229 Assert.Equal(HttpStatusCode.Redirect, reverted.StatusCode);
230 Assert.Equal("Revert \"Feature work\"", await s.ServerAsync("log", "-1", "--format=%s", "server/main"));
231 Assert.Equal("a.txt\nc.txt", await host.Git.MustAsync(s.Work, "ls-tree", "--name-only", "server/main"));
232 Assert.Equal("one\ntwo\nthree", await host.Git.MustAsync(s.Work, "show", "server/main:a.txt"));
233
234 // A change that does not apply cleanly is refused with the files named.
235 var conflicting = await BranchScenario.CreateAsync(host, "apply-conflict", diverge: true, conflict: true);
236 var first = await host.Git.MustAsync(conflicting.Work, "rev-parse", conflicting.FeatureSha + "~1");
237 var refused = await ForgeHost.PostFormAsync(owner, conflicting.Page($"commit/{first}"), "apply-commit", new() { ["Branch"] = "main", ["Action"] = "pick" });
238 var refusedHtml = await ForgeHost.TextAsync(refused);
239 Assert.Contains("cannot be applied automatically", refusedHtml);
240 Assert.Contains("<code>a.txt</code>", refusedHtml);
241 Assert.Equal(conflicting.MainSha, await conflicting.ServerAsync("rev-parse", "server/main"));
242
243 // Visitors get neither the form nor the effect.
244 Assert.DoesNotContain("apply-commit", await anonymous.GetStringAsync(s.Page($"commit/{s.FeatureSha}")));
245 var sneaky = await ForgeHost.PostFormAsync(anonymous, s.Page($"commit/{s.FeatureSha}"), "apply-commit", new() { ["Branch"] = "main", ["Action"] = "pick" });
246 Assert.False(sneaky.IsSuccessStatusCode);
247 }
248
249 [Fact]
250 public async Task Conflicts_are_resolved_in_the_browser()
251 {
252 var s = await BranchScenario.CreateAsync(host, "resolve", diverge: true, conflict: true);
253 using var owner = await host.CreateSignedInClientAsync();
254 using var anonymous = host.CreateClient();
255 var url = s.Page("conflicts/main...feature/x");
256
257 Assert.Contains("href=\"/jessie/resolve/conflicts/main...feature/x\"", await owner.GetStringAsync(s.Page("compare/main...feature/x")));
258 Assert.Equal(HttpStatusCode.NotFound, (await anonymous.GetAsync(url)).StatusCode);
259
260 var page = await ForgeHost.TextAsync(await owner.GetAsync(url));
261 Assert.Contains("<code>a.txt</code>", page);
262 Assert.Contains("<<<<<<< ", page);
263 Assert.Contains("TWO from main", page);
264 Assert.Contains("TWO from feature", page);
265
266 Dictionary<string, string> Form(string choice, string text = "") => new()
267 {
268 ["base_sha"] = s.MainSha,
269 ["head_sha"] = s.FeatureSha,
270 ["choice_0"] = choice,
271 ["text_0"] = text,
272 ["message"] = "",
273 };
274
275 // Leftover markers are refused.
276 var leftover = await ForgeHost.PostFormAsync(owner, url, "resolve", Form("edit", "one\r\n<<<<<<< main\r\nTWO\r\n>>>>>>> feature\r\nthree\r\n"));
277 Assert.Contains("still contains conflict markers", await ForgeHost.TextAsync(leftover));
278
279 // A stale page (the branch moved since) is refused.
280 var stale = Form("ours");
281 stale["base_sha"] = s.FeatureSha;
282 Assert.Contains("changed in the meantime", await ForgeHost.TextAsync(await ForgeHost.PostFormAsync(owner, url, "resolve", stale)));
283 Assert.Equal(s.MainSha, await s.ServerAsync("rev-parse", "server/main"));
284
285 // An edited resolution: browsers send CRLF, the file keeps its LF endings.
286 var resolved = await ForgeHost.PostFormAsync(owner, url, "resolve", Form("edit", "one\r\nTWO from both\r\nthree\r\n"));
287 Assert.Equal(HttpStatusCode.Redirect, resolved.StatusCode);
288 Assert.Equal($"{s.MainSha} {s.FeatureSha}", await s.ServerAsync("log", "-1", "--format=%P", "server/main"));
289 var bytes = await host.Git.RunAsync(s.Work, "cat-file", "blob", "server/main:a.txt");
290 Assert.Equal("one\nTWO from both\nthree\n", bytes.StdOut);
291 // The non-conflicting part of the merge came along.
292 Assert.Equal("new file\nsecond line", await host.Git.MustAsync(s.Work, "show", "server/main:b.txt"));
293
294 // Taking one side wholesale.
295 var theirs = await BranchScenario.CreateAsync(host, "resolve-theirs", diverge: true, conflict: true);
296 var taken = await ForgeHost.PostFormAsync(owner, theirs.Page("conflicts/main...feature/x"), "resolve", new()
297 {
298 ["base_sha"] = theirs.MainSha,
299 ["head_sha"] = theirs.FeatureSha,
300 ["choice_0"] = "theirs",
301 ["message"] = "Take the feature's version",
302 });
303 Assert.Equal(HttpStatusCode.Redirect, taken.StatusCode);
304 Assert.Equal("Take the feature's version", await theirs.ServerAsync("log", "-1", "--format=%s", "server/main"));
305 Assert.Equal("one\nTWO from feature\nthree", await host.Git.MustAsync(theirs.Work, "show", "server/main:a.txt"));
306 }
307
308 [Fact]
309 public async Task Pull_request_goes_from_open_to_merged_with_comments()
310 {
311 var s = await BranchScenario.CreateAsync(host, "pulls", diverge: true);
312 using var owner = await host.CreateSignedInClientAsync();
313 using var anonymous = host.CreateClient();
314 var compare = s.Page("compare/main...feature/x");
315
316 // Opened from the compare page.
317 var opened = await ForgeHost.PostFormAsync(owner, compare, "open-pull", new()
318 {
319 ["Title"] = "Add the feature",
320 ["Description"] = "Adds **b.txt**.\n\n<script>alert(1)</script>",
321 });
322 Assert.Equal("/jessie/pulls/pull/1", opened.Headers.Location?.PathAndQuery);
323
324 // A second one for the same branches is refused, and the compare page points at the first.
325 var duplicate = await ForgeHost.PostFormAsync(owner, s.Page("compare/main..feature/x"), "open-pull", new() { ["Title"] = "Again" });
326 Assert.False(duplicate.IsSuccessStatusCode && (await ForgeHost.TextAsync(duplicate)).Contains("Again"));
327 Assert.Contains("href=\"/jessie/pulls/pull/1\"", await owner.GetStringAsync(compare));
328
329 // Everyone who can read the repository can read the pull request.
330 var page = await ForgeHost.TextAsync(await anonymous.GetAsync(s.Page("pull/1")));
331 Assert.Contains("Add the feature", page);
332 Assert.Contains("<strong>b.txt</strong>", page);
333 Assert.DoesNotContain("<script>alert(1)</script>", page);
334 Assert.Contains("More feature work", page);
335 Assert.Contains("TWO from feature", page);
336 Assert.Contains("2 commits", page);
337 Assert.DoesNotContain("name=\"Method\"", page);
338 Assert.Contains("Add the feature", await anonymous.GetStringAsync(s.Page("pulls")));
339
340 // Only the owner comments.
341 await ForgeHost.PostFormAsync(anonymous, s.Page("pull/1"), "comment", new() { ["Body"] = "drive-by" });
342 var commented = await ForgeHost.PostFormAsync(owner, s.Page("pull/1"), "comment", new() { ["Body"] = "Looks *good*." });
343 var commentedHtml = await ForgeHost.TextAsync(commented);
344 Assert.Contains("<em>good</em>", commentedHtml);
345 Assert.Contains("1 comment", commentedHtml);
346 Assert.DoesNotContain("drive-by", commentedHtml);
347
348 // Close and reopen.
349 var closed = await ForgeHost.PostFormAsync(owner, s.Page("pull/1"), "pull-state", new() { ["Action"] = "close" });
350 Assert.DoesNotContain("name=\"Method\"", await ForgeHost.TextAsync(closed));
351 Assert.Equal(PullRequestStatus.Closed, (await DbAsync(db => db.PullRequests.SingleAsync(p => p.RepoId == s.Repo.Id))).Status);
352 Assert.Contains("Add the feature", await anonymous.GetStringAsync(s.Page("pulls?state=closed")));
353 // A closed pull request still shows what it proposed.
354 Assert.Contains("TWO from feature", await anonymous.GetStringAsync(s.Page("pull/1")));
355 var reopened = await ForgeHost.PostFormAsync(owner, s.Page("pull/1"), "pull-state", new() { ["Action"] = "reopen" });
356 Assert.Contains("name=\"Method\"", await ForgeHost.TextAsync(reopened));
357
358 // Merge with a squash and delete the branch.
359 var merged = await ForgeHost.PostFormAsync(owner, s.Page("pull/1"), "merge", new()
360 {
361 ["Method"] = "squash",
362 ["Message"] = "Add the feature (#1)",
363 ["DeleteBranch"] = "true",
364 });
365 var mergedHtml = await ForgeHost.TextAsync(merged);
366 Assert.Contains("Merged into main.", mergedHtml);
367 Assert.DoesNotContain("name=\"Method\"", mergedHtml);
368
369 var pull = await DbAsync(db => db.PullRequests.SingleAsync(p => p.RepoId == s.Repo.Id));
370 Assert.Equal(PullRequestStatus.Merged, pull.Status);
371 Assert.Equal(s.FeatureSha, pull.HeadSha);
372 Assert.Equal(pull.MergeCommitSha, await s.ServerAsync("rev-parse", "server/main"));
373 Assert.Equal("Add the feature (#1)", await host.Git.MustAsync(s.Work, "log", "-1", "--format=%s", "server/main"));
374 Assert.DoesNotContain("server/feature/x", await host.Git.MustAsync(s.Work, "branch", "-r"));
375
376 // The branch is gone, but the merged pull request keeps its commits and diff.
377 var after = await anonymous.GetStringAsync(s.Page("pull/1"));
378 Assert.Contains("More feature work", after);
379 Assert.Contains("TWO from feature", after);
380
381 // Title and description can be corrected afterwards; visitors cannot do it.
382 await ForgeHost.PostFormAsync(anonymous, s.Page("pull/1"), "edit-pull", new() { ["Title"] = "Hijacked" });
383 var edited = await ForgeHost.PostFormAsync(owner, s.Page("pull/1"), "edit-pull", new() { ["Title"] = "Add the feature, renamed", ["Description"] = "New *text*." });
384 var editedHtml = await ForgeHost.TextAsync(edited);
385 Assert.Contains("Add the feature, renamed", editedHtml);
386 Assert.Contains("<em>text</em>", editedHtml);
387 Assert.DoesNotContain("Hijacked", editedHtml);
388
389 // Private repositories keep their pull requests to themselves.
390 var secret = await BranchScenario.CreateAsync(host, "pulls-private", visibility: Visibility.Private);
391 await ForgeHost.PostFormAsync(owner, secret.Page("compare/main...feature/x"), "open-pull", new() { ["Title"] = "Secret" });
392 Assert.Equal(HttpStatusCode.OK, (await owner.GetAsync(secret.Page("pull/1"))).StatusCode);
393 Assert.Equal(HttpStatusCode.NotFound, (await anonymous.GetAsync(secret.Page("pull/1"))).StatusCode);
394 Assert.Equal(HttpStatusCode.NotFound, (await anonymous.GetAsync(secret.Page("pulls"))).StatusCode);
395 Assert.Equal(HttpStatusCode.NotFound, (await owner.GetAsync(s.Page("pull/99"))).StatusCode);
396 }
397
398 [Fact]
399 public async Task Pull_request_notices_a_merge_made_with_git()
400 {
401 var s = await BranchScenario.CreateAsync(host, "pulls-external", diverge: true);
402 using var owner = await host.CreateSignedInClientAsync();
403 await ForgeHost.PostFormAsync(owner, s.Page("compare/main...feature/x"), "open-pull", new() { ["Title"] = "Merged elsewhere" });
404
405 await host.Git.MustAsync(s.Work, "merge", "--no-ff", "-m", "Merge locally", "feature/x");
406 await host.Git.MustAsync(s.Work, "push", s.Url, "main");
407
408 Assert.Contains("Merged into main.", await ForgeHost.TextAsync(await owner.GetAsync(s.Page("pull/1"))));
409 Assert.Equal(PullRequestStatus.Merged, (await DbAsync(db => db.PullRequests.SingleAsync(p => p.RepoId == s.Repo.Id))).Status);
410 }
411
412 [Fact]
413 public async Task Conflicting_pull_request_is_merged_through_the_conflict_page()
414 {
415 var s = await BranchScenario.CreateAsync(host, "pulls-conflict", diverge: true, conflict: true);
416 using var owner = await host.CreateSignedInClientAsync();
417 await ForgeHost.PostFormAsync(owner, s.Page("compare/main...feature/x"), "open-pull", new() { ["Title"] = "Needs a hand" });
418
419 var page = await owner.GetStringAsync(s.Page("pull/1"));
420 Assert.Contains("These branches have conflicts.", page);
421 Assert.Contains("href=\"/jessie/pulls-conflict/conflicts/main...feature/x\"", page);
422 Assert.DoesNotContain("name=\"Method\"", page);
423
424 await ForgeHost.PostFormAsync(owner, s.Page("conflicts/main...feature/x"), "resolve", new()
425 {
426 ["base_sha"] = s.MainSha,
427 ["head_sha"] = s.FeatureSha,
428 ["choice_0"] = "ours",
429 });
430
431 var pull = await DbAsync(db => db.PullRequests.SingleAsync(p => p.RepoId == s.Repo.Id));
432 Assert.Equal(PullRequestStatus.Merged, pull.Status);
433 Assert.Equal(pull.MergeCommitSha, await s.ServerAsync("rev-parse", "server/main"));
434 Assert.Equal("one\nTWO from main\nthree", await host.Git.MustAsync(s.Work, "show", "server/main:a.txt"));
435 }
436
437 [Fact]
438 public async Task Protected_branch_refuses_force_pushes_and_deletion_but_not_ordinary_work()
439 {
440 var s = await BranchScenario.CreateAsync(host, "protected");
441 using var owner = await host.CreateSignedInClientAsync();
442 var settings = s.Page("settings/branches");
443
444 var invalid = await ForgeHost.PostFormAsync(owner, settings, "add-rule", new() { ["Pattern"] = "--force" });
445 Assert.Contains("This is not a valid branch name.", await ForgeHost.TextAsync(invalid));
446 var added = await ForgeHost.PostFormAsync(owner, settings, "add-rule", new() { ["Pattern"] = "main" });
447 Assert.Contains("<code>main</code>", await ForgeHost.TextAsync(added));
448
449 // An ordinary push still goes through.
450 await File.WriteAllTextAsync(Path.Combine(s.Work, "d.txt"), "more\n");
451 await host.Git.MustAsync(s.Work, "add", "-A");
452 await host.Git.MustAsync(s.Work, "commit", "-m", "Normal work");
453 await host.Git.MustAsync(s.Work, "push", s.Url, "main");
454 var tip = await host.Git.MustAsync(s.Work, "rev-parse", "HEAD");
455
456 // Rewriting history on it does not, and neither does deleting it.
457 await host.Git.MustAsync(s.Work, "commit", "--amend", "-m", "Rewritten");
458 var forced = await host.Git.RunAsync(s.Work, "push", "--force", s.Url, "main");
459 Assert.False(forced.Ok);
460 Assert.Contains("non-fast-forward", forced.StdErr);
461 await host.Git.MustAsync(s.Work, "push", s.Url, "feature/x:refs/heads/spare");
462 Assert.False((await host.Git.RunAsync(s.Work, "push", s.Url, "--delete", "main")).Ok);
463 Assert.Equal(tip, await s.ServerAsync("rev-parse", "server/main"));
464
465 // Branches that are not protected behave as before, in a push of their own.
466 await host.Git.MustAsync(s.Work, "push", "--force", s.Url, "main:refs/heads/spare");
467 await host.Git.MustAsync(s.Work, "push", s.Url, "--delete", "spare");
468
469 // The rule can be removed again.
470 var ruleId = (await DbAsync(db => db.BranchProtections.SingleAsync(r => r.RepoId == s.Repo.Id))).Id;
471 await ForgeHost.PostFormAsync(owner, settings, "remove-rule", new() { ["RuleId"] = ruleId.ToString() });
472 await host.Git.MustAsync(s.Work, "push", "--force", s.Url, "main");
473
474 using var anonymous = host.CreateClient();
475 Assert.Equal(HttpStatusCode.NotFound, (await anonymous.GetAsync(settings)).StatusCode);
476 }
477
478 [Fact]
479 public async Task Branch_closed_to_pushes_changes_only_through_the_web()
480 {
481 var s = await BranchScenario.CreateAsync(host, "web-only");
482 using var owner = await host.CreateSignedInClientAsync();
483 await ForgeHost.PostFormAsync(owner, s.Page("settings/branches"), "add-rule", new() { ["Pattern"] = "release/*", ["BlockPush"] = "true" });
484 await ForgeHost.PostFormAsync(owner, s.Page("branches"), "create-branch", new() { ["NewName"] = "release/1.0", ["From"] = "main" });
485
486 // Git may not push to it, even fast-forward…
487 var pushed = await host.Git.RunAsync(s.Work, "push", s.Url, "feature/x:refs/heads/release/1.0");
488 Assert.False(pushed.Ok);
489 Assert.Contains("hidden ref", pushed.StdErr);
490 Assert.Equal(s.MainSha, await s.ServerAsync("rev-parse", "server/release/1.0"));
491
492 // …the web may not delete it…
493 var deleted = await ForgeHost.PostFormAsync(owner, s.Page("branches"), "delete-branch", new() { ["DeleteName"] = "release/1.0" });
494 Assert.Contains("This branch is protected and cannot be deleted.", await ForgeHost.TextAsync(deleted));
495
496 // …but a merge on the web moves it, and other branches still take pushes.
497 var merged = await ForgeHost.PostFormAsync(owner, s.Page("compare/release/1.0...feature/x"), "merge", new() { ["Method"] = "ff" });
498 Assert.Equal(HttpStatusCode.Redirect, merged.StatusCode);
499 Assert.Equal(s.FeatureSha, await s.ServerAsync("rev-parse", "server/release/1.0"));
500 await host.Git.MustAsync(s.Work, "push", s.Url, "feature/x:refs/heads/main");
501 }
502 }
added forge.Tests/GitLayerTests.cs +325 −0View file
@@ -0,0 +1,325 @@
1 using Forge.Git;
2 using Forge.Tests.Support;
3 using Microsoft.Extensions.Options;
4
5 namespace Forge.Tests;
6
7 /// <summary>
8 /// A real repository in a temp directory with the awkward cases in it: a branch with a slash,
9 /// annotated and lightweight tags, a binary file, a file with a space in its name, and a rename.
10 /// </summary>
11 public sealed class GitRepoFixture : IAsyncLifetime
12 {
13 private readonly TempDir _temp = new();
14
15 public GitCli Cli { get; private set; } = null!;
16 public GitRepo Repo { get; private set; } = null!;
17 public RefResolver Resolver { get; private set; } = null!;
18 public string DataPath { get; private set; } = "";
19
20 /// <summary>The .git directory of the working repository; the git layer only needs a git dir.</summary>
21 public string RepoPath { get; private set; } = "";
22
23 public string FirstSha { get; private set; } = "";
24 public string SecondSha { get; private set; } = "";
25 public string FeatureSha { get; private set; } = "";
26
27 public async Task InitializeAsync()
28 {
29 DataPath = _temp.Sub("data");
30 var options = Options.Create(new ForgeOptions { DataPath = DataPath, GitPath = TestGit.Executable });
31 Cli = new GitCli(options);
32 Repo = new GitRepo(Cli);
33 Resolver = new RefResolver(Repo);
34
35 var git = new TestGit(_temp.Sub("home"));
36 var work = _temp.Sub("work");
37 await git.MustAsync(work, "init", "--initial-branch=main", ".");
38
39 Directory.CreateDirectory(Path.Combine(work, "src"));
40 await File.WriteAllTextAsync(Path.Combine(work, "README.md"), "# Fixture\n");
41 await File.WriteAllTextAsync(Path.Combine(work, "src", "a.cs"), "line one\nline two\nline three\n");
42 await File.WriteAllTextAsync(Path.Combine(work, "file with space.txt"), "spaced\n");
43 await File.WriteAllTextAsync(Path.Combine(work, "old.txt"), "this file will be renamed\nwithout changes\n");
44 await File.WriteAllBytesAsync(Path.Combine(work, "binary.bin"), [1, 2, 0, 3, 4, 0, 255]);
45 await git.MustAsync(work, "add", "-A");
46 await git.MustAsync(work, "commit", "-m", "First commit", "-m", "With a body.\nOn two lines.");
47 FirstSha = await git.MustAsync(work, "rev-parse", "HEAD");
48
49 await File.WriteAllTextAsync(Path.Combine(work, "src", "a.cs"), "line one\nline 2\nline three\nline four\n");
50 await git.MustAsync(work, "mv", "old.txt", "new.txt");
51 await git.MustAsync(work, "add", "-A");
52 await git.MustAsync(work, "commit", "-m", "Second commit");
53 SecondSha = await git.MustAsync(work, "rev-parse", "HEAD");
54
55 await git.MustAsync(work, "tag", "-a", "v1.0", "-m", "Release 1.0");
56 await git.MustAsync(work, "tag", "light");
57
58 await git.MustAsync(work, "checkout", "-b", "feature/x");
59 await File.WriteAllTextAsync(Path.Combine(work, "src", "feature.txt"), "feature\n");
60 await git.MustAsync(work, "add", "-A");
61 await git.MustAsync(work, "commit", "-m", "Feature commit");
62 FeatureSha = await git.MustAsync(work, "rev-parse", "HEAD");
63 await git.MustAsync(work, "checkout", "main");
64
65 RepoPath = Path.Combine(work, ".git");
66 }
67
68 public Task DisposeAsync()
69 {
70 _temp.Dispose();
71 return Task.CompletedTask;
72 }
73 }
74
75 public class GitLayerTests(GitRepoFixture fx) : IClassFixture<GitRepoFixture>
76 {
77 [Fact]
78 public async Task Version_is_reported()
79 {
80 var version = await fx.Cli.GetVersionAsync();
81 Assert.True(version >= ForgeApp.MinimumGitVersion, $"git {version} is older than {ForgeApp.MinimumGitVersion}");
82 }
83
84 [Fact]
85 public async Task Missing_git_gives_a_clear_error()
86 {
87 var cli = new GitCli(Options.Create(new ForgeOptions { DataPath = fx.DataPath, GitPath = "git-that-does-not-exist" }));
88 var ex = await Assert.ThrowsAsync<GitException>(() => cli.GetVersionAsync());
89 Assert.Contains("git-that-does-not-exist", ex.Message);
90 }
91
92 [Fact]
93 public async Task Refs_list_branches_and_tags()
94 {
95 var refs = await fx.Repo.ListRefsAsync(fx.RepoPath);
96
97 var main = Assert.Single(refs, r => r is { Kind: RefKind.Branch, Name: "main" });
98 Assert.Equal(fx.SecondSha, main.Sha);
99 Assert.Equal("Second commit", main.Subject);
100 Assert.NotNull(main.Date);
101
102 var feature = Assert.Single(refs, r => r is { Kind: RefKind.Branch, Name: "feature/x" });
103 Assert.Equal(fx.FeatureSha, feature.TargetSha);
104
105 var annotated = Assert.Single(refs, r => r is { Kind: RefKind.Tag, Name: "v1.0" });
106 Assert.Equal("tag", annotated.ObjectType);
107 Assert.NotEqual(fx.SecondSha, annotated.Sha);
108 Assert.Equal(fx.SecondSha, annotated.TargetSha);
109 Assert.Equal("Release 1.0", annotated.Subject);
110
111 var light = Assert.Single(refs, r => r is { Kind: RefKind.Tag, Name: "light" });
112 Assert.Equal(fx.SecondSha, light.Sha);
113 Assert.Null(light.PeeledSha);
114 }
115
116 [Fact]
117 public async Task Tree_lists_root_and_subdirectory()
118 {
119 var rootSha = await fx.Repo.GetRootTreeShaAsync(fx.RepoPath, fx.SecondSha);
120 Assert.NotNull(rootSha);
121 var root = await fx.Repo.ListTreeAsync(fx.RepoPath, rootSha);
122
123 Assert.Equal(
124 ["README.md", "binary.bin", "file with space.txt", "new.txt", "src"],
125 root.Select(e => e.Name).Order(StringComparer.Ordinal));
126 Assert.True(root.Single(e => e.Name == "src").IsTree);
127 Assert.Equal(7, root.Single(e => e.Name == "binary.bin").Size);
128
129 var src = await fx.Repo.GetEntryAsync(fx.RepoPath, fx.SecondSha, "src");
130 Assert.True(src is { IsTree: true });
131 var children = await fx.Repo.ListTreeAsync(fx.RepoPath, src.Sha);
132 Assert.Equal("a.cs", Assert.Single(children).Name);
133 }
134
135 [Fact]
136 public async Task Entry_lookup_handles_spaces_and_missing_paths()
137 {
138 var spaced = await fx.Repo.GetEntryAsync(fx.RepoPath, fx.SecondSha, "file with space.txt");
139 Assert.True(spaced is { IsBlob: true, Name: "file with space.txt" });
140
141 var nested = await fx.Repo.GetEntryAsync(fx.RepoPath, fx.SecondSha, "src/a.cs");
142 Assert.Equal("a.cs", nested?.Name);
143
144 Assert.Null(await fx.Repo.GetEntryAsync(fx.RepoPath, fx.SecondSha, "nope.txt"));
145 // Pathspec magic and option-like paths are plain (missing) file names.
146 Assert.Null(await fx.Repo.GetEntryAsync(fx.RepoPath, fx.SecondSha, ":(glob)**"));
147 Assert.Null(await fx.Repo.GetEntryAsync(fx.RepoPath, fx.SecondSha, "--name-only"));
148 }
149
150 [Fact]
151 public async Task Blob_is_read_with_size_and_cap()
152 {
153 var entry = await fx.Repo.GetEntryAsync(fx.RepoPath, fx.SecondSha, "src/a.cs");
154 Assert.NotNull(entry);
155 Assert.Equal(entry.Size, await fx.Repo.GetBlobSizeAsync(fx.RepoPath, entry.Sha));
156
157 var blob = await fx.Repo.ReadBlobAsync(fx.RepoPath, entry.Sha, 1024);
158 Assert.False(blob.Truncated);
159 Assert.False(blob.IsBinary);
160 Assert.Equal("line one\nline 2\nline three\nline four\n", blob.Text);
161
162 var capped = await fx.Repo.ReadBlobAsync(fx.RepoPath, entry.Sha, 8);
163 Assert.True(capped.Truncated);
164 Assert.Equal("line one", capped.Text);
165
166 var binary = await fx.Repo.GetEntryAsync(fx.RepoPath, fx.SecondSha, "binary.bin");
167 Assert.True((await fx.Repo.ReadBlobAsync(fx.RepoPath, binary!.Sha, 1024)).IsBinary);
168 }
169
170 [Fact]
171 public async Task Log_pages_and_filters_by_path()
172 {
173 var all = await fx.Repo.LogAsync(fx.RepoPath, fx.SecondSha);
174 Assert.Equal([fx.SecondSha, fx.FirstSha], all.Select(c => c.Sha));
175 Assert.Equal("First commit", all[1].Subject);
176 Assert.Equal("With a body.\nOn two lines.", all[1].Body);
177 Assert.Equal("Test Author", all[1].AuthorName);
178 Assert.Equal("author@example.com", all[1].AuthorEmail);
179 Assert.Equal([fx.FirstSha], all[0].Parents);
180
181 var second = await fx.Repo.LogAsync(fx.RepoPath, fx.SecondSha, skip: 1, take: 1);
182 Assert.Equal(fx.FirstSha, Assert.Single(second).Sha);
183
184 var readme = await fx.Repo.LogAsync(fx.RepoPath, fx.SecondSha, "README.md");
185 Assert.Equal(fx.FirstSha, Assert.Single(readme).Sha);
186
187 var range = await fx.Repo.LogRangeAsync(fx.RepoPath, fx.FirstSha, fx.FeatureSha, 20);
188 Assert.Equal([fx.FeatureSha, fx.SecondSha], range.Select(c => c.Sha));
189 }
190
191 [Fact]
192 public async Task Commit_diff_has_stats_hunks_and_renames()
193 {
194 var commit = await fx.Repo.GetCommitAsync(fx.RepoPath, fx.SecondSha);
195 Assert.Equal("Second commit", commit?.Subject);
196
197 var diff = await fx.Repo.GetDiffAsync(fx.RepoPath, fx.SecondSha);
198
199 var stat = Assert.Single(diff.Stats, s => s.Path == "src/a.cs");
200 Assert.Equal((2, 1), (stat.Added, stat.Deleted));
201 var renameStat = Assert.Single(diff.Stats, s => s.Path == "new.txt");
202 Assert.Equal("old.txt", renameStat.OldPath);
203
204 var modified = Assert.Single(diff.Patch.Files, f => f.NewPath == "src/a.cs");
205 Assert.Equal(FileChange.Modified, modified.Change);
206 var lines = modified.Hunks.SelectMany(h => h.Lines).ToList();
207 Assert.Contains(new DiffLine(DiffLineKind.Deleted, 2, null, "line two"), lines);
208 Assert.Contains(new DiffLine(DiffLineKind.Added, null, 2, "line 2"), lines);
209 Assert.Contains(new DiffLine(DiffLineKind.Added, null, 4, "line four"), lines);
210
211 var renamed = Assert.Single(diff.Patch.Files, f => f.Change == FileChange.Renamed);
212 Assert.Equal(("old.txt", "new.txt"), (renamed.OldPath, renamed.NewPath));
213 }
214
215 [Fact]
216 public async Task Root_commit_diff_marks_binary_files_and_reads_names_with_spaces()
217 {
218 var diff = await fx.Repo.GetDiffAsync(fx.RepoPath, fx.FirstSha);
219
220 Assert.True(Assert.Single(diff.Stats, s => s.Path == "binary.bin").IsBinary);
221 var binary = Assert.Single(diff.Patch.Files, f => f.NewPath == "binary.bin");
222 Assert.True(binary.IsBinary);
223 Assert.Equal(FileChange.Added, binary.Change);
224
225 var spaced = Assert.Single(diff.Patch.Files, f => f.NewPath == "file with space.txt");
226 Assert.Equal(FileChange.Added, spaced.Change);
227 Assert.Equal(1, spaced.Added);
228 }
229
230 [Fact]
231 public async Task Ahead_behind_counts_both_sides()
232 {
233 Assert.Equal((1, 0), await fx.Repo.AheadBehindAsync(fx.RepoPath, fx.SecondSha, fx.FeatureSha));
234 Assert.Equal((0, 2), await fx.Repo.AheadBehindAsync(fx.RepoPath, fx.FeatureSha, fx.FirstSha));
235 }
236
237 [Fact]
238 public async Task Resolver_handles_slashes_tags_shas_and_hostile_input()
239 {
240 var branch = await fx.Resolver.ResolveAsync(fx.RepoPath, "feature/x/src/feature.txt");
241 Assert.Equal(new ResolvedRef("feature/x", ResolvedKind.Branch, fx.FeatureSha, "src/feature.txt"), branch);
242
243 var tag = await fx.Resolver.ResolveAsync(fx.RepoPath, "v1.0/src");
244 Assert.Equal(new ResolvedRef("v1.0", ResolvedKind.Tag, fx.SecondSha, "src"), tag);
245
246 var sha = await fx.Resolver.ResolveAsync(fx.RepoPath, fx.FirstSha + "/README.md");
247 Assert.Equal(new ResolvedRef(fx.FirstSha, ResolvedKind.Commit, fx.FirstSha, "README.md"), sha);
248
249 Assert.Null(await fx.Resolver.ResolveAsync(fx.RepoPath, new string('0', 40)));
250 Assert.Null(await fx.Resolver.ResolveAsync(fx.RepoPath, "missing/README.md"));
251
252 // The checklist case: a "ref" shaped like an option must resolve to nothing and run nothing.
253 var marker = Path.Combine(fx.DataPath, "pwned");
254 Assert.Null(await fx.Resolver.ResolveAsync(fx.RepoPath, $"--upload-pack=touch {marker}"));
255 Assert.Null(await fx.Resolver.ResolveAsync(fx.RepoPath, "--output=" + marker));
256 Assert.False(File.Exists(marker));
257 }
258
259 [Fact]
260 public async Task Commit_lookup_accepts_hex_only()
261 {
262 Assert.Equal(fx.SecondSha, await fx.Repo.ResolveCommitAsync(fx.RepoPath, fx.SecondSha[..10]));
263 Assert.Null(await fx.Repo.ResolveCommitAsync(fx.RepoPath, "main"));
264 Assert.Null(await fx.Repo.ResolveCommitAsync(fx.RepoPath, "--all"));
265 Assert.Null(await fx.Repo.ResolveCommitAsync(fx.RepoPath, "HEAD~1"));
266 }
267
268 [Fact]
269 public async Task Init_creates_a_bare_repository_on_main_with_fsck_enabled()
270 {
271 var path = Path.Combine(fx.DataPath, "repos", "77.git");
272 Directory.CreateDirectory(Path.GetDirectoryName(path)!);
273
274 await fx.Repo.InitBareAsync(path);
275
276 Assert.True(File.Exists(Path.Combine(path, "HEAD")));
277 Assert.Equal("main", await fx.Repo.GetHeadBranchAsync(path));
278 Assert.Empty(await fx.Repo.ListRefsAsync(path));
279 var config = await fx.Cli.RunAsync(path, ["config", "--get", "receive.fsckObjects"]);
280 Assert.Equal("true", config.Text.Trim());
281 var bare = await fx.Cli.RunAsync(path, ["rev-parse", "--is-bare-repository"]);
282 Assert.Equal("true", bare.Text.Trim());
283 }
284
285 [Fact]
286 public async Task Timeout_kills_the_process()
287 {
288 // cat-file --batch waits for stdin forever; a stream that never ends keeps it alive.
289 await using var never = new NeverEndingStream();
290 await Assert.ThrowsAsync<GitTimeoutException>(() =>
291 fx.Cli.RunAsync(fx.RepoPath, ["cat-file", "--batch"], stdin: never, timeout: TimeSpan.FromMilliseconds(500)));
292 }
293
294 [Fact]
295 public async Task Cancellation_kills_the_process()
296 {
297 await using var never = new NeverEndingStream();
298 using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(300));
299 await Assert.ThrowsAnyAsync<OperationCanceledException>(() =>
300 fx.Cli.RunAsync(fx.RepoPath, ["cat-file", "--batch"], stdin: never, ct: cts.Token));
301 }
302
303 private sealed class NeverEndingStream : Stream
304 {
305 public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
306 {
307 await Task.Delay(Timeout.Infinite, cancellationToken);
308 return 0;
309 }
310
311 public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
312 ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
313
314 public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
315 public override bool CanRead => true;
316 public override bool CanSeek => false;
317 public override bool CanWrite => false;
318 public override long Length => throw new NotSupportedException();
319 public override long Position { get => 0; set => throw new NotSupportedException(); }
320 public override void Flush() { }
321 public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
322 public override void SetLength(long value) => throw new NotSupportedException();
323 public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
324 }
325 }
added forge.Tests/InsightsTests.cs +87 −0View file
@@ -0,0 +1,87 @@
1 using Forge.Features.Browse;
2 using Forge.Git;
3
4 namespace Forge.Tests;
5
6 public class InsightsTests
7 {
8 [Fact]
9 public void Languages_are_shared_by_bytes_and_ignore_data_and_vendored_files()
10 {
11 var shares = RepoInsights.ComputeLanguages(
12 [
13 new FileEntry("src/App.cs", 600),
14 new FileEntry("src/Deep/Other.cs", 150),
15 new FileEntry("web/site.js", 250),
16 new FileEntry("README.md", 10_000),
17 new FileEntry("package.json", 10_000),
18 new FileEntry("node_modules/left-pad/index.js", 50_000),
19 new FileEntry("web/wwwroot/lib/highlight/highlight.min.js", 50_000),
20 new FileEntry("web/jquery.min.js", 50_000),
21 new FileEntry("empty.py", 0),
22 ]);
23
24 Assert.Equal(["csharp", "javascript"], shares.Select(s => s.Key));
25 Assert.Equal("C#", shares[0].Name);
26 Assert.Equal(75.0, shares[0].Percent, 3);
27 Assert.Equal(25.0, shares[1].Percent, 3);
28 }
29
30 [Fact]
31 public void Languages_beyond_the_first_six_are_grouped_as_other()
32 {
33 string[] extensions = [".cs", ".js", ".ts", ".py", ".go", ".rs", ".java", ".rb"];
34 var files = extensions.Select((ext, i) => new FileEntry("file" + ext, 1000 - i * 100)).ToList();
35
36 var shares = RepoInsights.ComputeLanguages(files);
37
38 Assert.Equal(7, shares.Count);
39 Assert.Equal("other", shares[^1].Key);
40 Assert.Null(shares[^1].Name);
41 Assert.Equal(100.0, shares.Sum(s => s.Percent), 3);
42 }
43
44 [Fact]
45 public void A_repository_without_code_has_no_languages()
46 {
47 Assert.Empty(RepoInsights.ComputeLanguages([new FileEntry("README.md", 100), new FileEntry("data.json", 5)]));
48 }
49
50 [Fact]
51 public void Activity_counts_people_by_email_and_commits_by_utc_day()
52 {
53 var day = new DateTimeOffset(2026, 3, 10, 23, 30, 0, TimeSpan.Zero);
54 var activity = RepoInsights.ComputeActivity(
55 [
56 ("Jessie", "jessie@example.com", day.AddHours(1)), // Already the 11th in UTC.
57 ("jessie (laptop)", "Jessie@Example.com", day),
58 ("Sam", "sam@example.com", day.AddDays(-2)),
59 ("Jessie", "jessie@example.com", day.AddDays(-3)),
60 ], limit: 100);
61
62 Assert.Equal(4, activity.Commits);
63 Assert.False(activity.Truncated);
64 Assert.Equal(["Jessie", "Sam"], activity.Contributors.Select(c => c.Name));
65 Assert.Equal(3, activity.Contributors[0].Commits);
66 Assert.Equal(day.AddDays(-3), activity.Contributors[0].First);
67 Assert.Equal(day.AddHours(1), activity.Contributors[0].Last);
68 Assert.Equal(1, activity.CommitsByDay[new DateOnly(2026, 3, 11)]);
69 Assert.Equal(1, activity.CommitsByDay[new DateOnly(2026, 3, 10)]);
70 Assert.False(activity.CommitsByDay.ContainsKey(new DateOnly(2026, 3, 9)));
71
72 Assert.True(RepoInsights.ComputeActivity([("A", "a@example.com", day)], limit: 1).Truncated);
73 }
74
75 [Fact]
76 public void File_list_keeps_full_paths_and_skips_submodules()
77 {
78 var output =
79 "100644 blob 1111111111111111111111111111111111111111 12\tREADME.md\0"
80 + "160000 commit 2222222222222222222222222222222222222222 -\tvendor/sub\0"
81 + "100755 blob 3333333333333333333333333333333333333333 2048\tsrc/dir with space/run.sh\0";
82
83 var files = GitParsers.ParseFileList(output);
84
85 Assert.Equal([new FileEntry("README.md", 12), new FileEntry("src/dir with space/run.sh", 2048)], files);
86 }
87 }
added forge.Tests/LocalizationTests.cs +227 −0View file
@@ -0,0 +1,227 @@
1 using System.Globalization;
2 using System.Net;
3 using System.Text.RegularExpressions;
4 using Forge.Localization;
5 using Forge.Tests.Support;
6
7 namespace Forge.Tests;
8
9 public partial class LocalizationTests(ForgeHost host) : IClassFixture<ForgeHost>
10 {
11 private static readonly Translations Translations = new();
12 private static readonly Localizer T = new(Translations);
13
14 private static TResult In<TResult>(string culture, Func<TResult> action)
15 {
16 var (ui, format) = (CultureInfo.CurrentUICulture, CultureInfo.CurrentCulture);
17 try
18 {
19 CultureInfo.CurrentUICulture = CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(culture);
20 return action();
21 }
22 finally
23 {
24 (CultureInfo.CurrentUICulture, CultureInfo.CurrentCulture) = (ui, format);
25 }
26 }
27
28 /// <summary>Every English text the code can display: T["…"], T.Html("…"), Localizer.Key("…") and T.Plural(n, "…", "…").</summary>
29 private static HashSet<string> KeysUsedInSource()
30 {
31 var keys = new HashSet<string>(StringComparer.Ordinal);
32 var files = Directory.EnumerateFiles(ForgeHost.WebProjectDirectory, "*.*", SearchOption.AllDirectories)
33 .Where(f => f.EndsWith(".razor", StringComparison.Ordinal) || f.EndsWith(".cs", StringComparison.Ordinal))
34 .Where(f => !f.Contains(Path.DirectorySeparatorChar + "obj" + Path.DirectorySeparatorChar)
35 && !f.Contains(Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar));
36 foreach (var file in files)
37 {
38 var source = File.ReadAllText(file);
39 foreach (Match m in SingleKey().Matches(source))
40 {
41 keys.Add(Regex.Unescape(m.Groups[1].Value));
42 }
43
44 foreach (Match m in PluralKey().Matches(source))
45 {
46 keys.Add(m.Groups[1].Value + "|" + m.Groups[2].Value);
47 }
48 }
49
50 return keys;
51 }
52
53 [Fact]
54 public void English_is_first_and_slovak_is_available()
55 {
56 Assert.Equal("en", Translations.Languages[0]);
57 Assert.Contains("sk", Translations.Languages);
58 }
59
60 [Fact]
61 public void Every_language_translates_every_text_and_nothing_else()
62 {
63 var used = KeysUsedInSource();
64 Assert.True(used.Count > 150, $"Only {used.Count} keys found in the sources; the scan is probably broken.");
65
66 foreach (var language in Translations.Languages.Skip(1))
67 {
68 var translated = Translations.KeysOf(language).ToHashSet(StringComparer.Ordinal);
69 var missing = used.Except(translated).Order().ToList();
70 var unused = translated.Except(used).Order().ToList();
71 Assert.True(missing.Count == 0, $"{language}.json is missing:\n" + string.Join("\n", missing));
72 Assert.True(unused.Count == 0, $"{language}.json has entries the code does not use:\n" + string.Join("\n", unused));
73 }
74 }
75
76 [Fact]
77 public void Translations_keep_the_placeholders_of_the_english_text()
78 {
79 static string[] Placeholders(string text) =>
80 Placeholder().Matches(text).Select(m => m.Value).Distinct().Order().ToArray();
81
82 foreach (var language in Translations.Languages.Skip(1))
83 {
84 foreach (var key in Translations.KeysOf(language))
85 {
86 // A plural key is "one|other"; both halves carry the same placeholders.
87 var expected = Placeholders(key.Split('|')[^1]);
88 foreach (var form in Translations.Find(language, key)!)
89 {
90 Assert.True(expected.SequenceEqual(Placeholders(form)), $"{language}.json: \"{form}\" does not keep the placeholders of \"{key}\".");
91 }
92 }
93 }
94 }
95
96 [Fact]
97 public void Unknown_text_and_unknown_languages_fall_back_to_english()
98 {
99 Assert.Equal("Sign in", In("en", () => T["Sign in"]));
100 Assert.Equal("Prihlásiť sa", In("sk", () => T["Sign in"]));
101 Assert.Equal("Prihlásiť sa", In("sk-SK", () => T["Sign in"]));
102 Assert.Equal("Sign in", In("de-DE", () => T["Sign in"]));
103 Assert.Equal("Not a known text", In("sk", () => T["Not a known text"]));
104 Assert.Equal("sk", In("sk-SK", () => T.Language));
105 Assert.Equal("en", In("de-DE", () => T.Language));
106 Assert.Equal("Odhlásiť sa (jessie)", In("sk", () => T["Sign out ({0})", "jessie"]));
107 }
108
109 [Theory]
110 [InlineData(1, "1 line", "1 riadok")]
111 [InlineData(2, "2 lines", "2 riadky")]
112 [InlineData(4, "4 lines", "4 riadky")]
113 [InlineData(5, "5 lines", "5 riadkov")]
114 [InlineData(0, "0 lines", "0 riadkov")]
115 [InlineData(22, "22 lines", "22 riadkov")]
116 public void Plurals_follow_the_rules_of_each_language(int count, string english, string slovak)
117 {
118 Assert.Equal(english, In("en", () => T.Plural(count, "{0} line", "{0} lines")));
119 Assert.Equal(slovak, In("sk", () => T.Plural(count, "{0} line", "{0} lines")));
120 }
121
122 [Theory]
123 [InlineData(10, "just now", "práve teraz")]
124 [InlineData(60, "a minute ago", "pred minútou")]
125 [InlineData(60 * 5, "5 minutes ago", "pred 5 minútami")]
126 [InlineData(3600, "an hour ago", "pred hodinou")]
127 [InlineData(3600 * 3, "3 hours ago", "pred 3 hodinami")]
128 [InlineData(86400 + 3600, "yesterday", "včera")]
129 [InlineData(86400 * 3, "3 days ago", "pred 3 dňami")]
130 [InlineData(86400 * 45, "a month ago", "pred mesiacom")]
131 [InlineData(86400 * 100, "3 months ago", "pred 3 mesiacmi")]
132 [InlineData(86400 * 400, "a year ago", "pred rokom")]
133 [InlineData(86400 * 800, "2 years ago", "pred 2 rokmi")]
134 public void Relative_time_is_translated(int secondsAgo, string english, string slovak)
135 {
136 var now = new DateTimeOffset(2026, 1, 1, 12, 0, 0, TimeSpan.Zero);
137 Assert.Equal(english, In("en", () => T.RelativeTime(now.AddSeconds(-secondsAgo), now)));
138 Assert.Equal(slovak, In("sk", () => T.RelativeTime(now.AddSeconds(-secondsAgo), now)));
139 }
140
141 [Fact]
142 public async Task Pages_are_english_by_default_and_follow_the_browser_language()
143 {
144 await host.CreateUserAsync();
145
146 using var plain = host.CreateClient();
147 var english = await ForgeHost.TextAsync(await plain.GetAsync("/login"));
148 Assert.Contains("<html lang=\"en\">", english);
149 Assert.Contains("<h1>Sign in</h1>", english);
150
151 using var slovakBrowser = host.CreateClient();
152 slovakBrowser.DefaultRequestHeaders.AcceptLanguage.ParseAdd("sk-SK,sk;q=0.9,en;q=0.8");
153 var slovak = await ForgeHost.TextAsync(await slovakBrowser.GetAsync("/login"));
154 Assert.Contains("<html lang=\"sk\">", slovak);
155 Assert.Contains("<h1>Prihlásiť sa</h1>", slovak);
156
157 // A language Forge does not have falls back to English.
158 using var germanBrowser = host.CreateClient();
159 germanBrowser.DefaultRequestHeaders.AcceptLanguage.ParseAdd("de-DE,de;q=0.9");
160 Assert.Contains("<h1>Sign in</h1>", await ForgeHost.TextAsync(await germanBrowser.GetAsync("/login")));
161
162 // Messages produced by form handlers and by services are translated too.
163 var wrong = await ForgeHost.PostFormAsync(slovakBrowser, "/login", "login", new() { ["Username"] = "jessie", ["Password"] = "wrong password" });
164 Assert.Contains("Nesprávne meno alebo heslo.", await ForgeHost.TextAsync(wrong));
165 using var signedIn = await host.CreateSignedInClientAsync();
166 signedIn.DefaultRequestHeaders.AcceptLanguage.ParseAdd("sk");
167 var invalid = await ForgeHost.PostFormAsync(signedIn, "/new", "new-repo", new() { ["Name"] = "bad..name" });
168 Assert.Contains("Názov nesmie obsahovať „..“.", await ForgeHost.TextAsync(invalid));
169
170 // Error pages as well.
171 var missing = await slovakBrowser.GetAsync("/nobody/nothing");
172 Assert.Equal(HttpStatusCode.NotFound, missing.StatusCode);
173 Assert.Contains("Táto stránka neexistuje", await ForgeHost.TextAsync(missing));
174 }
175
176 [Fact]
177 public async Task Language_switcher_remembers_the_choice_over_the_browser_language()
178 {
179 await host.CreateUserAsync();
180 using var client = host.CreateClient();
181 client.DefaultRequestHeaders.AcceptLanguage.ParseAdd("en-US,en;q=0.9");
182
183 var page = await client.GetStringAsync("/login?returnUrl=%2Fnew");
184 Assert.Contains("name=\"lang\" value=\"sk\"", page);
185 Assert.Contains("slovenčina", WebUtility.HtmlDecode(page));
186 var token = WebUtility.HtmlDecode(AntiforgeryToken().Match(page).Groups[1].Value);
187
188 var switched = await client.PostAsync("/language", new FormUrlEncodedContent(new Dictionary<string, string>
189 {
190 ["__RequestVerificationToken"] = token,
191 ["lang"] = "sk",
192 ["returnUrl"] = "/login?returnUrl=%2Fnew",
193 }));
194 Assert.Equal(HttpStatusCode.Redirect, switched.StatusCode);
195 Assert.Equal("/login?returnUrl=%2Fnew", switched.Headers.Location?.OriginalString);
196
197 // The cookie wins over Accept-Language from now on.
198 Assert.Contains("<h1>Prihlásiť sa</h1>", await ForgeHost.TextAsync(await client.GetAsync("/login")));
199
200 // An unsupported language is ignored, and the return address cannot leave the site.
201 var ignored = await client.PostAsync("/language", new FormUrlEncodedContent(new Dictionary<string, string>
202 {
203 ["__RequestVerificationToken"] = token,
204 ["lang"] = "xx",
205 ["returnUrl"] = "//evil.example",
206 }));
207 Assert.Equal("/", ignored.Headers.Location?.OriginalString);
208 Assert.Contains("<h1>Prihlásiť sa</h1>", await ForgeHost.TextAsync(await client.GetAsync("/login")));
209
210 // Without the antiforgery token the switch is refused.
211 var forged = await client.PostAsync("/language", new FormUrlEncodedContent(new Dictionary<string, string> { ["lang"] = "en" }));
212 Assert.Equal(HttpStatusCode.BadRequest, forged.StatusCode);
213 }
214
215 // "this[" covers the Localizer's own lookups (relative time).
216 [GeneratedRegex("""(?:\bT\[|\bthis\[|\bT\.Html\(|Localizer\.Key\()\s*"((?:[^"\\]|\\.)*)"\s*[\],)]""")]
217 private static partial Regex SingleKey();
218
219 [GeneratedRegex("""\bT\.Plural\([^,]+,\s*"([^"]*)",\s*"([^"]*)"\)""")]
220 private static partial Regex PluralKey();
221
222 [GeneratedRegex(@"\{\d+\}")]
223 private static partial Regex Placeholder();
224
225 [GeneratedRegex("name=\"__RequestVerificationToken\" value=\"([^\"]+)\"")]
226 private static partial Regex AntiforgeryToken();
227 }
added forge.Tests/MergeTests.cs +326 −0View file
@@ -0,0 +1,326 @@
1 using System.Net;
2 using Forge.Data;
3 using Forge.Features.History;
4 using Forge.Features.Repos;
5 using Forge.Tests.Support;
6 using Microsoft.EntityFrameworkCore;
7 using Microsoft.Extensions.DependencyInjection;
8
9 namespace Forge.Tests;
10
11 /// <summary>Compare, merge, and creating or deleting branches and tags from the web UI.</summary>
12 public class MergeTests(ForgeHost host) : IClassFixture<ForgeHost>
13 {
14 private sealed record Scenario(Repository Repo, string Work, string Url, string MainSha, string FeatureSha);
15
16 /// <summary>
17 /// A repository with main and a branch "feature/x" that adds b.txt and edits line two of a.txt.
18 /// With <paramref name="diverge"/>, main also gets a commit of its own: a different file, or the same line for a conflict.
19 /// </summary>
20 private async Task<Scenario> CreateAsync(string name, bool diverge = false, bool conflict = false, Visibility visibility = Visibility.Public)
21 {
22 var user = await host.CreateUserAsync();
23 var repo = await host.CreateRepoAsync(user, name, visibility);
24 var token = await host.CreateTokenAsync(user, canWrite: true);
25 var url = host.GitUrl("jessie", name, token);
26 var work = host.NewDir("work");
27
28 await host.Git.CreateWorkRepoAsync(work, fileName: "a.txt", content: "one\ntwo\nthree\n");
29 await host.Git.MustAsync(work, "checkout", "-b", "feature/x");
30 await File.WriteAllTextAsync(Path.Combine(work, "a.txt"), "one\nTWO from feature\nthree\n");
31 await File.WriteAllTextAsync(Path.Combine(work, "b.txt"), "new file\n");
32 await host.Git.MustAsync(work, "add", "-A");
33 await host.Git.MustAsync(work, "commit", "-m", "Feature work");
34 await File.WriteAllTextAsync(Path.Combine(work, "b.txt"), "new file\nsecond line\n");
35 await host.Git.MustAsync(work, "commit", "-am", "More feature work");
36 var featureSha = await host.Git.MustAsync(work, "rev-parse", "HEAD");
37
38 await host.Git.MustAsync(work, "checkout", "main");
39 if (diverge)
40 {
41 var (file, content) = conflict ? ("a.txt", "one\nTWO from main\nthree\n") : ("c.txt", "only on main\n");
42 await File.WriteAllTextAsync(Path.Combine(work, file), content);
43 await host.Git.MustAsync(work, "add", "-A");
44 await host.Git.MustAsync(work, "commit", "-m", "Main moves on");
45 }
46
47 var mainSha = await host.Git.MustAsync(work, "rev-parse", "HEAD");
48 await host.Git.MustAsync(work, "push", url, "main", "feature/x");
49 return new Scenario(repo, work, url, mainSha, featureSha);
50 }
51
52 /// <summary>Fetches the server's state into the scenario's working repository and returns `git` output for it.</summary>
53 private async Task<string> ServerAsync(Scenario s, params string[] args)
54 {
55 await host.Git.MustAsync(s.Work, "fetch", "--prune", s.Url, "+refs/heads/*:refs/remotes/server/*");
56 return await host.Git.MustAsync(s.Work, args);
57 }
58
59 private Task<List<PushEvent>> EventsAsync(long repoId) =>
60 host.WithScopeAsync(sp => sp.GetRequiredService<ForgeDb>().PushEvents
61 .Where(e => e.RepoId == repoId).OrderBy(e => e.Id).ToListAsync());
62
63 private Task<RefResult> MergeViaServiceAsync(Scenario s, MergeMethod method) =>
64 host.WithScopeAsync(async sp =>
65 {
66 var repo = await sp.GetRequiredService<RepoService>().FindAsync("jessie", s.Repo.Name);
67 var refs = sp.GetRequiredService<RefService>();
68 return await refs.MergeAsync(repo!, new Git.GitIdentity("Jessie", "jessie@forge.test"), "main", "feature/x", method, null);
69 });
70
71 [Fact]
72 public async Task Compare_shows_commits_and_diff_and_offers_merge_only_to_the_owner()
73 {
74 var s = await CreateAsync("compare", diverge: true);
75 using var anonymous = host.CreateClient();
76 using var owner = await host.CreateSignedInClientAsync();
77
78 var page = await anonymous.GetStringAsync("/jessie/compare/compare/main...feature/x");
79 Assert.Contains("Feature work", page);
80 Assert.Contains("More feature work", page);
81 Assert.DoesNotContain("Main moves on", page);
82 Assert.Contains("2 commits", page);
83 Assert.Contains("b.txt", page);
84 Assert.Contains("TWO from feature", page);
85 // The diff is taken from the point where the branches diverged, so main's own change is not in it.
86 Assert.DoesNotContain("only on main", page);
87 Assert.DoesNotContain("name=\"Method\"", page);
88
89 var ownerPage = await owner.GetStringAsync("/jessie/compare/compare/main...feature/x");
90 Assert.Contains("These branches can be merged automatically.", ownerPage);
91 Assert.Contains("name=\"Method\"", ownerPage);
92 // Diverged branches cannot fast-forward.
93 Assert.DoesNotContain("value=\"ff\"", ownerPage);
94
95 // Two SHAs work too (webhook payloads link like this), and so does the picker's query form.
96 Assert.Equal(HttpStatusCode.OK, (await anonymous.GetAsync($"/jessie/compare/compare/{s.MainSha}...{s.FeatureSha}")).StatusCode);
97 var picked = await anonymous.GetAsync("/jessie/compare/compare?base=main&head=feature%2Fx");
98 Assert.Equal("/jessie/compare/compare/main...feature/x", picked.Headers.Location?.PathAndQuery);
99 Assert.Equal(HttpStatusCode.OK, (await anonymous.GetAsync("/jessie/compare/compare")).StatusCode);
100
101 Assert.Equal(HttpStatusCode.NotFound, (await anonymous.GetAsync("/jessie/compare/compare/main...nope")).StatusCode);
102 Assert.Equal(HttpStatusCode.NotFound, (await anonymous.GetAsync("/jessie/compare/compare/--all...main")).StatusCode);
103
104 // The branches page links to the comparison.
105 Assert.Contains("href=\"/jessie/compare/compare/main...feature/x\"", await anonymous.GetStringAsync("/jessie/compare/branches"));
106 }
107
108 [Fact]
109 public async Task Merge_commit_from_the_page_joins_both_histories_and_can_delete_the_branch()
110 {
111 var s = await CreateAsync("merge-commit", diverge: true);
112 using var owner = await host.CreateSignedInClientAsync();
113
114 var merged = await ForgeHost.PostFormAsync(owner, "/jessie/merge-commit/compare/main...feature/x", "merge", new()
115 {
116 ["Method"] = "merge",
117 ["Message"] = "",
118 ["DeleteBranch"] = "true",
119 });
120 Assert.Equal("/jessie/merge-commit/tree/main", merged.Headers.Location?.PathAndQuery);
121
122 // The new commit has both tips as parents and carries both sides' changes.
123 var parents = (await ServerAsync(s, "log", "-1", "--format=%P", "server/main")).Split(' ');
124 Assert.Equal([s.MainSha, s.FeatureSha], parents);
125 Assert.Equal("Merge branch 'feature/x' into main", await host.Git.MustAsync(s.Work, "log", "-1", "--format=%s", "server/main"));
126 Assert.Equal("jessie <jessie@forge.test>", await host.Git.MustAsync(s.Work, "log", "-1", "--format=%an <%ae>", "server/main"));
127 var files = await host.Git.MustAsync(s.Work, "ls-tree", "--name-only", "server/main");
128 Assert.Equal(["a.txt", "b.txt", "c.txt"], files.Split('\n'));
129 Assert.Contains("TWO from feature", await host.Git.MustAsync(s.Work, "show", "server/main:a.txt"));
130
131 // The branch is gone, and both changes were recorded like pushes.
132 Assert.DoesNotContain("server/feature/x", await host.Git.MustAsync(s.Work, "branch", "-r"));
133 var events = (await EventsAsync(s.Repo.Id)).Skip(2).ToList();
134 Assert.Collection(
135 events,
136 e => Assert.Equal(("refs/heads/main", s.MainSha), (e.RefName, e.OldSha)),
137 e => Assert.Equal(("refs/heads/feature/x", s.FeatureSha, Git.GitParsers.ZeroSha), (e.RefName, e.OldSha, e.NewSha)));
138
139 // A normal git client accepts the result: pulling it is a fast-forward.
140 await host.Git.MustAsync(s.Work, "pull", "--ff-only", s.Url, "main");
141 }
142
143 [Fact]
144 public async Task Squash_creates_one_commit_with_a_single_parent()
145 {
146 var s = await CreateAsync("squash", diverge: true);
147 using var owner = await host.CreateSignedInClientAsync();
148
149 await ForgeHost.PostFormAsync(owner, "/jessie/squash/compare/main...feature/x", "merge", new()
150 {
151 ["Method"] = "squash",
152 ["Message"] = "",
153 });
154
155 Assert.Equal(s.MainSha, await ServerAsync(s, "log", "-1", "--format=%P", "server/main"));
156 var message = await host.Git.MustAsync(s.Work, "log", "-1", "--format=%B", "server/main");
157 Assert.StartsWith("Squash branch 'feature/x' into main", message);
158 Assert.Contains("* Feature work", message);
159 Assert.Contains("* More feature work", message);
160 Assert.Equal("new file\nsecond line", await host.Git.MustAsync(s.Work, "show", "server/main:b.txt"));
161 // Without the checkbox the branch stays.
162 Assert.Contains("server/feature/x", await host.Git.MustAsync(s.Work, "branch", "-r"));
163 }
164
165 [Fact]
166 public async Task Fast_forward_moves_the_branch_without_a_new_commit()
167 {
168 var s = await CreateAsync("fast-forward");
169 using var owner = await host.CreateSignedInClientAsync();
170
171 var page = await owner.GetStringAsync("/jessie/fast-forward/compare/main...feature/x");
172 Assert.Contains("value=\"ff\"", page);
173
174 await ForgeHost.PostFormAsync(owner, "/jessie/fast-forward/compare/main...feature/x", "merge", new()
175 {
176 ["Method"] = "ff",
177 ["Message"] = "ignored",
178 });
179
180 Assert.Equal(s.FeatureSha, await ServerAsync(s, "rev-parse", "server/main"));
181
182 // Now there is nothing left to merge, and the page says so instead of offering the form.
183 var after = await owner.GetStringAsync("/jessie/fast-forward/compare/main...feature/x");
184 Assert.DoesNotContain("name=\"Method\"", after);
185 Assert.Equal("There is nothing to merge.", (await MergeViaServiceAsync(s, MergeMethod.MergeCommit)).Error);
186 }
187
188 [Fact]
189 public async Task Custom_message_is_used_for_the_merge_commit()
190 {
191 var s = await CreateAsync("message", diverge: true);
192 using var owner = await host.CreateSignedInClientAsync();
193
194 await ForgeHost.PostFormAsync(owner, "/jessie/message/compare/main...feature/x", "merge", new()
195 {
196 ["Method"] = "merge",
197 ["Message"] = "--amend is just text here",
198 });
199
200 Assert.Equal("--amend is just text here", await ServerAsync(s, "log", "-1", "--format=%s", "server/main"));
201 }
202
203 [Fact]
204 public async Task Conflicting_branches_are_reported_and_left_alone()
205 {
206 var s = await CreateAsync("conflict", diverge: true, conflict: true);
207 using var owner = await host.CreateSignedInClientAsync();
208
209 var page = await owner.GetStringAsync("/jessie/conflict/compare/main...feature/x");
210 Assert.Contains("These branches have conflicts", page);
211 Assert.Contains("<code>a.txt</code>", page);
212 Assert.DoesNotContain("name=\"Method\"", page);
213
214 foreach (var method in (MergeMethod[])[MergeMethod.MergeCommit, MergeMethod.Squash])
215 {
216 var result = await MergeViaServiceAsync(s, method);
217 Assert.Equal("The branches have conflicts and cannot be merged automatically.", result.Error);
218 Assert.Equal(["a.txt"], result.Conflicts);
219 }
220
221 Assert.Equal(
222 "Fast-forward is not possible because the branches have diverged.",
223 (await MergeViaServiceAsync(s, MergeMethod.FastForward)).Error);
224
225 Assert.Equal(s.MainSha, await ServerAsync(s, "rev-parse", "server/main"));
226 Assert.Equal(2, (await EventsAsync(s.Repo.Id)).Count);
227 }
228
229 [Fact]
230 public async Task Visitors_cannot_merge_or_change_refs()
231 {
232 var s = await CreateAsync("visitor", diverge: true);
233 using var anonymous = host.CreateClient();
234
235 // The compare page renders no merge form for a visitor, so the post has nothing to bind to.
236 var merge = await ForgeHost.PostFormAsync(anonymous, "/jessie/visitor/compare/main...feature/x", "merge", new() { ["Method"] = "merge" });
237 Assert.Equal(HttpStatusCode.BadRequest, merge.StatusCode);
238
239 // The delete form is on the page for everyone (its buttons are not); the handler must refuse on its own.
240 await ForgeHost.PostFormAsync(anonymous, "/jessie/visitor/branches", "delete-branch", new() { ["DeleteName"] = "feature/x" });
241 await ForgeHost.PostFormAsync(anonymous, "/jessie/visitor/branches", "create-branch", new() { ["NewName"] = "sneaky", ["From"] = "main" });
242
243 var branches = await ServerAsync(s, "branch", "-r");
244 Assert.Contains("server/feature/x", branches);
245 Assert.DoesNotContain("sneaky", branches);
246 Assert.Equal(s.MainSha, await host.Git.MustAsync(s.Work, "rev-parse", "server/main"));
247
248 // Nothing in a private repository is reachable at all.
249 await CreateAsync("visitor-private", visibility: Visibility.Private);
250 Assert.Equal(HttpStatusCode.NotFound, (await anonymous.GetAsync("/jessie/visitor-private/compare/main...feature/x")).StatusCode);
251 Assert.Equal(HttpStatusCode.NotFound, (await anonymous.GetAsync("/jessie/visitor-private/compare")).StatusCode);
252 }
253
254 [Fact]
255 public async Task Branches_are_created_and_deleted_from_the_page()
256 {
257 var s = await CreateAsync("branches");
258 using var owner = await host.CreateSignedInClientAsync();
259 const string page = "/jessie/branches/branches";
260
261 var created = await ForgeHost.PostFormAsync(owner, page, "create-branch", new() { ["NewName"] = "release/1.0", ["From"] = "feature/x" });
262 Assert.Contains("Branch release/1.0 was created.", await ForgeHost.TextAsync(created));
263 Assert.Equal(s.FeatureSha, await ServerAsync(s, "rev-parse", "server/release/1.0"));
264
265 // From a commit SHA.
266 await ForgeHost.PostFormAsync(owner, page, "create-branch", new() { ["NewName"] = "from-sha", ["From"] = s.MainSha });
267 Assert.Equal(s.MainSha, await ServerAsync(s, "rev-parse", "server/from-sha"));
268
269 var duplicate = await ForgeHost.PostFormAsync(owner, page, "create-branch", new() { ["NewName"] = "from-sha", ["From"] = "main" });
270 Assert.Contains("A branch with this name already exists.", await ForgeHost.TextAsync(duplicate));
271
272 var missing = await ForgeHost.PostFormAsync(owner, page, "create-branch", new() { ["NewName"] = "ok-name", ["From"] = "nope" });
273 Assert.Contains("The starting point does not exist.", await ForgeHost.TextAsync(missing));
274
275 foreach (var bad in (string[])["-x", "--force", "a..b", "has space", "ends.lock", "a~1", "HEAD", "x/", "a:b"])
276 {
277 var refused = await ForgeHost.PostFormAsync(owner, page, "create-branch", new() { ["NewName"] = bad, ["From"] = "main" });
278 Assert.True(
279 (await ForgeHost.TextAsync(refused)).Contains("This is not a valid branch name."),
280 $"Branch name '{bad}' was not refused.");
281 }
282
283 var deleted = await ForgeHost.PostFormAsync(owner, page, "delete-branch", new() { ["DeleteName"] = "release/1.0" });
284 Assert.Contains($"Branch release/1.0 was deleted (it pointed at {s.FeatureSha}).", await ForgeHost.TextAsync(deleted));
285
286 var protectedDefault = await ForgeHost.PostFormAsync(owner, page, "delete-branch", new() { ["DeleteName"] = "main" });
287 Assert.Contains("The default branch cannot be deleted.", await ForgeHost.TextAsync(protectedDefault));
288
289 var branches = (await ServerAsync(s, "branch", "-r")).Split('\n').Select(b => b.Trim()).Order().ToList();
290 Assert.Equal(["server/feature/x", "server/from-sha", "server/main"], branches);
291
292 // Creations and the deletion were recorded as push events, after the two from the initial push.
293 var events = (await EventsAsync(s.Repo.Id)).Skip(2).Select(e => (e.RefName, Created: e.OldSha == Git.GitParsers.ZeroSha, Deleted: e.NewSha == Git.GitParsers.ZeroSha)).ToList();
294 Assert.Equal(
295 [
296 ("refs/heads/release/1.0", true, false),
297 ("refs/heads/from-sha", true, false),
298 ("refs/heads/release/1.0", false, true),
299 ], events);
300 }
301
302 [Fact]
303 public async Task Tags_are_created_and_deleted_from_the_page()
304 {
305 var s = await CreateAsync("tags");
306 using var owner = await host.CreateSignedInClientAsync();
307 const string page = "/jessie/tags/tags";
308
309 var created = await ForgeHost.PostFormAsync(owner, page, "create-tag", new() { ["NewName"] = "v1.0", ["From"] = "feature/x" });
310 var html = await ForgeHost.TextAsync(created);
311 Assert.Contains("Tag v1.0 was created.", html);
312 Assert.Contains("href=\"/jessie/tags/tree/v1.0\"", html);
313
314 await host.Git.MustAsync(s.Work, "fetch", "--tags", s.Url);
315 Assert.Equal(s.FeatureSha, await host.Git.MustAsync(s.Work, "rev-parse", "v1.0^{commit}"));
316
317 var duplicate = await ForgeHost.PostFormAsync(owner, page, "create-tag", new() { ["NewName"] = "v1.0", ["From"] = "main" });
318 Assert.Contains("A tag with this name already exists.", await ForgeHost.TextAsync(duplicate));
319 var invalid = await ForgeHost.PostFormAsync(owner, page, "create-tag", new() { ["NewName"] = "-d", ["From"] = "main" });
320 Assert.Contains("This is not a valid tag name.", await ForgeHost.TextAsync(invalid));
321
322 var deleted = await ForgeHost.PostFormAsync(owner, page, "delete-tag", new() { ["DeleteName"] = "v1.0" });
323 Assert.Contains($"Tag v1.0 was deleted (it pointed at {s.FeatureSha}).", await ForgeHost.TextAsync(deleted));
324 Assert.Equal("", await host.Git.MustAsync(s.Work, "ls-remote", "--tags", s.Url));
325 }
326 }
added forge.Tests/ParserTests.cs +340 −0View file
@@ -0,0 +1,340 @@
1 using Forge.Features.Auth;
2 using Forge.Features.Browse;
3 using Forge.Features.Repos;
4 using Forge.Features.SmartHttp;
5 using Forge.Features.Webhooks;
6 using Forge.Git;
7
8 namespace Forge.Tests;
9
10 /// <summary>Pure logic that needs neither git nor the web app.</summary>
11 public class ParserTests
12 {
13 [Fact]
14 public void ParseTree_reads_modes_sizes_and_names_with_spaces()
15 {
16 const string output =
17 "100644 blob 1111111111111111111111111111111111111111 12\tfile with space.txt\0"
18 + "040000 tree 2222222222222222222222222222222222222222 -\tsrc\0"
19 + "160000 commit 3333333333333333333333333333333333333333 -\tvendor/lib\0";
20
21 var entries = GitParsers.ParseTree(output);
22
23 Assert.Equal(3, entries.Count);
24 Assert.Equal("file with space.txt", entries[0].Name);
25 Assert.Equal(12, entries[0].Size);
26 Assert.True(entries[0].IsBlob);
27 Assert.True(entries[1].IsTree);
28 Assert.Null(entries[1].Size);
29 Assert.Equal("lib", entries[2].Name);
30 Assert.True(entries[2].IsSubmodule);
31 }
32
33 [Fact]
34 public void ParseLog_splits_records_and_keeps_multiline_bodies()
35 {
36 var a = new string('a', 40);
37 var b = new string('b', 40);
38 var output =
39 $"{a}\0{b}\0Ann\0ann@example.com\01700000000\0Bob\0bob@example.com\01700000100\0Subject one\0Body line 1\nBody line 2\n\0\n"
40 + $"{b}\0\0Ann\0ann@example.com\01600000000\0Ann\0ann@example.com\01600000000\0Root\0\0\n";
41
42 var commits = GitParsers.ParseLog(output);
43
44 Assert.Equal(2, commits.Count);
45 Assert.Equal(a, commits[0].Sha);
46 Assert.Equal([b], commits[0].Parents);
47 Assert.Equal("Body line 1\nBody line 2", commits[0].Body);
48 Assert.Equal("Bob", commits[0].CommitterName);
49 Assert.Equal(DateTimeOffset.FromUnixTimeSeconds(1700000000), commits[0].AuthorDate);
50 Assert.Equal(b, commits[1].Sha);
51 Assert.Empty(commits[1].Parents);
52 Assert.Equal("", commits[1].Body);
53 }
54
55 [Fact]
56 public void ParseNumstat_handles_renames_and_binary_files()
57 {
58 const string output = "3\t1\tsrc/a.cs\0-\t-\tlogo.png\00\t0\t\0old name.txt\0new name.txt\0";
59
60 var stats = GitParsers.ParseNumstat(output);
61
62 Assert.Equal(3, stats.Count);
63 Assert.Equal(new FileStat("src/a.cs", null, 3, 1), stats[0]);
64 Assert.True(stats[1].IsBinary);
65 Assert.Equal("new name.txt", stats[2].Path);
66 Assert.Equal("old name.txt", stats[2].OldPath);
67 }
68
69 [Fact]
70 public void ParseDiff_builds_hunks_with_line_numbers()
71 {
72 const string patch = """
73 diff --git a/src/a.cs b/src/a.cs
74 index 1111111..2222222 100644
75 --- a/src/a.cs
76 +++ b/src/a.cs
77 @@ -1,3 +1,4 @@ class A
78 line one
79 -line two
80 +line 2
81 +line 2b
82 line three
83 \ No newline at end of file
84 diff --git a/logo.png b/logo.png
85 new file mode 100644
86 index 0000000..3333333
87 Binary files /dev/null and b/logo.png differ
88 diff --git a/old name.txt b/new name.txt
89 similarity index 100%
90 rename from old name.txt
91 rename to new name.txt
92 diff --git a/gone.txt b/gone.txt
93 deleted file mode 100644
94 index 4444444..0000000
95 --- a/gone.txt
96 +++ /dev/null
97 @@ -1 +0,0 @@
98 -bye
99
100 """;
101
102 var diff = GitParsers.ParseDiff(patch.ReplaceLineEndings("\n"));
103
104 Assert.False(diff.Truncated);
105 Assert.Equal(4, diff.Files.Count);
106
107 var modified = diff.Files[0];
108 Assert.Equal("src/a.cs", modified.NewPath);
109 Assert.Equal(FileChange.Modified, modified.Change);
110 Assert.Equal(2, modified.Added);
111 Assert.Equal(1, modified.Deleted);
112 var lines = Assert.Single(modified.Hunks).Lines;
113 Assert.Equal(new DiffLine(DiffLineKind.Context, 1, 1, "line one"), lines[0]);
114 Assert.Equal(new DiffLine(DiffLineKind.Deleted, 2, null, "line two"), lines[1]);
115 Assert.Equal(new DiffLine(DiffLineKind.Added, null, 2, "line 2"), lines[2]);
116 Assert.Equal(new DiffLine(DiffLineKind.Added, null, 3, "line 2b"), lines[3]);
117 Assert.Equal(new DiffLine(DiffLineKind.Context, 3, 4, "line three"), lines[4]);
118 Assert.Equal(DiffLineKind.NoNewline, lines[5].Kind);
119
120 var binary = diff.Files[1];
121 Assert.True(binary.IsBinary);
122 Assert.Equal(FileChange.Added, binary.Change);
123 Assert.Equal("logo.png", binary.NewPath);
124
125 var renamed = diff.Files[2];
126 Assert.Equal(FileChange.Renamed, renamed.Change);
127 Assert.Equal("old name.txt", renamed.OldPath);
128 Assert.Equal("new name.txt", renamed.NewPath);
129
130 var deleted = diff.Files[3];
131 Assert.Equal(FileChange.Deleted, deleted.Change);
132 Assert.Equal("gone.txt", deleted.DisplayPath);
133 }
134
135 [Fact]
136 public void ParseDiff_applies_file_and_line_limits()
137 {
138 var big = "diff --git a/big.txt b/big.txt\n--- a/big.txt\n+++ b/big.txt\n@@ -0,0 +1,5 @@\n+1\n+2\n+3\n+4\n+5\n";
139 var patch = big + "diff --git a/b.txt b/b.txt\n--- a/b.txt\n+++ b/b.txt\n@@ -1 +1 @@\n-x\n+y\n"
140 + "diff --git a/c.txt b/c.txt\n--- a/c.txt\n+++ b/c.txt\n@@ -1 +1 @@\n-x\n+y\n";
141
142 var diff = GitParsers.ParseDiff(patch, maxFiles: 2, maxLinesPerFile: 3);
143
144 Assert.True(diff.Truncated);
145 Assert.Equal(2, diff.Files.Count);
146 Assert.True(diff.Files[0].TooLarge);
147 Assert.Empty(diff.Files[0].Hunks);
148 Assert.Equal(5, diff.Files[0].Added);
149 Assert.False(diff.Files[1].TooLarge);
150 }
151
152 [Theory]
153 [InlineData("plain.txt", "plain.txt")]
154 [InlineData("\"tab\\there.txt\"", "tab\there.txt")]
155 [InlineData("\"quote\\\"d.txt\"", "quote\"d.txt")]
156 [InlineData("\"\\303\\251t\\303\\251.txt\"", "été.txt")]
157 public void Unquote_reverses_git_path_quoting(string quoted, string expected) =>
158 Assert.Equal(expected, GitParsers.Unquote(quoted));
159
160 [Fact]
161 public void IsBinary_looks_for_nul_in_the_first_8000_bytes()
162 {
163 var late = new byte[9000];
164 Array.Fill(late, (byte)'a');
165 late[8500] = 0;
166 var early = (byte[])late.Clone();
167 early[100] = 0;
168
169 Assert.False(GitParsers.IsBinary(late));
170 Assert.True(GitParsers.IsBinary(early));
171 Assert.False(GitParsers.IsBinary("text"u8));
172 }
173
174 [Fact]
175 public void RefResolver_prefers_the_longest_matching_ref()
176 {
177 var sha1 = new string('1', 40);
178 var sha2 = new string('2', 40);
179 GitRef[] refs =
180 [
181 new("refs/heads/feature", "feature", RefKind.Branch, sha1, "commit", null, null, ""),
182 new("refs/heads/feature/x", "feature/x", RefKind.Branch, sha2, "commit", null, null, ""),
183 new("refs/tags/v1.0", "v1.0", RefKind.Tag, sha1, "tag", sha2, null, ""),
184 ];
185
186 var deep = RefResolver.Match(refs, "feature/x/src/a.cs");
187 Assert.Equal(new ResolvedRef("feature/x", ResolvedKind.Branch, sha2, "src/a.cs"), deep);
188
189 var shallow = RefResolver.Match(refs, "feature/y/a.cs");
190 Assert.Equal(new ResolvedRef("feature", ResolvedKind.Branch, sha1, "y/a.cs"), shallow);
191
192 // An annotated tag resolves to the commit it points at.
193 Assert.Equal(new ResolvedRef("v1.0", ResolvedKind.Tag, sha2, ""), RefResolver.Match(refs, "v1.0"));
194 }
195
196 [Theory]
197 [InlineData("--upload-pack=touch /tmp/x")]
198 [InlineData("-n")]
199 [InlineData("feature/../x")]
200 [InlineData("nope")]
201 [InlineData("")]
202 public void RefResolver_rejects_anything_that_is_not_an_existing_ref(string input)
203 {
204 GitRef[] refs = [new("refs/heads/feature", "feature", RefKind.Branch, new string('1', 40), "commit", null, null, "")];
205 Assert.Null(RefResolver.Match(refs, input));
206 }
207
208 [Theory]
209 [InlineData("forge", true)]
210 [InlineData("my.repo_2-x", true)]
211 [InlineData("-leading-dash", true)]
212 [InlineData("", false)]
213 [InlineData(".", false)]
214 [InlineData("..", false)]
215 [InlineData("a..b", false)]
216 [InlineData("a/b", false)]
217 [InlineData("a\\b", false)]
218 [InlineData("repo.git", false)]
219 [InlineData("repo.GIT", false)]
220 [InlineData("has space", false)]
221 [InlineData("name\n", false)]
222 [InlineData("ž", false)]
223 public void Repository_names_are_validated(string name, bool valid) =>
224 Assert.Equal(valid, RepoService.ValidateName(name) is null);
225
226 [Fact]
227 public void Repository_name_length_is_limited_to_100()
228 {
229 Assert.Null(RepoService.ValidateName(new string('a', 100)));
230 Assert.NotNull(RepoService.ValidateName(new string('a', 101)));
231 }
232
233 [Theory]
234 [InlineData("jessie", true)]
235 [InlineData("settings", false)]
236 [InlineData("Login", false)]
237 [InlineData("-x", false)]
238 [InlineData("a.b", false)]
239 public void Usernames_are_validated(string name, bool valid) =>
240 Assert.Equal(valid, AccountRules.ValidateUsername(name) is null);
241
242 [Fact]
243 public void PktLine_prefixes_the_total_length_in_hex() =>
244 Assert.Equal("001e# service=git-upload-pack\n", System.Text.Encoding.ASCII.GetString(SmartHttpEndpoints.PktLine("# service=git-upload-pack\n")));
245
246 [Theory]
247 [InlineData("version=2", "version=2")]
248 [InlineData("version=2:object-format=sha1", "version=2:object-format=sha1")]
249 [InlineData("version=2; rm -rf /", null)]
250 [InlineData("a b", null)]
251 [InlineData("", null)]
252 public void Git_protocol_header_is_validated(string header, string? expected) =>
253 Assert.Equal(expected, SmartHttpEndpoints.ValidateProtocolHeader(header));
254
255 [Fact]
256 public void Basic_auth_password_is_extracted()
257 {
258 var header = "Basic " + Convert.ToBase64String("git:forge_abc:def"u8);
259 Assert.Equal("forge_abc:def", SmartHttpEndpoints.ParseBasicPassword(header));
260 Assert.Null(SmartHttpEndpoints.ParseBasicPassword(null));
261 Assert.Null(SmartHttpEndpoints.ParseBasicPassword("Bearer x"));
262 Assert.Equal("", SmartHttpEndpoints.ParseBasicPassword("Basic !!!"));
263 }
264
265 [Fact]
266 public void Push_diff_reports_created_updated_and_deleted_refs()
267 {
268 var a = new string('a', 40);
269 var b = new string('b', 40);
270 var before = new Dictionary<string, string> { ["refs/heads/main"] = a, ["refs/heads/old"] = a };
271 var after = new Dictionary<string, string> { ["refs/heads/main"] = b, ["refs/tags/v1"] = b };
272
273 var changes = PushRecorder.Diff(before, after);
274
275 Assert.Equal(
276 [
277 new RefChange("refs/heads/main", a, b),
278 new RefChange("refs/heads/old", a, GitParsers.ZeroSha),
279 new RefChange("refs/tags/v1", GitParsers.ZeroSha, b),
280 ], changes);
281 }
282
283 [Fact]
284 public void Tokens_are_hashed_with_sha256()
285 {
286 Assert.Equal(
287 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
288 TokenService.Hash("abc"));
289 }
290
291 [Fact]
292 public void Webhook_signature_is_hmac_sha256_of_the_body()
293 {
294 // RFC 4231 test case 2.
295 Assert.Equal(
296 "sha256=5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843",
297 WebhookSender.Sign("Jefe", "what do ya want for nothing?"u8));
298 }
299
300 [Fact]
301 public void Markdown_is_sanitized_and_relative_links_point_into_the_repository()
302 {
303 var links = new LinkContext("/o/r/raw/main", "/o/r/blob/main", "docs");
304 var html = new MarkdownRenderer().Render(
305 """
306 # Title
307
308 ![logo](img/logo.png) [guide](../GUIDE.md) [root](/LICENSE) [ext](https://example.com/x) [anchor](#top)
309
310 <script>alert(1)</script>
311 <img src="x.png" onerror="alert(1)">
312 <a href="javascript:alert(1)">bad</a>
313 """,
314 links);
315
316 Assert.Contains("src=\"/o/r/raw/main/docs/img/logo.png\"", html);
317 Assert.Contains("href=\"/o/r/blob/main/GUIDE.md\"", html);
318 Assert.Contains("href=\"/o/r/blob/main/LICENSE\"", html);
319 Assert.Contains("src=\"/o/r/raw/main/docs/x.png\"", html);
320 Assert.Contains("href=\"#top\"", html);
321 Assert.Matches("<a[^>]*href=\"https://example.com/x\"[^>]*rel=\"nofollow noopener\"", html);
322 Assert.DoesNotContain("<script", html);
323 Assert.DoesNotContain("onerror", html);
324 Assert.DoesNotContain("javascript:", html);
325 }
326
327 [Fact]
328 public void Auth_failure_limiter_blocks_after_repeated_failures()
329 {
330 var limiter = new AuthFailureLimiter(TimeProvider.System);
331 for (var i = 0; i < AuthFailureLimiter.MaxFailures; i++)
332 {
333 Assert.False(limiter.IsBlocked("1.2.3.4"));
334 limiter.RecordFailure("1.2.3.4");
335 }
336
337 Assert.True(limiter.IsBlocked("1.2.3.4"));
338 Assert.False(limiter.IsBlocked("5.6.7.8"));
339 }
340 }
added forge.Tests/SmartHttpTests.cs +218 −0View file
@@ -0,0 +1,218 @@
1 using System.Net;
2 using System.Net.Http.Headers;
3 using System.Text;
4 using Forge.Data;
5 using Forge.Tests.Support;
6 using Microsoft.EntityFrameworkCore;
7 using Microsoft.Extensions.DependencyInjection;
8
9 namespace Forge.Tests;
10
11 /// <summary>Real `git clone` and `git push` against the running app.</summary>
12 public class SmartHttpTests(ForgeHost host) : IClassFixture<ForgeHost>
13 {
14 [Theory]
15 [InlineData("0")]
16 [InlineData("2")]
17 public async Task Push_then_clone_round_trips(string protocolVersion)
18 {
19 var user = await host.CreateUserAsync();
20 var name = "roundtrip-v" + protocolVersion;
21 var repo = await host.CreateRepoAsync(user, name, Visibility.Public);
22 var token = await host.CreateTokenAsync(user, canWrite: true);
23 var protocol = "protocol.version=" + protocolVersion;
24
25 var work = host.NewDir("work");
26 var sha = await host.Git.CreateWorkRepoAsync(work);
27 await host.Git.MustAsync(work, "-c", protocol, "push", host.GitUrl(user.Username, name, token), "main");
28
29 // Tags go up with --tags.
30 await host.Git.MustAsync(work, "tag", "-a", "v1", "-m", "one");
31 await host.Git.MustAsync(work, "-c", protocol, "push", "--tags", host.GitUrl(user.Username, name, token));
32
33 // A public repository clones without credentials.
34 var clone = host.NewDir("clone");
35 await host.Git.MustAsync(clone, "-c", protocol, "clone", host.GitUrl(user.Username, name), ".");
36 Assert.Equal(sha, await host.Git.MustAsync(clone, "rev-parse", "HEAD"));
37 Assert.Equal("# Demo\n", await File.ReadAllTextAsync(Path.Combine(clone, "README.md")));
38 Assert.Equal("v1", await host.Git.MustAsync(clone, "tag", "--list"));
39
40 // A second push is a fast-forward and is recorded as an update.
41 await File.WriteAllTextAsync(Path.Combine(work, "second.txt"), "more\n");
42 await host.Git.MustAsync(work, "add", "-A");
43 await host.Git.MustAsync(work, "commit", "-m", "Second");
44 var secondSha = await host.Git.MustAsync(work, "rev-parse", "HEAD");
45 await host.Git.MustAsync(work, "-c", protocol, "push", host.GitUrl(user.Username, name, token), "main");
46 await host.Git.MustAsync(clone, "-c", protocol, "pull", "--ff-only");
47 Assert.Equal(secondSha, await host.Git.MustAsync(clone, "rev-parse", "HEAD"));
48
49 var events = await host.WithScopeAsync(sp => sp.GetRequiredService<ForgeDb>().PushEvents
50 .Where(e => e.RepoId == repo.Id).OrderBy(e => e.Id).ToListAsync());
51 Assert.Collection(
52 events,
53 e => Assert.Equal(("refs/heads/main", Git.GitParsers.ZeroSha, sha), (e.RefName, e.OldSha, e.NewSha)),
54 e => Assert.Equal(("refs/tags/v1", Git.GitParsers.ZeroSha), (e.RefName, e.OldSha)),
55 e => Assert.Equal(("refs/heads/main", sha, secondSha), (e.RefName, e.OldSha, e.NewSha)));
56
57 var reloaded = await host.ReloadRepoAsync(repo.Id);
58 Assert.NotNull(reloaded.PushedAt);
59 Assert.Equal("main", reloaded.DefaultBranch);
60 }
61
62 [Fact]
63 public async Task First_push_of_another_branch_becomes_the_default_branch()
64 {
65 var user = await host.CreateUserAsync();
66 var repo = await host.CreateRepoAsync(user, "master-first", Visibility.Public);
67 var token = await host.CreateTokenAsync(user, canWrite: true);
68
69 var work = host.NewDir("work");
70 var sha = await host.Git.CreateWorkRepoAsync(work, branch: "master");
71 await host.Git.MustAsync(work, "push", host.GitUrl(user.Username, repo.Name, token), "master");
72
73 Assert.Equal("master", (await host.ReloadRepoAsync(repo.Id)).DefaultBranch);
74
75 // HEAD moved too, so a clone checks out the pushed branch.
76 var clone = host.NewDir("clone");
77 await host.Git.MustAsync(clone, "clone", host.GitUrl(user.Username, repo.Name), ".");
78 Assert.Equal(sha, await host.Git.MustAsync(clone, "rev-parse", "HEAD"));
79 }
80
81 [Fact]
82 public async Task Private_repository_needs_a_token_to_clone()
83 {
84 var user = await host.CreateUserAsync();
85 var (repo, sha, _) = await host.CreatePushedRepoAsync(user, "private-clone", Visibility.Private);
86 var readToken = await host.CreateTokenAsync(user, canWrite: false);
87
88 var anonymous = await host.Git.RunAsync(host.NewDir("anon"), "clone", host.GitUrl(user.Username, repo.Name), ".");
89 Assert.False(anonymous.Ok);
90
91 var clone = host.NewDir("clone");
92 await host.Git.MustAsync(clone, "clone", host.GitUrl(user.Username, repo.Name, readToken), ".");
93 Assert.Equal(sha, await host.Git.MustAsync(clone, "rev-parse", "HEAD"));
94
95 var used = await host.WithScopeAsync(sp => sp.GetRequiredService<ForgeDb>().AccessTokens
96 .Where(t => !t.CanWrite && t.UserId == user.Id).Select(t => t.LastUsedAt).ToListAsync());
97 Assert.Contains(used, u => u is not null);
98 }
99
100 [Fact]
101 public async Task Push_is_rejected_without_a_write_token()
102 {
103 var user = await host.CreateUserAsync();
104 var (repo, sha, work) = await host.CreatePushedRepoAsync(user, "push-rights", Visibility.Public);
105 var readToken = await host.CreateTokenAsync(user, canWrite: false);
106 var expired = await host.CreateTokenAsync(user, canWrite: true, DateTime.UtcNow.AddMinutes(-1));
107
108 await File.WriteAllTextAsync(Path.Combine(work, "new.txt"), "x\n");
109 await host.Git.MustAsync(work, "add", "-A");
110 await host.Git.MustAsync(work, "commit", "-m", "Not allowed");
111
112 Assert.False((await host.Git.RunAsync(work, "push", host.GitUrl(user.Username, repo.Name), "main")).Ok);
113 Assert.False((await host.Git.RunAsync(work, "push", host.GitUrl(user.Username, repo.Name, readToken), "main")).Ok);
114 Assert.False((await host.Git.RunAsync(work, "push", host.GitUrl(user.Username, repo.Name, expired), "main")).Ok);
115 Assert.False((await host.Git.RunAsync(work, "push", host.GitUrl(user.Username, repo.Name, "forge_wrong"), "main")).Ok);
116
117 // Nothing moved on the server.
118 var check = host.NewDir("check");
119 await host.Git.MustAsync(check, "clone", host.GitUrl(user.Username, repo.Name), ".");
120 Assert.Equal(sha, await host.Git.MustAsync(check, "rev-parse", "HEAD"));
121 }
122
123 [Fact]
124 public async Task Status_codes_do_not_reveal_private_repositories()
125 {
126 var user = await host.CreateUserAsync();
127 var other = await host.CreateUserAsync("other");
128 await host.CreatePushedRepoAsync(user, "hidden", Visibility.Private);
129 var readToken = await host.CreateTokenAsync(user, canWrite: false);
130 var otherToken = await host.CreateTokenAsync(other, canWrite: true);
131 var expired = await host.CreateTokenAsync(user, canWrite: true, DateTime.UtcNow.AddMinutes(-1));
132 using var client = host.CreateClient();
133
134 const string upload = "/jessie/hidden.git/info/refs?service=git-upload-pack";
135 const string receive = "/jessie/hidden.git/info/refs?service=git-receive-pack";
136 const string missing = "/jessie/does-not-exist.git/info/refs?service=git-upload-pack";
137
138 // Anonymous: a private repository and a missing one answer identically, and git is asked for credentials.
139 var hidden = await client.GetAsync(upload);
140 var absent = await client.GetAsync(missing);
141 Assert.Equal(HttpStatusCode.Unauthorized, hidden.StatusCode);
142 Assert.Equal(HttpStatusCode.Unauthorized, absent.StatusCode);
143 Assert.StartsWith("Basic realm=\"forge\"", hidden.Headers.WwwAuthenticate.ToString());
144 Assert.Equal(await hidden.Content.ReadAsStringAsync(), await absent.Content.ReadAsStringAsync());
145
146 // Another user's valid token: the repository does not exist for them.
147 Assert.Equal(HttpStatusCode.NotFound, (await GetAsync(client, upload, otherToken)).StatusCode);
148 Assert.Equal(HttpStatusCode.NotFound, (await GetAsync(client, receive, otherToken)).StatusCode);
149
150 // The owner's read token reads but may not push; an expired token is no token.
151 Assert.Equal(HttpStatusCode.OK, (await GetAsync(client, upload, readToken)).StatusCode);
152 Assert.Equal(HttpStatusCode.Forbidden, (await GetAsync(client, receive, readToken)).StatusCode);
153 Assert.Equal(HttpStatusCode.Unauthorized, (await GetAsync(client, upload, expired)).StatusCode);
154 }
155
156 [Fact]
157 public async Task Info_refs_validates_the_service_and_sets_headers()
158 {
159 var user = await host.CreateUserAsync();
160 await host.CreatePushedRepoAsync(user, "headers", Visibility.Public);
161 using var client = host.CreateClient();
162
163 var bad = await client.GetAsync("/jessie/headers.git/info/refs?service=git-upload-archive");
164 Assert.Equal(HttpStatusCode.BadRequest, bad.StatusCode);
165 Assert.Equal(HttpStatusCode.BadRequest, (await client.GetAsync("/jessie/headers.git/info/refs")).StatusCode);
166
167 var v0 = await client.GetAsync("/jessie/headers.git/info/refs?service=git-upload-pack");
168 Assert.Equal(HttpStatusCode.OK, v0.StatusCode);
169 Assert.Equal("application/x-git-upload-pack-advertisement", v0.Content.Headers.ContentType?.MediaType);
170 Assert.Equal("no-cache", v0.Headers.CacheControl?.ToString());
171 Assert.StartsWith("001e# service=git-upload-pack\n0000", await v0.Content.ReadAsStringAsync());
172
173 // Protocol v2: the header reaches git as GIT_PROTOCOL and the answer is a v2 capability advertisement.
174 using var request = new HttpRequestMessage(HttpMethod.Get, "/jessie/headers.git/info/refs?service=git-upload-pack");
175 request.Headers.Add("Git-Protocol", "version=2");
176 var v2 = await (await client.SendAsync(request)).Content.ReadAsStringAsync();
177 Assert.StartsWith("000eversion 2\n", v2);
178 }
179
180 [Fact]
181 public async Task Oversized_push_is_rejected()
182 {
183 var small = new ForgeHost();
184 small.ExtraArgs.Add("--Forge:MaxPushSizeMb=1");
185 await small.InitializeAsync();
186 try
187 {
188 var user = await small.CreateUserAsync();
189 var repo = await small.CreateRepoAsync(user, "small", Visibility.Public);
190 var token = await small.CreateTokenAsync(user, canWrite: true);
191
192 var work = small.NewDir("work");
193 await small.Git.CreateWorkRepoAsync(work);
194 // Random bytes do not compress, so the pack is larger than the 1 MB limit.
195 await File.WriteAllBytesAsync(Path.Combine(work, "big.bin"), System.Security.Cryptography.RandomNumberGenerator.GetBytes(3 * 1024 * 1024));
196 await small.Git.MustAsync(work, "add", "-A");
197 await small.Git.MustAsync(work, "commit", "-m", "Too big");
198
199 var push = await small.Git.RunAsync(work, "push", small.GitUrl(user.Username, repo.Name, token), "main");
200 Assert.False(push.Ok);
201
202 var refs = await small.WithScopeAsync(sp => sp.GetRequiredService<ForgeDb>().PushEvents.CountAsync());
203 Assert.Equal(0, refs);
204 }
205 finally
206 {
207 await small.DisposeAsync();
208 }
209 }
210
211 private static Task<HttpResponseMessage> GetAsync(HttpClient client, string url, string token)
212 {
213 var request = new HttpRequestMessage(HttpMethod.Get, url);
214 request.Headers.Authorization = new AuthenticationHeaderValue(
215 "Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes("git:" + token)));
216 return client.SendAsync(request);
217 }
218 }
added forge.Tests/Support/BranchScenario.cs +59 −0View file
@@ -0,0 +1,59 @@
1 using Forge.Data;
2
3 namespace Forge.Tests.Support;
4
5 /// <summary>
6 /// A pushed repository with main and a branch "feature/x". The feature branch has two commits:
7 /// it edits line two of a.txt and adds b.txt. Main can be made to diverge, with or without a conflict.
8 /// </summary>
9 public sealed record BranchScenario(ForgeHost Host, Repository Repo, string Work, string Url, string MainSha, string FeatureSha)
10 {
11 public string Name => Repo.Name;
12
13 public static async Task<BranchScenario> CreateAsync(
14 ForgeHost host,
15 string name,
16 bool diverge = false,
17 bool conflict = false,
18 Visibility visibility = Visibility.Public)
19 {
20 var user = await host.CreateUserAsync();
21 var repo = await host.CreateRepoAsync(user, name, visibility);
22 var token = await host.CreateTokenAsync(user, canWrite: true);
23 var url = host.GitUrl("jessie", name, token);
24 var work = host.NewDir("work");
25 var git = host.Git;
26
27 await git.CreateWorkRepoAsync(work, fileName: "a.txt", content: "one\ntwo\nthree\n");
28 await git.MustAsync(work, "checkout", "-b", "feature/x");
29 await File.WriteAllTextAsync(Path.Combine(work, "a.txt"), "one\nTWO from feature\nthree\n");
30 await File.WriteAllTextAsync(Path.Combine(work, "b.txt"), "new file\n");
31 await git.MustAsync(work, "add", "-A");
32 await git.MustAsync(work, "commit", "-m", "Feature work");
33 await File.WriteAllTextAsync(Path.Combine(work, "b.txt"), "new file\nsecond line\n");
34 await git.MustAsync(work, "commit", "-am", "More feature work");
35 var featureSha = await git.MustAsync(work, "rev-parse", "HEAD");
36
37 await git.MustAsync(work, "checkout", "main");
38 if (diverge)
39 {
40 var (file, content) = conflict ? ("a.txt", "one\nTWO from main\nthree\n") : ("c.txt", "only on main\n");
41 await File.WriteAllTextAsync(Path.Combine(work, file), content);
42 await git.MustAsync(work, "add", "-A");
43 await git.MustAsync(work, "commit", "-m", "Main moves on");
44 }
45
46 var mainSha = await git.MustAsync(work, "rev-parse", "HEAD");
47 await git.MustAsync(work, "push", url, "main", "feature/x");
48 return new BranchScenario(host, repo, work, url, mainSha, featureSha);
49 }
50
51 /// <summary>Fetches the server's branches as server/* into the working repository, then runs git there.</summary>
52 public async Task<string> ServerAsync(params string[] args)
53 {
54 await Host.Git.MustAsync(Work, "fetch", "--prune", Url, "+refs/heads/*:refs/remotes/server/*");
55 return await Host.Git.MustAsync(Work, args);
56 }
57
58 public string Page(string relative) => $"/jessie/{Name}/{relative}";
59 }
added forge.Tests/Support/ForgeHost.cs +213 −0View file
@@ -0,0 +1,213 @@
1 using System.Net;
2 using System.Text.RegularExpressions;
3 using Forge.Data;
4 using Forge.Features.Auth;
5 using Forge.Features.Repos;
6 using Forge.Git;
7 using Microsoft.AspNetCore.Identity;
8 using Microsoft.Data.Sqlite;
9 using Microsoft.Extensions.DependencyInjection;
10
11 namespace Forge.Tests.Support;
12
13 /// <summary>
14 /// The real app on a random local port with a temporary data directory and database.
15 /// Tests talk to it over HTTP, with HttpClient and with the real git client.
16 /// </summary>
17 public sealed partial class ForgeHost : IAsyncLifetime
18 {
19 public const string Password = "correct horse battery";
20
21 private readonly TempDir _temp = new();
22 private WebApplication _app = null!;
23
24 public string BaseUrl { get; private set; } = "";
25 public string DataPath => Path.Combine(_temp.Path, "data");
26 public IServiceProvider Services => _app.Services;
27 public TestGit Git { get; private set; } = null!;
28
29 /// <summary>Extra command-line configuration, set by a subclass-free test before InitializeAsync runs.</summary>
30 public List<string> ExtraArgs { get; } = [];
31
32 /// <summary>The forge project folder, found by walking up to the solution file, wherever the build output lives.</summary>
33 public static string WebProjectDirectory
34 {
35 get
36 {
37 for (var dir = new DirectoryInfo(AppContext.BaseDirectory); dir is not null; dir = dir.Parent)
38 {
39 if (File.Exists(Path.Combine(dir.FullName, "forge.slnx")))
40 {
41 return Path.Combine(dir.FullName, "forge");
42 }
43 }
44
45 throw new DirectoryNotFoundException("forge.slnx was not found above " + AppContext.BaseDirectory);
46 }
47 }
48
49 public async Task InitializeAsync()
50 {
51 Git = new TestGit(_temp.Sub("client-home"));
52 string[] args =
53 [
54 "--urls=http://127.0.0.1:0",
55 "--environment=Production",
56 "--Forge:DataPath=" + DataPath,
57 "--Forge:BaseUrl=http://forge.test",
58 "--Forge:GitPath=" + TestGit.Executable,
59 "--Logging:LogLevel:Default=Warning",
60 // The web project's directory, so wwwroot is served as it is in a real run.
61 "--contentRoot=" + WebProjectDirectory,
62 .. ExtraArgs,
63 ];
64 _app = ForgeApp.Build(args);
65 await ForgeApp.InitializeAsync(_app);
66 await _app.StartAsync();
67 BaseUrl = _app.Urls.First().TrimEnd('/');
68 }
69
70 public async Task DisposeAsync()
71 {
72 await _app.StopAsync();
73 await _app.DisposeAsync();
74 SqliteConnection.ClearAllPools();
75 _temp.Dispose();
76 }
77
78 public string NewDir(string name) => _temp.Sub(name + "-" + Guid.NewGuid().ToString("N")[..8]);
79
80 public string RepoDirectory(long repoId) => Path.Combine(DataPath, "repos", repoId + ".git");
81
82 /// <summary>Clone URL with the token embedded as the password, the way a user would paste it.</summary>
83 public string GitUrl(string owner, string repo, string? token = null)
84 {
85 var authority = BaseUrl["http://".Length..];
86 return token is null
87 ? $"http://{authority}/{owner}/{repo}.git"
88 : $"http://git:{token}@{authority}/{owner}/{repo}.git";
89 }
90
91 public async Task<T> WithScopeAsync<T>(Func<IServiceProvider, Task<T>> action)
92 {
93 await using var scope = Services.CreateAsyncScope();
94 return await action(scope.ServiceProvider);
95 }
96
97 public Task<User> CreateUserAsync(string username = "jessie") =>
98 WithScopeAsync(async sp =>
99 {
100 var db = sp.GetRequiredService<ForgeDb>();
101 // Tests in one class share the host, so the user may already be there.
102 if (db.Users.FirstOrDefault(u => u.Username == username) is { } existing)
103 {
104 return existing;
105 }
106
107 var user = new User { Username = username, DisplayName = username, CreatedAt = DateTime.UtcNow };
108 user.PasswordHash = sp.GetRequiredService<IPasswordHasher<User>>().HashPassword(user, Password);
109 db.Users.Add(user);
110 await db.SaveChangesAsync();
111 return user;
112 });
113
114 public Task<Repository> CreateRepoAsync(User owner, string name, Visibility visibility) =>
115 WithScopeAsync(async sp =>
116 {
117 var (repo, error) = await sp.GetRequiredService<RepoService>().CreateAsync(owner.Id, name, "", visibility);
118 Assert.True(repo is not null, error);
119 return repo!;
120 });
121
122 public Task<string> CreateTokenAsync(User user, bool canWrite, DateTime? expiresAt = null) =>
123 WithScopeAsync(async sp =>
124 {
125 var (_, plaintext) = await sp.GetRequiredService<TokenService>()
126 .CreateAsync(user.Id, canWrite ? "write" : "read", canWrite, expiresAt);
127 return plaintext;
128 });
129
130 public Task<Repository> ReloadRepoAsync(long id) =>
131 WithScopeAsync(async sp => (await sp.GetRequiredService<ForgeDb>().Repositories.FindAsync(id))!);
132
133 /// <summary>A client that keeps cookies and does not follow redirects, so tests can assert on them.</summary>
134 public HttpClient CreateClient() =>
135 new(new HttpClientHandler { AllowAutoRedirect = false, UseCookies = true, CookieContainer = new CookieContainer() })
136 {
137 BaseAddress = new Uri(BaseUrl),
138 };
139
140 /// <summary>Submits a server-rendered form the way a browser would: load the page, then post with its antiforgery token.</summary>
141 public static async Task<HttpResponseMessage> PostFormAsync(
142 HttpClient client,
143 string pageUrl,
144 string formName,
145 Dictionary<string, string> fields)
146 {
147 var page = await client.GetAsync(pageUrl);
148 var html = await page.Content.ReadAsStringAsync();
149 var match = AntiforgeryToken().Match(html);
150 Assert.True(match.Success, $"No antiforgery token on {pageUrl} (status {(int)page.StatusCode}).");
151
152 var form = new Dictionary<string, string>(fields)
153 {
154 ["__RequestVerificationToken"] = WebUtility.HtmlDecode(match.Groups[1].Value),
155 ["_handler"] = formName,
156 };
157 return await client.PostAsync(pageUrl, new FormUrlEncodedContent(form));
158 }
159
160 /// <summary>Page text with HTML entities decoded; the renderer writes non-ASCII letters as entities.</summary>
161 public static async Task<string> TextAsync(HttpResponseMessage response) =>
162 WebUtility.HtmlDecode(await response.Content.ReadAsStringAsync());
163
164 private readonly Dictionary<string, CookieContainer> _sessions = [];
165
166 /// <summary>
167 /// A client signed in as the user. The login happens once per host and its cookies are reused,
168 /// so a class with many tests does not run into the login rate limit.
169 /// </summary>
170 public async Task<HttpClient> CreateSignedInClientAsync(string username = "jessie")
171 {
172 if (_sessions.TryGetValue(username, out var cookies))
173 {
174 return new HttpClient(new HttpClientHandler { AllowAutoRedirect = false, UseCookies = true, CookieContainer = cookies })
175 {
176 BaseAddress = new Uri(BaseUrl),
177 };
178 }
179
180 cookies = new CookieContainer();
181 _sessions[username] = cookies;
182 var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false, UseCookies = true, CookieContainer = cookies })
183 {
184 BaseAddress = new Uri(BaseUrl),
185 };
186 var response = await PostFormAsync(client, "/login", "login", new()
187 {
188 ["Username"] = username,
189 ["Password"] = Password,
190 });
191 Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
192 return client;
193 }
194
195 /// <summary>Creates a repository and pushes one commit to it. Returns the pushed commit SHA.</summary>
196 public async Task<(Repository Repo, string Sha, string WorkDir)> CreatePushedRepoAsync(
197 User owner,
198 string name,
199 Visibility visibility,
200 string fileName = "README.md",
201 string content = "# Demo\n")
202 {
203 var repo = await CreateRepoAsync(owner, name, visibility);
204 var token = await CreateTokenAsync(owner, canWrite: true);
205 var work = NewDir("work");
206 var sha = await Git.CreateWorkRepoAsync(work, fileName: fileName, content: content);
207 await Git.MustAsync(work, "push", GitUrl(owner.Username, name, token), "main");
208 return (repo, sha, work);
209 }
210
211 [GeneratedRegex("name=\"__RequestVerificationToken\" value=\"([^\"]+)\"")]
212 private static partial Regex AntiforgeryToken();
213 }
added forge.Tests/Support/TestGit.cs +96 −0View file
@@ -0,0 +1,96 @@
1 using System.Text;
2 using CliWrap;
3 using Forge.Git;
4
5 namespace Forge.Tests.Support;
6
7 public sealed record GitRun(int ExitCode, string StdOut, string StdErr)
8 {
9 public bool Ok => ExitCode == 0;
10 }
11
12 /// <summary>
13 /// The git client used by tests, as a user's machine would run it. Isolated from the real machine:
14 /// no system or user config, no credential helper, and no prompts, so a rejected push fails instead of hanging.
15 /// </summary>
16 public sealed class TestGit(string home)
17 {
18 public static string Executable => Environment.GetEnvironmentVariable("FORGE_TEST_GIT") ?? "git";
19
20 public async Task<GitRun> RunAsync(string workDir, params string[] args)
21 {
22 var stdout = new StringBuilder();
23 var stderr = new StringBuilder();
24 using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(2));
25
26 var result = await Cli.Wrap(Executable)
27 .WithArguments(args)
28 .WithWorkingDirectory(workDir)
29 .WithEnvironmentVariables(new Dictionary<string, string?>
30 {
31 ["GIT_CONFIG_NOSYSTEM"] = "1",
32 ["HOME"] = home,
33 ["XDG_CONFIG_HOME"] = Path.Combine(home, ".config"),
34 ["GIT_TERMINAL_PROMPT"] = "0",
35 ["GCM_INTERACTIVE"] = "never",
36 ["GIT_ASKPASS"] = null,
37 ["SSH_ASKPASS"] = null,
38 ["GIT_AUTHOR_NAME"] = "Test Author",
39 ["GIT_AUTHOR_EMAIL"] = "author@example.com",
40 ["GIT_COMMITTER_NAME"] = "Test Author",
41 ["GIT_COMMITTER_EMAIL"] = "author@example.com",
42 ["GIT_DIR"] = null,
43 ["GIT_WORK_TREE"] = null,
44 ["LC_ALL"] = "C",
45 })
46 .WithStandardOutputPipe(PipeTarget.ToStringBuilder(stdout))
47 .WithStandardErrorPipe(PipeTarget.ToStringBuilder(stderr))
48 .WithValidation(CommandResultValidation.None)
49 .ExecuteAsync(timeout.Token);
50
51 return new GitRun(result.ExitCode, stdout.ToString(), stderr.ToString());
52 }
53
54 /// <summary>Runs git and fails the test with git's own output if it exits non-zero.</summary>
55 public async Task<string> MustAsync(string workDir, params string[] args)
56 {
57 var run = await RunAsync(workDir, args);
58 Assert.True(run.Ok, $"git {string.Join(' ', args)} failed ({run.ExitCode}):\n{run.StdOut}\n{run.StdErr}");
59 return run.StdOut.Trim();
60 }
61
62 /// <summary>Creates a working repository on branch <paramref name="branch"/> with one commit.</summary>
63 public async Task<string> CreateWorkRepoAsync(string path, string branch = "main", string fileName = "README.md", string content = "# Demo\n")
64 {
65 Directory.CreateDirectory(path);
66 await MustAsync(path, "init", "--initial-branch=" + branch, ".");
67 await File.WriteAllTextAsync(Path.Combine(path, fileName), content);
68 await MustAsync(path, "add", "-A");
69 await MustAsync(path, "commit", "-m", "First commit");
70 return await MustAsync(path, "rev-parse", "HEAD");
71 }
72 }
73
74 public sealed class TempDir : IDisposable
75 {
76 public string Path { get; } = Directory.CreateTempSubdirectory("forge-test-").FullName;
77
78 public string Sub(string name)
79 {
80 var path = System.IO.Path.Combine(Path, name);
81 Directory.CreateDirectory(path);
82 return path;
83 }
84
85 public void Dispose()
86 {
87 try
88 {
89 RepoPaths.DeleteDirectory(Path);
90 }
91 catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
92 {
93 // A leftover temp directory must not fail a test run.
94 }
95 }
96 }
added forge.Tests/WebTests.cs +650 −0View file
@@ -0,0 +1,650 @@
1 using System.Net;
2 using Forge.Data;
3 using Forge.Features.Repos;
4 using Forge.Tests.Support;
5 using Microsoft.EntityFrameworkCore;
6 using Microsoft.Extensions.DependencyInjection;
7
8 namespace Forge.Tests;
9
10 /// <summary>Pages, permissions and the raw endpoint, over HTTP against the running app.</summary>
11 public class WebTests(ForgeHost host) : IClassFixture<ForgeHost>
12 {
13 private static string[] RepoPages(string repo, string sha) =>
14 [
15 $"/jessie/{repo}",
16 $"/jessie/{repo}/tree/main",
17 $"/jessie/{repo}/blob/main/README.md",
18 $"/jessie/{repo}/raw/main/README.md",
19 $"/jessie/{repo}/commits/main",
20 $"/jessie/{repo}/commits",
21 $"/jessie/{repo}/commit/{sha}",
22 $"/jessie/{repo}/branches",
23 $"/jessie/{repo}/tags",
24 $"/jessie/{repo}/atom",
25 $"/jessie/{repo}/search?q=Demo",
26 $"/jessie/{repo}/activity",
27 ];
28
29 private static string[] AdminPages(string repo) =>
30 [
31 $"/jessie/{repo}/settings",
32 $"/jessie/{repo}/settings/webhooks",
33 ];
34
35 [Fact]
36 public async Task Anonymous_visitor_gets_404_for_everything_in_a_private_repository()
37 {
38 var user = await host.CreateUserAsync();
39 var (_, sha, _) = await host.CreatePushedRepoAsync(user, "secret", Visibility.Private);
40 using var anonymous = host.CreateClient();
41
42 foreach (var url in RepoPages("secret", sha).Concat(AdminPages("secret")))
43 {
44 var response = await anonymous.GetAsync(url);
45 Assert.True(response.StatusCode == HttpStatusCode.NotFound, $"{url} answered {(int)response.StatusCode}, expected 404");
46 }
47
48 // The home page does not list it either.
49 Assert.DoesNotContain("secret", await anonymous.GetStringAsync("/"));
50
51 // The owner sees all of it.
52 using var owner = await host.CreateSignedInClientAsync();
53 foreach (var url in RepoPages("secret", sha).Concat(AdminPages("secret")))
54 {
55 var response = await owner.GetAsync(url);
56 Assert.True(response.StatusCode == HttpStatusCode.OK, $"{url} answered {(int)response.StatusCode} for the owner, expected 200");
57 }
58
59 Assert.Contains("secret", await owner.GetStringAsync("/"));
60 }
61
62 [Fact]
63 public async Task Public_repository_is_readable_but_its_settings_are_hidden()
64 {
65 var user = await host.CreateUserAsync();
66 var (_, sha, _) = await host.CreatePushedRepoAsync(user, "open", Visibility.Public);
67 using var anonymous = host.CreateClient();
68
69 foreach (var url in RepoPages("open", sha))
70 {
71 var response = await anonymous.GetAsync(url);
72 Assert.True(response.StatusCode == HttpStatusCode.OK, $"{url} answered {(int)response.StatusCode}, expected 200");
73 }
74
75 foreach (var url in AdminPages("open"))
76 {
77 Assert.Equal(HttpStatusCode.NotFound, (await anonymous.GetAsync(url)).StatusCode);
78 }
79
80 Assert.Contains("open", await anonymous.GetStringAsync("/"));
81 }
82
83 [Fact]
84 public async Task Home_page_searches_and_sorts_repositories()
85 {
86 var user = await host.CreateUserAsync();
87 await host.WithScopeAsync(async sp =>
88 {
89 var repos = sp.GetRequiredService<RepoService>();
90 await repos.CreateAsync(user.Id, "zebra-tools", "Stripes for everyone", Visibility.Public);
91 await repos.CreateAsync(user.Id, "aardvark", "100% ants", Visibility.Public);
92 return 0;
93 });
94 using var client = host.CreateClient();
95
96 var byName = await client.GetStringAsync("/?q=ZEBRA");
97 Assert.Contains("zebra-tools", byName);
98 Assert.DoesNotContain("aardvark", byName);
99
100 // The description is searched too, and LIKE wildcards in the text are literal.
101 var byDescription = await client.GetStringAsync("/?q=100%25");
102 Assert.Contains("aardvark", byDescription);
103 Assert.DoesNotContain("zebra-tools", byDescription);
104 Assert.DoesNotContain("zebra-tools", await client.GetStringAsync("/?q=_ebra"));
105
106 var nothing = await ForgeHost.TextAsync(await client.GetAsync("/?q=no-such-thing"));
107 Assert.Contains("No repository matches “no-such-thing”.", nothing);
108
109 var sorted = await client.GetStringAsync("/jessie?sort=name");
110 Assert.True(sorted.IndexOf("aardvark", StringComparison.Ordinal) < sorted.IndexOf("zebra-tools", StringComparison.Ordinal));
111 }
112
113 [Fact]
114 public async Task Pages_show_repository_content()
115 {
116 var user = await host.CreateUserAsync();
117 var repo = await host.CreateRepoAsync(user, "content", Visibility.Public);
118 var token = await host.CreateTokenAsync(user, canWrite: true);
119 using var client = host.CreateClient();
120
121 // Before the first push the page explains how to push.
122 var empty = await client.GetStringAsync("/jessie/content");
123 Assert.Contains("The repository is empty", empty);
124 Assert.Contains("git clone http://forge.test/jessie/content.git", empty);
125
126 var work = host.NewDir("work");
127 await host.Git.CreateWorkRepoAsync(work, content: "# Hello\n\nSee [the code](src/app.cs) and ![logo](logo.png).\n");
128 Directory.CreateDirectory(Path.Combine(work, "src"));
129 await File.WriteAllTextAsync(Path.Combine(work, "src", "app.cs"), "class App\n{\n}\n");
130 await host.Git.MustAsync(work, "add", "-A");
131 await host.Git.MustAsync(work, "commit", "-m", "Add the app");
132 var sha = await host.Git.MustAsync(work, "rev-parse", "HEAD");
133 await host.Git.MustAsync(work, "checkout", "-b", "feature/x");
134 await host.Git.MustAsync(work, "tag", "v1");
135 await host.Git.MustAsync(work, "push", host.GitUrl("jessie", "content", token), "main", "feature/x", "v1");
136
137 var home = await client.GetStringAsync("/jessie/content");
138 Assert.Contains("README.md", home);
139 Assert.Contains(">src</a>", home);
140 Assert.Contains("<h1>Hello</h1>", home);
141 Assert.Contains("href=\"/jessie/content/blob/main/src/app.cs\"", home);
142 Assert.Contains("src=\"/jessie/content/raw/main/logo.png\"", home);
143 Assert.Contains("Add the app", home);
144
145 // Every entry shows the commit that last changed it; the side panel summarises the repository.
146 Assert.Contains("First commit</a>", home);
147 Assert.Contains("2 commits", home);
148 Assert.Contains("2 branches", home);
149 Assert.Contains("1 tag<", home);
150 Assert.Contains("class=\"lang-csharp\"", home);
151 Assert.Contains("100.0 %", home);
152
153 // A branch name with a slash resolves, and the rest of the URL is the path.
154 var tree = await client.GetStringAsync("/jessie/content/tree/feature/x/src");
155 Assert.Contains("app.cs", tree);
156
157 var blob = await client.GetStringAsync("/jessie/content/blob/main/src/app.cs");
158 Assert.Contains("class App", blob);
159 Assert.Contains("id=\"L3\"", blob);
160 Assert.Contains("language-csharp", blob);
161 Assert.Contains("/lib/highlight/highlight.min.js", blob);
162 Assert.DoesNotContain("/lib/highlight/highlight.min.js", home);
163
164 // A Markdown file is rendered; ?plain=1 shows its source with line numbers instead.
165 var preview = await client.GetStringAsync("/jessie/content/blob/main/README.md");
166 Assert.Contains("<h1>Hello</h1>", preview);
167 Assert.DoesNotContain("id=\"L1\"", preview);
168 var source = await client.GetStringAsync("/jessie/content/blob/main/README.md?plain=1");
169 Assert.Contains("# Hello", source);
170 Assert.Contains("id=\"L1\"", source);
171
172 // The permalink names the commit, so it keeps pointing at this version.
173 Assert.Contains($"href=\"/jessie/content/blob/{sha}/src/app.cs\"", blob);
174
175 var commits = await client.GetStringAsync("/jessie/content/commits/main/src/app.cs");
176 Assert.Contains("Add the app", commits);
177 Assert.DoesNotContain("First commit", commits);
178 Assert.Contains("Commits on ", commits);
179 Assert.Contains($"data-copy=\"{sha}\"", commits);
180
181 var commit = await client.GetStringAsync($"/jessie/content/commit/{sha}");
182 Assert.Contains("src/app.cs", commit);
183 Assert.Contains("class App", commit);
184
185 // Both commits were made just now, so they fall into the current week of the chart.
186 var activity = await client.GetStringAsync("/jessie/content/activity");
187 Assert.Contains("Commits per week", activity);
188 Assert.Contains("The last 52 weeks, 2 commits in total", activity);
189 Assert.Single(System.Text.RegularExpressions.Regex.Matches(activity, "class=\"week-bar\""));
190 Assert.Single(System.Text.RegularExpressions.Regex.Matches(activity, "class=\"contributor\""));
191
192 Assert.Contains("feature/x", await client.GetStringAsync("/jessie/content/branches"));
193 Assert.Contains("v1", await client.GetStringAsync("/jessie/content/tags"));
194
195 var atom = await client.GetAsync("/jessie/content/atom");
196 Assert.Equal("application/atom+xml", atom.Content.Headers.ContentType?.MediaType);
197 var feed = await atom.Content.ReadAsStringAsync();
198 Assert.Contains("<title>Add the app</title>", feed);
199 Assert.Contains($"http://forge.test/jessie/content/commit/{sha}", feed);
200
201 // Paths and refs that do not exist are plain 404s.
202 Assert.Equal(HttpStatusCode.NotFound, (await client.GetAsync("/jessie/content/tree/nope")).StatusCode);
203 Assert.Equal(HttpStatusCode.NotFound, (await client.GetAsync("/jessie/content/blob/main/nope.txt")).StatusCode);
204 Assert.Equal(HttpStatusCode.NotFound, (await client.GetAsync("/jessie/content/commit/" + new string('0', 40))).StatusCode);
205 Assert.Equal(HttpStatusCode.NotFound, (await client.GetAsync("/jessie/nope")).StatusCode);
206
207 // A blob URL for a directory, and a tree URL for a file, redirect to the right view.
208 var redirect = await client.GetAsync("/jessie/content/blob/main/src");
209 Assert.Equal("/jessie/content/tree/main/src", redirect.Headers.Location?.PathAndQuery);
210 }
211
212 [Fact]
213 public async Task Search_finds_file_names_and_code_and_treats_the_text_literally()
214 {
215 var user = await host.CreateUserAsync();
216 var repo = await host.CreateRepoAsync(user, "searchable", Visibility.Public);
217 var token = await host.CreateTokenAsync(user, canWrite: true);
218 var work = host.NewDir("work");
219 await host.Git.CreateWorkRepoAsync(work, content: "# Notes\n\nThe Anvil is heavy.\n");
220 Directory.CreateDirectory(Path.Combine(work, "src"));
221 await File.WriteAllTextAsync(Path.Combine(work, "src", "anvil.cs"), "class Hammer\n{\n // strikes <b>the</b> anvil.*\n}\n");
222 await File.WriteAllBytesAsync(Path.Combine(work, "anvil.bin"), [1, 0, (byte)'a', (byte)'n', (byte)'v', (byte)'i', (byte)'l']);
223 await host.Git.MustAsync(work, "add", "-A");
224 await host.Git.MustAsync(work, "commit", "-m", "Add files");
225 await host.Git.MustAsync(work, "tag", "v1");
226 await host.Git.MustAsync(work, "push", host.GitUrl("jessie", repo.Name, token), "main", "v1");
227 using var client = host.CreateClient();
228 var marker = Path.Combine(host.DataPath, "pwned-by-search");
229
230 // Case does not matter; both the file names and the lines are found, binary content is not.
231 var page = await client.GetStringAsync("/jessie/searchable/search?q=ANVIL");
232 Assert.Contains("src/<mark>anvil</mark>.cs", page);
233 Assert.Contains("<mark>anvil</mark>.bin", page);
234 Assert.Contains("The <mark>Anvil</mark> is heavy.", page);
235 Assert.Contains("href=\"/jessie/searchable/blob/main/src/anvil.cs#L3\"", page);
236 // A match in a Markdown file links to its source view, where the line exists.
237 Assert.Contains("href=\"/jessie/searchable/blob/main/README.md?plain=1#L3\"", page);
238
239 // The text is literal (no regular expression) and is encoded on the way out.
240 var literal = await client.GetStringAsync("/jessie/searchable/search?q=" + Uri.EscapeDataString("anvil.*"));
241 Assert.Contains("<mark>anvil.*</mark>", literal);
242 Assert.DoesNotContain("is heavy", literal);
243 var html = await client.GetStringAsync("/jessie/searchable/search?q=" + Uri.EscapeDataString("<b>the</b>"));
244 Assert.Contains("<mark>&lt;b&gt;the&lt;/b&gt;</mark>", html);
245 Assert.DoesNotContain("<b>the</b>", html);
246
247 // Text that looks like an option is still just text.
248 foreach (var hostile in (string[])["--output=" + marker, "-O" + marker, "--open-files-in-pager=touch " + marker])
249 {
250 var response = await client.GetAsync("/jessie/searchable/search?q=" + Uri.EscapeDataString(hostile));
251 Assert.Equal(HttpStatusCode.OK, response.StatusCode);
252 }
253
254 Assert.False(File.Exists(marker));
255
256 // A tag can be searched; a ref that does not exist is a 404; nothing found says so.
257 Assert.Contains("class <mark>Hammer</mark>", await client.GetStringAsync("/jessie/searchable/search?q=hammer&ref=v1"));
258 Assert.Equal(HttpStatusCode.NotFound, (await client.GetAsync("/jessie/searchable/search?q=hammer&ref=--all")).StatusCode);
259 var nothing = await ForgeHost.TextAsync(await client.GetAsync("/jessie/searchable/search?q=zzzz"));
260 Assert.Contains("Nothing in main matches “zzzz”.", nothing);
261
262 // One character is too short to search for.
263 Assert.Contains("Search this repository", await client.GetStringAsync("/jessie/searchable/search?q=a"));
264 }
265
266 [Fact]
267 public async Task Option_like_refs_are_not_found()
268 {
269 var user = await host.CreateUserAsync();
270 await host.CreatePushedRepoAsync(user, "hostile", Visibility.Public);
271 using var client = host.CreateClient();
272 var marker = Path.Combine(host.DataPath, "pwned");
273
274 string[] refs = ["--upload-pack=touch " + marker, "--output=" + marker, "-n", "--all"];
275 foreach (var hostile in refs)
276 {
277 var encoded = Uri.EscapeDataString(hostile);
278 foreach (var view in (string[])["tree", "blob", "raw", "commits"])
279 {
280 var response = await client.GetAsync($"/jessie/hostile/{view}/{encoded}/README.md");
281 Assert.True(response.StatusCode == HttpStatusCode.NotFound, $"{view}/{hostile} answered {(int)response.StatusCode}");
282 }
283
284 Assert.Equal(HttpStatusCode.NotFound, (await client.GetAsync($"/jessie/hostile/commit/{encoded}")).StatusCode);
285 }
286
287 Assert.False(File.Exists(marker));
288 }
289
290 [Fact]
291 public async Task Raw_never_serves_html_and_only_inlines_safe_images()
292 {
293 var user = await host.CreateUserAsync();
294 var repo = await host.CreateRepoAsync(user, "raw", Visibility.Public);
295 var token = await host.CreateTokenAsync(user, canWrite: true);
296
297 var work = host.NewDir("work");
298 await host.Git.CreateWorkRepoAsync(work, fileName: "index.html", content: "<script>alert(1)</script>\n");
299 await File.WriteAllTextAsync(Path.Combine(work, "icon.svg"), "<svg xmlns=\"http://www.w3.org/2000/svg\"><script>alert(1)</script></svg>\n");
300 await File.WriteAllBytesAsync(Path.Combine(work, "pixel.png"), [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 0]);
301 await File.WriteAllBytesAsync(Path.Combine(work, "data.bin"), [1, 0, 2, 0, 3]);
302 await File.WriteAllTextAsync(Path.Combine(work, "name with space.txt"), "spaced\n");
303 await host.Git.MustAsync(work, "add", "-A");
304 await host.Git.MustAsync(work, "commit", "-m", "Files");
305 await host.Git.MustAsync(work, "push", host.GitUrl("jessie", repo.Name, token), "main");
306 using var client = host.CreateClient();
307
308 var html = await client.GetAsync("/jessie/raw/raw/main/index.html");
309 Assert.Equal(HttpStatusCode.OK, html.StatusCode);
310 Assert.Equal("text/plain; charset=utf-8", html.Content.Headers.ContentType?.ToString());
311 Assert.Equal("nosniff", html.Headers.GetValues("X-Content-Type-Options").Single());
312 Assert.Equal("<script>alert(1)</script>\n", await html.Content.ReadAsStringAsync());
313
314 var svg = await client.GetAsync("/jessie/raw/raw/main/icon.svg");
315 Assert.Equal("application/octet-stream", svg.Content.Headers.ContentType?.MediaType);
316 Assert.Equal("attachment", svg.Content.Headers.ContentDisposition?.DispositionType);
317
318 var png = await client.GetAsync("/jessie/raw/raw/main/pixel.png");
319 Assert.Equal("image/png", png.Content.Headers.ContentType?.MediaType);
320 Assert.Null(png.Content.Headers.ContentDisposition);
321 Assert.Equal(12, (await png.Content.ReadAsByteArrayAsync()).Length);
322
323 var bin = await client.GetAsync("/jessie/raw/raw/main/data.bin");
324 Assert.Equal("application/octet-stream", bin.Content.Headers.ContentType?.MediaType);
325 Assert.Equal("attachment", bin.Content.Headers.ContentDisposition?.DispositionType);
326 Assert.Equal(new byte[] { 1, 0, 2, 0, 3 }, await bin.Content.ReadAsByteArrayAsync());
327
328 var spaced = await client.GetAsync("/jessie/raw/raw/main/name%20with%20space.txt");
329 Assert.Equal("spaced\n", await spaced.Content.ReadAsStringAsync());
330
331 // ETag is the blob SHA; a matching If-None-Match gets 304 with no body.
332 var etag = html.Headers.ETag;
333 Assert.NotNull(etag);
334 using var conditional = new HttpRequestMessage(HttpMethod.Get, "/jessie/raw/raw/main/index.html");
335 conditional.Headers.IfNoneMatch.Add(etag);
336 var notModified = await client.SendAsync(conditional);
337 Assert.Equal(HttpStatusCode.NotModified, notModified.StatusCode);
338 Assert.Empty(await notModified.Content.ReadAsByteArrayAsync());
339
340 // The blob page shows the HTML file as escaped source, never as markup.
341 var page = await client.GetStringAsync("/jessie/raw/blob/main/index.html");
342 Assert.Contains("&lt;script&gt;alert(1)&lt;/script&gt;", page);
343 Assert.DoesNotContain("<script>alert(1)</script>", page);
344 }
345
346 [Fact]
347 public async Task Security_headers_are_on_every_page()
348 {
349 await host.CreateUserAsync();
350 using var client = host.CreateClient();
351
352 var response = await client.GetAsync("/login");
353
354 Assert.Equal(HttpStatusCode.OK, response.StatusCode);
355 Assert.StartsWith("default-src 'self'", response.Headers.GetValues("Content-Security-Policy").Single());
356 Assert.Equal("nosniff", response.Headers.GetValues("X-Content-Type-Options").Single());
357 Assert.Equal("DENY", response.Headers.GetValues("X-Frame-Options").Single());
358 // The CSP forbids inline script and style, so pages must not contain any.
359 var html = await response.Content.ReadAsStringAsync();
360 Assert.DoesNotContain("style=\"", html);
361 Assert.DoesNotContain("<script>", html);
362 }
363
364 [Theory]
365 [InlineData("/style.css", "text/css")]
366 [InlineData("/app.js", "text/javascript")]
367 [InlineData("/theme.js", "text/javascript")]
368 [InlineData("/favicon.png", "image/png")]
369 [InlineData("/lib/highlight/highlight.min.js", "text/javascript")]
370 [InlineData("/lib/highlight/github.min.css", "text/css")]
371 public async Task Static_assets_are_served_and_not_mistaken_for_pages(string url, string contentType)
372 {
373 await host.CreateUserAsync();
374 using var client = host.CreateClient();
375
376 var response = await client.GetAsync(url);
377
378 Assert.Equal(HttpStatusCode.OK, response.StatusCode);
379 Assert.Equal(contentType, response.Content.Headers.ContentType?.MediaType);
380 }
381
382 [Fact]
383 public async Task Forms_require_an_antiforgery_token()
384 {
385 await host.CreateUserAsync();
386 using var client = host.CreateClient();
387
388 var response = await client.PostAsync("/login", new FormUrlEncodedContent(new Dictionary<string, string>
389 {
390 ["_handler"] = "login",
391 ["Username"] = "jessie",
392 ["Password"] = ForgeHost.Password,
393 }));
394
395 Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
396 }
397
398 [Fact]
399 public async Task Signed_in_owner_manages_repository_through_forms()
400 {
401 var user = await host.CreateUserAsync();
402 using var client = await host.CreateSignedInClientAsync();
403
404 // Pages that need a session send anonymous visitors to the login page.
405 using var anonymous = host.CreateClient();
406 var bounced = await anonymous.GetAsync("/new");
407 Assert.Equal(HttpStatusCode.Redirect, bounced.StatusCode);
408 Assert.StartsWith("/login", bounced.Headers.Location!.PathAndQuery);
409
410 // Invalid names are refused with a message.
411 var invalid = await ForgeHost.PostFormAsync(client, "/new", "new-repo", new() { ["Name"] = "bad..name", ["Visibility"] = "private" });
412 Assert.Equal(HttpStatusCode.OK, invalid.StatusCode);
413 Assert.Contains("alert error", await ForgeHost.TextAsync(invalid));
414
415 var created = await ForgeHost.PostFormAsync(client, "/new", "new-repo", new()
416 {
417 ["Name"] = "managed",
418 ["Description"] = "A managed repo",
419 ["Visibility"] = "private",
420 });
421 Assert.Equal("/jessie/managed", created.Headers.Location?.PathAndQuery);
422
423 var repo = await host.WithScopeAsync(sp => sp.GetRequiredService<ForgeDb>().Repositories.SingleAsync(r => r.Name == "managed"));
424 var directory = host.RepoDirectory(repo.Id);
425 Assert.True(File.Exists(Path.Combine(directory, "HEAD")));
426 Assert.Equal(Visibility.Private, repo.Visibility);
427
428 // A duplicate name is refused.
429 var duplicate = await ForgeHost.PostFormAsync(client, "/new", "new-repo", new() { ["Name"] = "MANAGED", ["Visibility"] = "private" });
430 Assert.Contains("already exists", await ForgeHost.TextAsync(duplicate));
431
432 // Description and visibility.
433 var saved = await ForgeHost.PostFormAsync(client, "/jessie/managed/settings", "general", new()
434 {
435 ["Description"] = "Now public",
436 ["Visibility"] = "public",
437 });
438 Assert.Contains("Saved.", await ForgeHost.TextAsync(saved));
439 Assert.Equal(Visibility.Public, (await host.ReloadRepoAsync(repo.Id)).Visibility);
440
441 // Rename changes the row and the URL, never the directory.
442 var renamed = await ForgeHost.PostFormAsync(client, "/jessie/managed/settings", "rename", new() { ["NewName"] = "renamed" });
443 Assert.Equal("/jessie/renamed/settings", renamed.Headers.Location?.PathAndQuery);
444 Assert.Equal("renamed", (await host.ReloadRepoAsync(repo.Id)).Name);
445 Assert.True(Directory.Exists(directory));
446 Assert.Equal(HttpStatusCode.NotFound, (await client.GetAsync("/jessie/managed")).StatusCode);
447 Assert.Equal(HttpStatusCode.OK, (await client.GetAsync("/jessie/renamed")).StatusCode);
448
449 // Default branch: push two branches, then switch.
450 var token = await host.CreateTokenAsync(user, canWrite: true);
451 var work = host.NewDir("work");
452 await host.Git.CreateWorkRepoAsync(work);
453 await host.Git.MustAsync(work, "branch", "develop");
454 await host.Git.MustAsync(work, "push", host.GitUrl("jessie", "renamed", token), "main", "develop");
455 await ForgeHost.PostFormAsync(client, "/jessie/renamed/settings", "default-branch", new() { ["Branch"] = "develop" });
456 Assert.Equal("develop", (await host.ReloadRepoAsync(repo.Id)).DefaultBranch);
457 var bogus = await ForgeHost.PostFormAsync(client, "/jessie/renamed/settings", "default-branch", new() { ["Branch"] = "--delete" });
458 Assert.Contains("alert error", await ForgeHost.TextAsync(bogus));
459
460 // Delete needs the name typed back.
461 var refused = await ForgeHost.PostFormAsync(client, "/jessie/renamed/settings", "delete", new() { ["ConfirmName"] = "wrong" });
462 Assert.Contains("does not match", await ForgeHost.TextAsync(refused));
463 Assert.True(Directory.Exists(directory));
464
465 var deleted = await ForgeHost.PostFormAsync(client, "/jessie/renamed/settings", "delete", new() { ["ConfirmName"] = "renamed" });
466 Assert.Equal("/", deleted.Headers.Location?.PathAndQuery);
467 Assert.False(Directory.Exists(directory));
468 Assert.False(await host.WithScopeAsync(sp => sp.GetRequiredService<ForgeDb>().Repositories.AnyAsync(r => r.Id == repo.Id)));
469 }
470
471 [Fact]
472 public async Task Tokens_are_shown_once_and_stored_hashed()
473 {
474 var user = await host.CreateUserAsync();
475 using var client = await host.CreateSignedInClientAsync();
476
477 var created = await ForgeHost.PostFormAsync(client, "/settings/tokens", "create-token", new()
478 {
479 ["Name"] = "laptop",
480 ["Scope"] = "write",
481 ["ExpiresInDays"] = "30",
482 });
483 var html = await created.Content.ReadAsStringAsync();
484 var plaintext = System.Text.RegularExpressions.Regex.Match(html, "forge_[0-9a-f]{64}").Value;
485 Assert.NotEmpty(plaintext);
486
487 var row = await host.WithScopeAsync(sp => sp.GetRequiredService<ForgeDb>().AccessTokens.SingleAsync(t => t.Name == "laptop"));
488 Assert.Equal(Features.Auth.TokenService.Hash(plaintext), row.TokenHash);
489 Assert.True(row.CanWrite);
490 Assert.InRange(row.ExpiresAt!.Value, DateTime.UtcNow.AddDays(29), DateTime.UtcNow.AddDays(31));
491
492 // Loading the page again does not show it, and the database never had it.
493 Assert.DoesNotContain(plaintext, await client.GetStringAsync("/settings/tokens"));
494 foreach (var file in Directory.GetFiles(host.DataPath, "forge.db*"))
495 {
496 // The app has the database open, so read it with sharing. The WAL file counts too.
497 await using var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
498 using var buffer = new MemoryStream();
499 await stream.CopyToAsync(buffer);
500 Assert.DoesNotContain(plaintext, System.Text.Encoding.Latin1.GetString(buffer.ToArray()));
501 }
502
503 // The token works for git, and stops working once revoked.
504 var repo = await host.CreateRepoAsync(user, "token-check", Visibility.Private);
505 var work = host.NewDir("work");
506 await host.Git.CreateWorkRepoAsync(work);
507 await host.Git.MustAsync(work, "push", host.GitUrl("jessie", repo.Name, plaintext), "main");
508
509 await ForgeHost.PostFormAsync(client, "/settings/tokens", "revoke-token", new() { ["TokenId"] = row.Id.ToString() });
510 Assert.False(await host.WithScopeAsync(sp => sp.GetRequiredService<ForgeDb>().AccessTokens.AnyAsync(t => t.Id == row.Id)));
511 Assert.False((await host.Git.RunAsync(work, "push", host.GitUrl("jessie", repo.Name, plaintext), "main", "--force")).Ok);
512 }
513
514 [Fact]
515 public async Task Rename_does_not_touch_the_directory()
516 {
517 var user = await host.CreateUserAsync();
518 var repo = await host.CreateRepoAsync(user, "before-rename", Visibility.Private);
519 var directory = host.RepoDirectory(repo.Id);
520 var created = Directory.GetCreationTimeUtc(directory);
521
522 var error = await host.WithScopeAsync(async sp =>
523 {
524 var service = sp.GetRequiredService<RepoService>();
525 var tracked = await service.FindAsync("jessie", "before-rename");
526 return await service.RenameAsync(tracked!, "after-rename");
527 });
528
529 Assert.Null(error);
530 Assert.True(Directory.Exists(directory));
531 Assert.Equal(created, Directory.GetCreationTimeUtc(directory));
532 Assert.Equal([directory], Directory.GetDirectories(Path.GetDirectoryName(directory)!, repo.Id + ".git"));
533 }
534 }
535
536 /// <summary>First-run setup needs an empty database, so it gets a host of its own.</summary>
537 public class SetupTests(ForgeHost host) : IClassFixture<ForgeHost>
538 {
539 [Fact]
540 public async Task Setup_creates_the_first_account_and_then_closes_for_good()
541 {
542 using var client = host.CreateClient();
543
544 // With no account, the home page leads to setup.
545 var home = await client.GetAsync("/");
546 Assert.Equal("/setup", home.Headers.Location?.PathAndQuery);
547 Assert.True(File.Exists(Path.Combine(host.DataPath, "forge.db")));
548 Assert.True(Directory.Exists(Path.Combine(host.DataPath, "repos")));
549
550 var mismatch = await ForgeHost.PostFormAsync(client, "/setup", "setup", new()
551 {
552 ["Username"] = "jessie",
553 ["Password"] = ForgeHost.Password,
554 ["PasswordRepeat"] = "something else",
555 });
556 Assert.Contains("do not match", await ForgeHost.TextAsync(mismatch));
557
558 var reserved = await ForgeHost.PostFormAsync(client, "/setup", "setup", new()
559 {
560 ["Username"] = "settings",
561 ["Password"] = ForgeHost.Password,
562 ["PasswordRepeat"] = ForgeHost.Password,
563 });
564 Assert.Contains("reserved", await ForgeHost.TextAsync(reserved));
565
566 var created = await ForgeHost.PostFormAsync(client, "/setup", "setup", new()
567 {
568 ["Username"] = "jessie",
569 ["DisplayName"] = "Jessie",
570 ["Password"] = ForgeHost.Password,
571 ["PasswordRepeat"] = ForgeHost.Password,
572 });
573 Assert.Equal(HttpStatusCode.Redirect, created.StatusCode);
574 Assert.Equal("/", created.Headers.Location?.PathAndQuery);
575
576 // Setup signed the new user in.
577 var signedIn = await client.GetStringAsync("/");
578 Assert.Contains("Sign out (jessie)", signedIn);
579
580 // The password is stored hashed.
581 var user = await host.WithScopeAsync(sp => sp.GetRequiredService<ForgeDb>().Users.SingleAsync());
582 Assert.DoesNotContain(ForgeHost.Password, user.PasswordHash);
583
584 // Setup is gone, for the signed-in user and for strangers, on GET and on POST.
585 using var stranger = host.CreateClient();
586 Assert.Equal(HttpStatusCode.NotFound, (await client.GetAsync("/setup")).StatusCode);
587 Assert.Equal(HttpStatusCode.NotFound, (await stranger.GetAsync("/setup")).StatusCode);
588 var loginPage = await stranger.GetAsync("/login");
589 var token = System.Text.RegularExpressions.Regex.Match(
590 await loginPage.Content.ReadAsStringAsync(), "name=\"__RequestVerificationToken\" value=\"([^\"]+)\"").Groups[1].Value;
591 var second = await stranger.PostAsync("/setup", new FormUrlEncodedContent(new Dictionary<string, string>
592 {
593 ["__RequestVerificationToken"] = token,
594 ["_handler"] = "setup",
595 ["Username"] = "intruder",
596 ["Password"] = ForgeHost.Password,
597 ["PasswordRepeat"] = ForgeHost.Password,
598 }));
599 // The page no longer renders a form, so the framework refuses the post (400) before any handler runs.
600 Assert.True(
601 second.StatusCode is HttpStatusCode.NotFound or HttpStatusCode.BadRequest,
602 $"POST /setup answered {(int)second.StatusCode}");
603 Assert.Equal(1, await host.WithScopeAsync(sp => sp.GetRequiredService<ForgeDb>().Users.CountAsync()));
604
605 // Logout ends the session; a wrong password does not start one; the right one does.
606 var page = await client.GetStringAsync("/");
607 var logoutToken = System.Text.RegularExpressions.Regex.Match(page, "name=\"__RequestVerificationToken\" value=\"([^\"]+)\"").Groups[1].Value;
608 var loggedOut = await client.PostAsync("/logout", new FormUrlEncodedContent(new Dictionary<string, string>
609 {
610 ["__RequestVerificationToken"] = logoutToken,
611 }));
612 Assert.Equal(HttpStatusCode.Redirect, loggedOut.StatusCode);
613 Assert.Contains("Sign in", await client.GetStringAsync("/"));
614
615 var wrong = await ForgeHost.PostFormAsync(client, "/login", "login", new() { ["Username"] = "jessie", ["Password"] = "wrong password" });
616 Assert.Equal(HttpStatusCode.OK, wrong.StatusCode);
617 Assert.Contains("Wrong username or password", await ForgeHost.TextAsync(wrong));
618
619 var right = await ForgeHost.PostFormAsync(client, "/login?returnUrl=%2Fnew", "login", new() { ["Username"] = "JESSIE", ["Password"] = ForgeHost.Password });
620 Assert.Equal("/new", right.Headers.Location?.PathAndQuery);
621
622 // An off-site return URL is ignored.
623 using var other = host.CreateClient();
624 var offsite = await ForgeHost.PostFormAsync(other, "/login?returnUrl=%2F%2Fevil.example", "login", new() { ["Username"] = "jessie", ["Password"] = ForgeHost.Password });
625 Assert.Equal("/", offsite.Headers.Location?.PathAndQuery);
626 }
627 }
628
629 /// <summary>The login limiter is per client address, so this needs a host nobody else is logging in to.</summary>
630 public class RateLimitTests(ForgeHost host) : IClassFixture<ForgeHost>
631 {
632 [Fact]
633 public async Task Login_attempts_are_rate_limited()
634 {
635 await host.CreateUserAsync();
636 using var client = host.CreateClient();
637
638 var statuses = new List<HttpStatusCode>();
639 for (var i = 0; i < 12; i++)
640 {
641 var response = await ForgeHost.PostFormAsync(client, "/login", "login", new() { ["Username"] = "jessie", ["Password"] = "guess " + i });
642 statuses.Add(response.StatusCode);
643 }
644
645 Assert.All(statuses.Take(10), s => Assert.Equal(HttpStatusCode.OK, s));
646 Assert.Contains(HttpStatusCode.TooManyRequests, statuses.Skip(10));
647 // Reading the login page is still possible.
648 Assert.Equal(HttpStatusCode.OK, (await client.GetAsync("/login")).StatusCode);
649 }
650 }
added forge.Tests/WebhookTests.cs +199 −0View file
@@ -0,0 +1,199 @@
1 using System.Collections.Concurrent;
2 using System.Net;
3 using System.Text.Json;
4 using Forge.Data;
5 using Forge.Features.Webhooks;
6 using Forge.Tests.Support;
7 using Microsoft.EntityFrameworkCore;
8 using Microsoft.Extensions.DependencyInjection;
9
10 namespace Forge.Tests;
11
12 public class WebhookTests(ForgeHost host) : IClassFixture<ForgeHost>
13 {
14 private sealed record Received(string Event, string Delivery, string Signature, byte[] Body);
15
16 /// <summary>A local HTTP endpoint standing in for a CI server. Answers with whatever status the test queues.</summary>
17 private sealed class Receiver : IAsyncDisposable
18 {
19 private readonly WebApplication _app;
20
21 public ConcurrentQueue<Received> Requests { get; } = new();
22 public ConcurrentQueue<int> Statuses { get; } = new();
23 public string Url { get; }
24
25 private Receiver(WebApplication app)
26 {
27 _app = app;
28 Url = app.Urls.First().TrimEnd('/') + "/hook";
29 }
30
31 public static async Task<Receiver> StartAsync()
32 {
33 var builder = WebApplication.CreateBuilder(["--urls=http://127.0.0.1:0", "--Logging:LogLevel:Default=Warning"]);
34 var app = builder.Build();
35 Receiver? self = null;
36 app.MapPost("/hook", async (HttpContext context) =>
37 {
38 using var body = new MemoryStream();
39 await context.Request.Body.CopyToAsync(body);
40 self!.Requests.Enqueue(new Received(
41 context.Request.Headers["X-Forge-Event"].ToString(),
42 context.Request.Headers["X-Forge-Delivery"].ToString(),
43 context.Request.Headers["X-Forge-Signature"].ToString(),
44 body.ToArray()));
45 return Results.StatusCode(self.Statuses.TryDequeue(out var status) ? status : 200);
46 });
47 await app.StartAsync();
48 self = new Receiver(app);
49 return self;
50 }
51
52 public async Task<Received> NextAsync(int count = 1)
53 {
54 var deadline = DateTime.UtcNow.AddSeconds(30);
55 while (Requests.Count < count)
56 {
57 Assert.True(DateTime.UtcNow < deadline, $"Expected {count} webhook request(s), got {Requests.Count}.");
58 await Task.Delay(50);
59 }
60
61 return Requests.ElementAt(count - 1);
62 }
63
64 public async ValueTask DisposeAsync()
65 {
66 await _app.StopAsync();
67 await _app.DisposeAsync();
68 }
69 }
70
71 private Task<List<WebhookDelivery>> DeliveriesAsync(long webhookId) =>
72 host.WithScopeAsync(sp => sp.GetRequiredService<ForgeDb>().WebhookDeliveries
73 .Where(d => d.WebhookId == webhookId).OrderBy(d => d.Id).ToListAsync());
74
75 private async Task<List<WebhookDelivery>> WaitForDeliveriesAsync(long webhookId, Func<List<WebhookDelivery>, bool> done)
76 {
77 var deadline = DateTime.UtcNow.AddSeconds(30);
78 while (true)
79 {
80 var rows = await DeliveriesAsync(webhookId);
81 if (done(rows))
82 {
83 return rows;
84 }
85
86 Assert.True(DateTime.UtcNow < deadline, $"Deliveries did not reach the expected state; have {rows.Count}.");
87 await Task.Delay(50);
88 }
89 }
90
91 [Fact]
92 public async Task Push_sends_a_signed_payload_and_failures_are_retried()
93 {
94 WebhookWorker.RetryDelays = [TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(100)];
95 await using var receiver = await Receiver.StartAsync();
96 var user = await host.CreateUserAsync();
97 var repo = await host.CreateRepoAsync(user, "hooked", Visibility.Public);
98 var token = await host.CreateTokenAsync(user, canWrite: true);
99 using var client = await host.CreateSignedInClientAsync();
100
101 // Add the webhook through the UI.
102 var added = await ForgeHost.PostFormAsync(client, "/jessie/hooked/settings/webhooks", "add-webhook", new()
103 {
104 ["Url"] = receiver.Url,
105 ["Secret"] = "s3cret",
106 });
107 Assert.Equal(HttpStatusCode.Redirect, added.StatusCode);
108 var hook = await host.WithScopeAsync(sp => sp.GetRequiredService<ForgeDb>().Webhooks.SingleAsync(w => w.RepoId == repo.Id));
109 var detailUrl = $"/jessie/hooked/settings/webhooks/{hook.Id}";
110
111 // Test ping.
112 var pinged = await ForgeHost.PostFormAsync(client, detailUrl, "hook-action", new() { ["Action"] = "ping" });
113 Assert.Contains("The ping was delivered", await ForgeHost.TextAsync(pinged));
114 var ping = await receiver.NextAsync(1);
115 Assert.Equal("ping", ping.Event);
116 Assert.Equal(WebhookSender.Sign("s3cret", ping.Body), ping.Signature);
117
118 // A push: the first attempt fails with 500, the retry succeeds.
119 receiver.Statuses.Enqueue(500);
120 var work = host.NewDir("work");
121 var sha = await host.Git.CreateWorkRepoAsync(work);
122 await host.Git.MustAsync(work, "push", host.GitUrl("jessie", "hooked", token), "main");
123
124 var retried = await receiver.NextAsync(3);
125 Assert.Equal("push", retried.Event);
126 Assert.Equal(WebhookSender.Sign("s3cret", retried.Body), retried.Signature);
127 Assert.StartsWith("sha256=", retried.Signature);
128
129 using var payload = JsonDocument.Parse(retried.Body);
130 var root = payload.RootElement;
131 Assert.Equal("refs/heads/main", root.GetProperty("ref").GetString());
132 Assert.Equal(Git.GitParsers.ZeroSha, root.GetProperty("before").GetString());
133 Assert.Equal(sha, root.GetProperty("after").GetString());
134 Assert.Equal("jessie/hooked", root.GetProperty("repository").GetProperty("full_name").GetString());
135 Assert.Equal("http://forge.test/jessie/hooked.git", root.GetProperty("repository").GetProperty("clone_url").GetString());
136 Assert.StartsWith("http://forge.test/jessie/hooked/", root.GetProperty("compare").GetString());
137 var commit = Assert.Single(root.GetProperty("commits").EnumerateArray());
138 Assert.Equal(sha, commit.GetProperty("id").GetString());
139 Assert.Equal("First commit", commit.GetProperty("message").GetString());
140
141 // Every attempt is a row: ping, failed push, successful retry.
142 var rows = await WaitForDeliveriesAsync(hook.Id, r => r.Count(d => d.PushEventId != null && d.StatusCode != null) == 2);
143 var pushRows = rows.Where(d => d.PushEventId != null).ToList();
144 Assert.Equal([(1, 500), (2, 200)], pushRows.Select(d => (d.Attempt, d.StatusCode!.Value)));
145 Assert.Equal(retried.Delivery, pushRows[1].Id.ToString());
146 Assert.Null(rows[0].PushEventId);
147 Assert.Equal(200, rows[0].StatusCode);
148
149 // The history page lists them, and Redeliver sends the event again.
150 var history = await client.GetStringAsync(detailUrl);
151 Assert.Contains("refs/heads/main", history);
152 var redelivered = await ForgeHost.PostFormAsync(client, detailUrl, "redeliver", new() { ["DeliveryId"] = pushRows[0].Id.ToString() });
153 Assert.Contains("Delivered again", await ForgeHost.TextAsync(redelivered));
154 var again = await receiver.NextAsync(4);
155 Assert.Equal(retried.Body, again.Body);
156 Assert.Equal(3, (await DeliveriesAsync(hook.Id)).Last().Attempt);
157
158 // A disabled webhook receives nothing.
159 await ForgeHost.PostFormAsync(client, detailUrl, "hook-action", new() { ["Action"] = "toggle" });
160 await File.WriteAllTextAsync(Path.Combine(work, "more.txt"), "more\n");
161 await host.Git.MustAsync(work, "add", "-A");
162 await host.Git.MustAsync(work, "commit", "-m", "More");
163 await host.Git.MustAsync(work, "push", host.GitUrl("jessie", "hooked", token), "main");
164 await Task.Delay(500);
165 Assert.Equal(4, receiver.Requests.Count);
166
167 // Deleting the repository removes its webhooks and deliveries with it.
168 await host.WithScopeAsync(async sp =>
169 {
170 var service = sp.GetRequiredService<Features.Repos.RepoService>();
171 await service.DeleteAsync((await service.FindAsync("jessie", "hooked"))!);
172 return 0;
173 });
174 Assert.Empty(await DeliveriesAsync(hook.Id));
175 }
176
177 [Fact]
178 public async Task Unreachable_receiver_is_recorded_as_a_failed_delivery()
179 {
180 var user = await host.CreateUserAsync();
181 var repo = await host.CreateRepoAsync(user, "unreachable", Visibility.Public);
182 var hook = await host.WithScopeAsync(async sp =>
183 {
184 var db = sp.GetRequiredService<ForgeDb>();
185 // Port 9 (discard) on localhost: nothing listens there.
186 var row = new Webhook { RepoId = repo.Id, Url = "http://127.0.0.1:9/hook", Secret = "x", CreatedAt = DateTime.UtcNow };
187 db.Webhooks.Add(row);
188 await db.SaveChangesAsync();
189 return row;
190 });
191
192 var ok = await host.Services.GetRequiredService<WebhookSender>().DeliverAsync(hook.Id, null, 1);
193
194 Assert.False(ok);
195 var delivery = Assert.Single(await DeliveriesAsync(hook.Id));
196 Assert.Null(delivery.StatusCode);
197 Assert.False(string.IsNullOrEmpty(delivery.Error));
198 }
199 }
added forge.Tests/forge.Tests.csproj +29 −0View file
@@ -0,0 +1,29 @@
1 <Project Sdk="Microsoft.NET.Sdk">
2
3 <PropertyGroup>
4 <TargetFramework>net11.0</TargetFramework>
5 <Nullable>enable</Nullable>
6 <ImplicitUsings>enable</ImplicitUsings>
7 <IsPackable>false</IsPackable>
8 <RootNamespace>Forge.Tests</RootNamespace>
9 </PropertyGroup>
10
11 <ItemGroup>
12 <FrameworkReference Include="Microsoft.AspNetCore.App" />
13 <PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.12.0" />
14 <PackageReference Include="xunit" Version="2.9.3" />
15 <PackageReference Include="xunit.runner.visualstudio" Version="3.1.5" />
16 </ItemGroup>
17
18 <ItemGroup>
19 <ProjectReference Include="..\forge\forge.csproj" />
20 </ItemGroup>
21
22 <ItemGroup>
23 <Using Include="Xunit" />
24 <Using Include="Microsoft.AspNetCore.Builder" />
25 <Using Include="Microsoft.AspNetCore.Http" />
26 <Using Include="Microsoft.Extensions.Hosting" />
27 </ItemGroup>
28
29 </Project>
added forge.slnx +4 −0View file
@@ -0,0 +1,4 @@
1 <Solution>
2 <Project Path="forge/forge.csproj" />
3 <Project Path="forge.Tests/forge.Tests.csproj" />
4 </Solution>
added forge/Components/App.razor +25 −0View file
@@ -0,0 +1,25 @@
1 <!DOCTYPE html>
2 <html lang="@T.Language">
3
4 <head>
5 <meta charset="utf-8"/>
6 <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
7 <meta name="color-scheme" content="light dark"/>
8 <script src="/theme.js?v=@AssetVersion"></script>
9 <link rel="stylesheet" href="/style.css?v=@AssetVersion"/>
10 <link rel="icon" type="image/png" href="/favicon.png"/>
11 <HeadOutlet/>
12 </head>
13
14 <body>
15 <Routes/>
16 <script src="/app.js?v=@AssetVersion" defer></script>
17 </body>
18
19 </html>
20
21 @code {
22 /// <summary>Changes with every build, so browsers pick up new CSS and JS.</summary>
23 public static readonly string AssetVersion =
24 typeof(App).Assembly.ManifestModule.ModuleVersionId.ToString("N")[..8];
25 }
added forge/Components/Avatar.razor +32 −0View file
@@ -0,0 +1,32 @@
1 @* A generated avatar: the first letter on one of eight colours, picked from the name so it never changes. *@
2 <span class="avatar avatar-@Size avatar-c@(ColorIndex(Name))" aria-hidden="true">@Initial</span>
3
4 @code {
5 [Parameter, EditorRequired]
6 public string Name { get; set; } = "";
7
8 /// <summary>sm (20px), md (28px) or lg (72px).</summary>
9 [Parameter]
10 public string Size { get; set; } = "sm";
11
12 private string Initial
13 {
14 get
15 {
16 var trimmed = Name.Trim();
17 return trimmed.Length == 0 ? "?" : System.Globalization.StringInfo.GetNextTextElement(trimmed).ToUpperInvariant();
18 }
19 }
20
21 /// <summary>A stable hash (string.GetHashCode differs between runs).</summary>
22 public static int ColorIndex(string name)
23 {
24 var hash = 2166136261u;
25 foreach (var c in name.Trim().ToLowerInvariant())
26 {
27 hash = (hash ^ c) * 16777619u;
28 }
29
30 return (int)(hash % 8);
31 }
32 }
added forge/Components/Breadcrumbs.razor +29 −0View file
@@ -0,0 +1,29 @@
1 <nav class="breadcrumbs" aria-label="@T["Path"]">
2 <a href="@Urls.Tree(Repository, RefName)">@Repository.Name</a>
3 @for (var i = 0; i < Segments.Length; i++)
4 {
5 var upTo = string.Join('/', Segments, 0, i + 1);
6 <span class="sep">/</span>
7 @if (i == Segments.Length - 1)
8 {
9 <strong>@Segments[i]</strong>
10 }
11 else
12 {
13 <a href="@Urls.Tree(Repository, RefName, upTo)">@Segments[i]</a>
14 }
15 }
16 </nav>
17
18 @code {
19 [Parameter, EditorRequired]
20 public Repository Repository { get; set; } = null!;
21
22 [Parameter, EditorRequired]
23 public string RefName { get; set; } = "";
24
25 [Parameter]
26 public string Path { get; set; } = "";
27
28 private string[] Segments => Path.Length == 0 ? [] : Path.Split('/');
29 }
added forge/Components/CloneBox.razor +22 −0View file
@@ -0,0 +1,22 @@
1 @* The "Clone" dropdown. A <details> element, so it opens without script; only the copy button needs it. *@
2 <details class="menu clone-menu">
3 <summary class="button">
4 <Icon Name="download"/> @T["Clone"] <Icon Name="chevron-down" Size="14"/>
5 </summary>
6 <div class="menu-panel menu-right clone-panel">
7 <p class="clone-title"><Icon Name="link" Size="14"/> @T["Clone over HTTP"]</p>
8 <div class="clone-box">
9 <input type="text" readonly value="@Url" aria-label="@T["Clone URL"]" class="clone-url"/>
10 <button type="button" class="button js-only" data-copy="@Url" data-copied-label="@T["Copied"]"
11 title="@T["Copy"]" aria-label="@T["Copy"]">
12 <Icon Name="copy"/>
13 </button>
14 </div>
15 <p class="muted small clone-hint">@T["Use an access token as the password."]</p>
16 </div>
17 </details>
18
19 @code {
20 [Parameter, EditorRequired]
21 public string Url { get; set; } = "";
22 }
added forge/Components/CommitList.razor +55 −0View file
@@ -0,0 +1,55 @@
1 @foreach (var group in Groups)
2 {
3 @if (GroupByDay)
4 {
5 <h3 class="commit-day">
6 <Icon Name="commit"/> @T["Commits on {0}", group.Key.ToString("d MMMM yyyy", CultureInfo.CurrentCulture)]
7 </h3>
8 }
9 <ul class="commit-list">
10 @foreach (var c in group)
11 {
12 <li class="commit-row">
13 <div class="commit-main">
14 <a class="commit-subject" href="@Urls.Commit(Repository, c.Sha)">@(c.Subject.Length == 0 ? T["(no message)"] : c.Subject)</a>
15 <div class="muted small commit-byline">
16 <Avatar Name="@c.AuthorName"/>
17 <span>@c.AuthorName</span>
18 <span class="sep">·</span>
19 <TimeAgo Value="c.AuthorDate"/>
20 </div>
21 </div>
22 <div class="commit-actions">
23 <span class="button-group">
24 <a class="button small sha" href="@Urls.Commit(Repository, c.Sha)">@c.ShortSha</a>
25 <button type="button" class="button small js-only" data-copy="@c.Sha"
26 title="@T["Copy the full SHA"]" aria-label="@T["Copy the full SHA"]">
27 <Icon Name="copy" Size="14"/>
28 </button>
29 </span>
30 <a class="button small" href="@Urls.Tree(Repository, c.Sha)"
31 title="@T["Browse files at this commit"]" aria-label="@T["Browse files at this commit"]">
32 <Icon Name="code" Size="14"/>
33 </a>
34 </div>
35 </li>
36 }
37 </ul>
38 }
39
40 @code {
41 [Parameter, EditorRequired]
42 public Repository Repository { get; set; } = null!;
43
44 [Parameter, EditorRequired]
45 public IReadOnlyList<CommitInfo> Commits { get; set; } = [];
46
47 /// <summary>Puts a date heading above the commits of each day (in the author's time zone).</summary>
48 [Parameter]
49 public bool GroupByDay { get; set; }
50
51 private IEnumerable<IGrouping<DateTime, CommitInfo>> Groups =>
52 GroupByDay
53 ? Commits.GroupBy(c => c.AuthorDate.Date)
54 : Commits.GroupBy(_ => DateTime.MinValue);
55 }
added forge/Components/Counter.razor +10 −0View file
@@ -0,0 +1,10 @@
1 @* A small count next to a tab label. Zero shows nothing. *@
2 @if (Value > 0)
3 {
4 <span class="counter">@Value.ToString("N0", CultureInfo.CurrentCulture)</span>
5 }
6
7 @code {
8 [Parameter]
9 public int Value { get; set; }
10 }
added forge/Components/Error.razor +5 −0View file
@@ -0,0 +1,5 @@
1 @page "/error"
2
3 <PageTitle>@T["Error"] · Forge</PageTitle>
4
5 <StatusMessage Code="500"/>
added forge/Components/HighlightAssets.razor +7 −0View file
@@ -0,0 +1,7 @@
1 @* Loads highlight.js from this server. Use on pages that show code; a page can have only one HeadContent.
2 app.js switches the two stylesheets when the visitor picks a theme by hand (data-hl-theme). *@
3 <HeadContent>
4 <link rel="stylesheet" href="/lib/highlight/github.min.css" media="(prefers-color-scheme: light)" data-hl-theme="light"/>
5 <link rel="stylesheet" href="/lib/highlight/github-dark.min.css" media="(prefers-color-scheme: dark)" data-hl-theme="dark"/>
6 <script src="/lib/highlight/highlight.min.js" defer></script>
7 </HeadContent>
added forge/Components/Highlighted.razor +40 −0View file
@@ -0,0 +1,40 @@
1 @* Text with every occurrence of a search term marked. Case-insensitive.
2 Built as one string so that no whitespace is added or lost inside preformatted code. *@
3 @((MarkupString)Render(Text, Term))
4
5 @code {
6 [Parameter, EditorRequired]
7 public string Text { get; set; } = "";
8
9 [Parameter, EditorRequired]
10 public string Term { get; set; } = "";
11
12 /// <summary>HTML for <paramref name="text"/>: every part is encoded, matches are wrapped in &lt;mark&gt;.</summary>
13 public static string Render(string text, string term)
14 {
15 var encode = System.Text.Encodings.Web.HtmlEncoder.Default;
16 if (term.Length == 0)
17 {
18 return encode.Encode(text);
19 }
20
21 var html = new System.Text.StringBuilder(text.Length + 32);
22 var position = 0;
23 while (position < text.Length)
24 {
25 var found = text.IndexOf(term, position, StringComparison.OrdinalIgnoreCase);
26 if (found < 0)
27 {
28 break;
29 }
30
31 html.Append(encode.Encode(text[position..found]))
32 .Append("<mark>")
33 .Append(encode.Encode(text.Substring(found, term.Length)))
34 .Append("</mark>");
35 position = found + term.Length;
36 }
37
38 return html.Append(encode.Encode(text[position..])).ToString();
39 }
40 }
added forge/Components/Icon.razor +59 −0View file
@@ -0,0 +1,59 @@
1 @* Inline SVG icons (24×24 grid, drawn with the text colour). Inline because the CSP allows no external sprite tricks and no inline style. *@
2 <svg class="@CssClass" viewBox="0 0 24 24" width="@Size" height="@Size" aria-hidden="true" focusable="false">@((MarkupString)Shapes.GetValueOrDefault(Name, ""))</svg>
3
4 @code {
5 [Parameter, EditorRequired]
6 public string Name { get; set; } = "";
7
8 [Parameter]
9 public int Size { get; set; } = 16;
10
11 [Parameter]
12 public string? Class { get; set; }
13
14 private string CssClass => Class is null ? "icon" : "icon " + Class;
15
16 private static readonly Dictionary<string, string> Shapes = new(StringComparer.Ordinal)
17 {
18 // An anvil. Used filled (class "logo-mark").
19 ["logo"] = "<path d=\"M2 6h13c2.6 0 4.6-1 6.5-3 0 5-3 8.5-7.5 8.5h-1V16h3.5v4h-12v-4H8v-4.5C5 11.5 2.6 9.3 2 6Z\"/>",
20 ["folder"] = "<path d=\"M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.93a2 2 0 0 1-1.66-.9l-.82-1.2A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13c0 1.1.9 2 2 2Z\"/>",
21 ["file"] = "<path d=\"M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z\"/><path d=\"M14 2v6h6\"/>",
22 ["code"] = "<path d=\"m16 18 6-6-6-6\"/><path d=\"m8 6-6 6 6 6\"/>",
23 ["commit"] = "<circle cx=\"12\" cy=\"12\" r=\"3\"/><path d=\"M3 12h6\"/><path d=\"M15 12h6\"/>",
24 ["branch"] = "<path d=\"M6 3v12\"/><circle cx=\"18\" cy=\"6\" r=\"3\"/><circle cx=\"6\" cy=\"18\" r=\"3\"/><path d=\"M18 9a9 9 0 0 1-9 9\"/>",
25 ["tag"] = "<path d=\"M12 2H2v10l9.29 9.29c.94.94 2.48.94 3.42 0l6.58-6.58c.94-.94.94-2.48 0-3.42L12 2Z\"/><path d=\"M7 7h.01\"/>",
26 ["pull"] = "<circle cx=\"18\" cy=\"18\" r=\"3\"/><circle cx=\"6\" cy=\"6\" r=\"3\"/><path d=\"M13 6h3a2 2 0 0 1 2 2v7\"/><path d=\"M6 9v12\"/>",
27 ["merge"] = "<circle cx=\"18\" cy=\"18\" r=\"3\"/><circle cx=\"6\" cy=\"6\" r=\"3\"/><path d=\"M6 21V9a9 9 0 0 0 9 9\"/>",
28 ["settings"] = "<path d=\"M4 21v-7\"/><path d=\"M4 10V3\"/><path d=\"M12 21v-9\"/><path d=\"M12 8V3\"/><path d=\"M20 21v-5\"/><path d=\"M20 12V3\"/><path d=\"M1 14h6\"/><path d=\"M9 8h6\"/><path d=\"M17 16h6\"/>",
29 ["search"] = "<circle cx=\"11\" cy=\"11\" r=\"8\"/><path d=\"m21 21-4.3-4.3\"/>",
30 ["plus"] = "<path d=\"M5 12h14\"/><path d=\"M12 5v14\"/>",
31 ["lock"] = "<rect x=\"3\" y=\"11\" width=\"18\" height=\"11\" rx=\"2\"/><path d=\"M7 11V7a5 5 0 0 1 10 0v4\"/>",
32 ["globe"] = "<circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M2 12h20\"/><path d=\"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z\"/>",
33 ["copy"] = "<rect x=\"9\" y=\"9\" width=\"13\" height=\"13\" rx=\"2\"/><path d=\"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1\"/>",
34 ["check"] = "<path d=\"M20 6 9 17l-5-5\"/>",
35 ["sun"] = "<circle cx=\"12\" cy=\"12\" r=\"4\"/><path d=\"M12 1v2\"/><path d=\"M12 21v2\"/><path d=\"m4.22 4.22 1.42 1.42\"/><path d=\"m18.36 18.36 1.42 1.42\"/><path d=\"M1 12h2\"/><path d=\"M21 12h2\"/><path d=\"m4.22 19.78 1.42-1.42\"/><path d=\"m18.36 5.64 1.42-1.42\"/>",
36 ["moon"] = "<path d=\"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z\"/>",
37 ["monitor"] = "<rect x=\"2\" y=\"3\" width=\"20\" height=\"14\" rx=\"2\"/><path d=\"M8 21h8\"/><path d=\"M12 17v4\"/>",
38 ["chevron-down"] = "<path d=\"m6 9 6 6 6-6\"/>",
39 ["history"] = "<circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M12 6v6l4 2\"/>",
40 ["key"] = "<circle cx=\"7.5\" cy=\"15.5\" r=\"5.5\"/><path d=\"m21 2-9.6 9.6\"/><path d=\"m15.5 7.5 3 3L22 7l-3-3\"/>",
41 ["sign-out"] = "<path d=\"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4\"/><path d=\"m16 17 5-5-5-5\"/><path d=\"M21 12H9\"/>",
42 ["book"] = "<path d=\"M4 19.5A2.5 2.5 0 0 1 6.5 17H20\"/><path d=\"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z\"/>",
43 ["package"] = "<path d=\"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z\"/><path d=\"M3.27 6.96 12 12.01l8.73-5.05\"/><path d=\"M12 22.08V12\"/>",
44 ["download"] = "<path d=\"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4\"/><path d=\"m7 10 5 5 5-5\"/><path d=\"M12 15V3\"/>",
45 ["rss"] = "<path d=\"M4 11a9 9 0 0 1 9 9\"/><path d=\"M4 4a16 16 0 0 1 16 16\"/><circle cx=\"5\" cy=\"19\" r=\"1\"/>",
46 ["zap"] = "<path d=\"M13 2 3 14h9l-1 8 10-12h-9l1-8z\"/>",
47 ["shield"] = "<path d=\"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z\"/>",
48 ["user"] = "<path d=\"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2\"/><circle cx=\"12\" cy=\"7\" r=\"4\"/>",
49 ["users"] = "<path d=\"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2\"/><circle cx=\"9\" cy=\"7\" r=\"4\"/><path d=\"M23 21v-2a4 4 0 0 0-3-3.87\"/><path d=\"M16 3.13a4 4 0 0 1 0 7.75\"/>",
50 ["link"] = "<path d=\"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71\"/><path d=\"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71\"/>",
51 ["activity"] = "<path d=\"M22 12h-4l-3 9L9 3l-3 9H2\"/>",
52 ["x"] = "<path d=\"M18 6 6 18\"/><path d=\"m6 6 12 12\"/>",
53 ["arrow-left"] = "<path d=\"M19 12H5\"/><path d=\"m12 19-7-7 7-7\"/>",
54 ["arrow-right"] = "<path d=\"M5 12h14\"/><path d=\"m12 5 7 7-7 7\"/>",
55 ["comment"] = "<path d=\"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z\"/>",
56 ["inbox"] = "<path d=\"M22 12h-6l-2 3h-4l-2-3H2\"/><path d=\"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z\"/>",
57 ["eye"] = "<path d=\"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z\"/><circle cx=\"12\" cy=\"12\" r=\"3\"/>",
58 };
59 }
added forge/Components/LanguageBar.razor +30 −0View file
@@ -0,0 +1,30 @@
1 @* Language shares as one stacked bar with a legend. Widths are SVG attributes because the CSP forbids inline style. *@
2 <svg class="lang-bar" viewBox="0 0 100 8" preserveAspectRatio="none" width="100%" height="8" role="img" aria-label="@T["Languages"]">
3 @{
4 var x = 0.0;
5 foreach (var share in Shares)
6 {
7 // A 0.4 gap between slices, so neighbouring colours do not run together.
8 var width = Math.Max(share.Percent - 0.4, 0.2);
9 <rect class="lang-@share.Key" x="@Number(x)" y="0" width="@Number(width)" height="8"/>
10 x += share.Percent;
11 }
12 }
13 </svg>
14 <ul class="lang-legend">
15 @foreach (var share in Shares)
16 {
17 <li>
18 <span class="lang-dot lang-@share.Key"></span>
19 <span>@(share.Name ?? T["Other"])</span>
20 <span class="muted">@share.Percent.ToString("0.0", CultureInfo.CurrentCulture) %</span>
21 </li>
22 }
23 </ul>
24
25 @code {
26 [Parameter, EditorRequired]
27 public IReadOnlyList<LanguageShare> Shares { get; set; } = [];
28
29 private static string Number(double value) => value.ToString("0.##", CultureInfo.InvariantCulture);
30 }
added forge/Components/MainLayout.razor +130 −0View file
@@ -0,0 +1,130 @@
1 @inherits LayoutComponentBase
2 @using Microsoft.AspNetCore.Diagnostics
3 @inject CurrentUser Me
4 @inject IHttpContextAccessor Http
5
6 <a class="skip-link" href="#main">@T["Skip to content"]</a>
7
8 <header class="topbar">
9 <div class="wrap topbar-inner">
10 <a class="brand" href="/">
11 <Icon Name="logo" Size="22" Class="logo-mark"/>
12 <span>Forge</span>
13 </a>
14
15 <form class="search" method="get" action="/" role="search">
16 <Icon Name="search" Size="15"/>
17 <input type="search" name="q" value="@Query" placeholder="@T["Search repositories"]"
18 aria-label="@T["Search repositories"]" autocomplete="off" data-hotkey="/"/>
19 <kbd class="js-only">/</kbd>
20 </form>
21
22 <nav class="topnav">
23 <button type="button" class="icon-button js-only" data-theme-toggle
24 title="@T["Switch theme"]" aria-label="@T["Switch theme"]">
25 <Icon Name="monitor" Size="17" Class="theme-icon theme-icon-auto"/>
26 <Icon Name="sun" Size="17" Class="theme-icon theme-icon-light"/>
27 <Icon Name="moon" Size="17" Class="theme-icon theme-icon-dark"/>
28 </button>
29 @if (Me.IsAuthenticated)
30 {
31 <a class="icon-button" href="/new" title="@T["New repository"]" aria-label="@T["New repository"]">
32 <Icon Name="plus" Size="18"/>
33 </a>
34 <details class="menu">
35 <summary class="menu-button" aria-label="@T["Account menu"]">
36 <Avatar Name="@(Me.Username ?? "")" Size="md"/>
37 <Icon Name="chevron-down" Size="14"/>
38 </summary>
39 <div class="menu-panel menu-right">
40 <p class="menu-header">@T["Signed in as"] <strong>@Me.Username</strong></p>
41 <a class="menu-item" href="@Urls.User(Me.Username!)"><Icon Name="book"/> @T["Your repositories"]</a>
42 <a class="menu-item" href="/new"><Icon Name="plus"/> @T["New repository"]</a>
43 <a class="menu-item" href="/settings/tokens"><Icon Name="key"/> @T["Access tokens"]</a>
44 <form method="post" action="/logout" class="menu-form">
45 <AntiforgeryToken/>
46 <button type="submit" class="menu-item"><Icon Name="sign-out"/> @T["Sign out ({0})", Me.Username]</button>
47 </form>
48 </div>
49 </details>
50 }
51 else
52 {
53 <a class="button small" href="/login">@T["Sign in"]</a>
54 }
55 </nav>
56 </div>
57 </header>
58
59 <main class="wrap" id="main">
60 @Body
61 </main>
62
63 <footer class="footer">
64 <div class="wrap footer-inner">
65 <span class="footer-brand muted">
66 <Icon Name="logo" Size="15" Class="logo-mark"/>
67 Forge · @T["self-hosted Git"]
68 <button type="button" class="link-button js-only footer-link" data-open-dialog="shortcuts">@T["Keyboard shortcuts"]</button>
69 </span>
70 <form method="post" action="/language" class="language-form">
71 <AntiforgeryToken/>
72 <input type="hidden" name="returnUrl" value="@ReturnUrl"/>
73 <span class="muted language-label"><Icon Name="globe" Size="14"/> @T["Language"]:</span>
74 @foreach (var language in T.Languages)
75 {
76 var name = CultureInfo.GetCultureInfo(language).NativeName;
77 @if (string.Equals(language, T.Language, StringComparison.OrdinalIgnoreCase))
78 {
79 <strong lang="@language">@name</strong>
80 }
81 else
82 {
83 <button type="submit" name="lang" value="@language" lang="@language" class="link-button">@name</button>
84 }
85 }
86 </form>
87 </div>
88 </footer>
89
90 @* Opened by the "?" key or the footer link (app.js). *@
91 <dialog class="dialog" id="shortcuts" aria-labelledby="shortcuts-title">
92 <h2 id="shortcuts-title">@T["Keyboard shortcuts"]</h2>
93 <dl class="shortcut-list">
94 <dt><kbd>/</kbd></dt>
95 <dd>@T["Search repositories"]</dd>
96 <dt><kbd>s</kbd></dt>
97 <dd>@T["Search file names and code"]</dd>
98 <dt><kbd>y</kbd></dt>
99 <dd>@T["Open the permalink of the file being viewed"]</dd>
100 <dt><kbd>?</kbd></dt>
101 <dd>@T["Show this help"]</dd>
102 </dl>
103 <form method="dialog">
104 <button type="submit" class="button">@T["Close"]</button>
105 </form>
106 </dialog>
107
108 @code {
109 /// <summary>The search box keeps what was searched for on the repository list.</summary>
110 private string? Query =>
111 Http.HttpContext is { } context && context.Request.Path == "/" ? context.Request.Query["q"].ToString() : null;
112
113 /// <summary>Where the language switcher returns to: the page the visitor asked for, even when an error page is shown instead.</summary>
114 private string ReturnUrl
115 {
116 get
117 {
118 var context = Http.HttpContext;
119 if (context is null)
120 {
121 return "/";
122 }
123
124 var original = context.Features.Get<IStatusCodeReExecuteFeature>();
125 return original is not null
126 ? original.OriginalPathBase + original.OriginalPath + original.OriginalQueryString
127 : context.Request.PathBase + context.Request.Path + context.Request.QueryString;
128 }
129 }
130 }
added forge/Components/NotFound.razor +5 −0View file
@@ -0,0 +1,5 @@
1 @page "/not-found"
2
3 <PageTitle>@T["Not found"] · Forge</PageTitle>
4
5 <StatusMessage Code="404"/>
added forge/Components/RefSwitcher.razor +53 −0View file
@@ -0,0 +1,53 @@
1 @* Branch and tag picker. A <details> element, so it needs no script. *@
2 <details class="ref-switcher">
3 <summary class="button">
4 <span class="muted">@KindLabel:</span>
5 <strong>@(CurrentKind == ResolvedKind.Commit && Current.Length > 8 ? Current[..8] : Current)</strong>
6 </summary>
7 <div class="ref-menu">
8 @if (Branches.Any())
9 {
10 <p class="ref-menu-title">@T["Branches"]</p>
11 @foreach (var r in Branches)
12 {
13 <a class="@ItemClass(r, ResolvedKind.Branch)" href="@UrlFor(r.Name)">@r.Name</a>
14 }
15 }
16 @if (Tags.Any())
17 {
18 <p class="ref-menu-title">@T["Tags"]</p>
19 @foreach (var r in Tags)
20 {
21 <a class="@ItemClass(r, ResolvedKind.Tag)" href="@UrlFor(r.Name)">@r.Name</a>
22 }
23 }
24 </div>
25 </details>
26
27 @code {
28 [Parameter, EditorRequired]
29 public IReadOnlyList<GitRef> Refs { get; set; } = [];
30
31 [Parameter, EditorRequired]
32 public string Current { get; set; } = "";
33
34 [Parameter]
35 public ResolvedKind CurrentKind { get; set; }
36
37 /// <summary>Builds the URL of the current view for another ref name.</summary>
38 [Parameter, EditorRequired]
39 public Func<string, string> UrlFor { get; set; } = null!;
40
41 private IEnumerable<GitRef> Branches => Refs.Where(r => r.Kind == RefKind.Branch);
42 private IEnumerable<GitRef> Tags => Refs.Where(r => r.Kind == RefKind.Tag);
43
44 private string KindLabel => CurrentKind switch
45 {
46 ResolvedKind.Tag => T["tag"],
47 ResolvedKind.Commit => T["commit"],
48 _ => T["branch"],
49 };
50
51 private string ItemClass(GitRef r, ResolvedKind kind) =>
52 kind == CurrentKind && r.Name == Current ? "ref-item active" : "ref-item";
53 }
added forge/Components/RepoHeader.razor +72 −0View file
@@ -0,0 +1,72 @@
1 @inject IOptions<ForgeOptions> Options
2 @inject GitRepo Git
3 @inject RepoPaths Paths
4 @inject IServiceScopeFactory Scopes
5
6 <div class="repo-head">
7 <h1 class="repo-title">
8 <Icon Name="@(IsPrivate ? "lock" : "book")" Size="20"/>
9 <a href="@Urls.User(Repository.Owner.Username)">@Repository.Owner.Username</a>
10 <span class="sep">/</span>
11 <a class="repo-name" href="@Urls.Repo(Repository)">@Repository.Name</a>
12 <span class="badge">@(IsPrivate ? T["private"] : T["public"])</span>
13 </h1>
14 @if (Repository.Description.Length > 0)
15 {
16 <p class="muted repo-description">@Repository.Description</p>
17 }
18 <div class="repo-bar">
19 <nav class="tabs">
20 <a class="@TabClass("code")" href="@Urls.Repo(Repository)"><Icon Name="code"/> @T["Code"]</a>
21 <a class="@TabClass("commits")" href="@Urls.Repo(Repository)/commits"><Icon Name="commit"/> @T["Commits"]</a>
22 <a class="@TabClass("branches")" href="@Urls.Branches(Repository)">
23 <Icon Name="branch"/> @T["Branches"] <Counter Value="_branches"/>
24 </a>
25 <a class="@TabClass("tags")" href="@Urls.Tags(Repository)">
26 <Icon Name="tag"/> @T["Tags"] <Counter Value="_tags"/>
27 </a>
28 <a class="@TabClass("pulls")" href="@Urls.Pulls(Repository)">
29 <Icon Name="pull"/> @T["Pull requests"] <Counter Value="_openPulls"/>
30 </a>
31 <a class="@TabClass("activity")" href="@Urls.Activity(Repository)"><Icon Name="activity"/> @T["Activity"]</a>
32 @if (IsOwner)
33 {
34 <a class="@TabClass("settings")" href="@Urls.Settings(Repository)"><Icon Name="settings"/> @T["Settings"]</a>
35 }
36 </nav>
37 <CloneBox Url="@Urls.Clone(Options.Value, Repository)"/>
38 </div>
39 </div>
40
41 @code {
42 [Parameter, EditorRequired]
43 public Repository Repository { get; set; } = null!;
44
45 /// <summary>code, commits, branches, tags, pulls or settings.</summary>
46 [Parameter]
47 public string Active { get; set; } = "";
48
49 [Parameter]
50 public bool IsOwner { get; set; }
51
52 private int _branches;
53 private int _tags;
54 private int _openPulls;
55
56 private bool IsPrivate => Repository.Visibility == Visibility.Private;
57
58 private string TabClass(string tab) => tab == Active ? "tab active" : "tab";
59
60 protected override async Task OnInitializedAsync()
61 {
62 var refs = await Git.ListRefsAsync(Paths.For(Repository.Id));
63 _branches = refs.Count(r => r.Kind == RefKind.Branch);
64 _tags = refs.Count(r => r.Kind == RefKind.Tag);
65
66 // A scope of its own: the page around this header may be using the request's DbContext right now.
67 await using var scope = Scopes.CreateAsyncScope();
68 var repoId = Repository.Id;
69 _openPulls = await scope.ServiceProvider.GetRequiredService<ForgeDb>().PullRequests
70 .CountAsync(p => p.RepoId == repoId && p.Status == PullRequestStatus.Open);
71 }
72 }
added forge/Components/RepoPageBase.cs +75 −0View file
@@ -0,0 +1,75 @@
1 using Forge.Data;
2 using Forge.Features.Auth;
3 using Forge.Features.Repos;
4 using Forge.Git;
5 using Microsoft.AspNetCore.Components;
6
7 namespace Forge.Components;
8
9 /// <summary>
10 /// Base for every page under /{owner}/{repo}. Loads the repository and applies access rules in one
11 /// place: a repository the visitor may not read answers exactly like one that does not exist.
12 /// </summary>
13 public abstract class RepoPageBase : ComponentBase
14 {
15 [Parameter]
16 public string Owner { get; set; } = "";
17
18 [Parameter]
19 public string Repo { get; set; } = "";
20
21 [Inject]
22 protected RepoService Repos { get; set; } = null!;
23
24 [Inject]
25 protected RepoPaths Paths { get; set; } = null!;
26
27 [Inject]
28 protected GitRepo Git { get; set; } = null!;
29
30 [Inject]
31 protected RefResolver Resolver { get; set; } = null!;
32
33 [Inject]
34 protected CurrentUser Me { get; set; } = null!;
35
36 [Inject]
37 protected NavigationManager Nav { get; set; } = null!;
38
39 /// <summary>Null until loaded, and null again when the page answered 404 or redirected. Markup must check it.</summary>
40 protected Repository? Repository { get; private set; }
41
42 protected string RepoPath { get; private set; } = "";
43
44 protected bool IsOwner { get; private set; }
45
46 /// <summary>Returns false after answering 404; the caller must stop.</summary>
47 protected async Task<bool> LoadRepoAsync(bool requireAdmin = false)
48 {
49 var repo = await Repos.FindAsync(Owner, Repo);
50 if (repo is null
51 || !RepoAccess.CanRead(repo, Me.Actor)
52 || (requireAdmin && !RepoAccess.CanAdmin(repo, Me.Actor)))
53 {
54 NotFound();
55 return false;
56 }
57
58 Repository = repo;
59 RepoPath = Paths.For(repo.Id);
60 IsOwner = RepoAccess.CanAdmin(repo, Me.Actor);
61 return true;
62 }
63
64 protected void NotFound()
65 {
66 Repository = null;
67 Nav.NotFound();
68 }
69
70 protected void Redirect(string url)
71 {
72 Repository = null;
73 Nav.NavigateTo(url);
74 }
75 }
added forge/Components/Routes.razor +5 −0View file
@@ -0,0 +1,5 @@
1 <Router AppAssembly="typeof(Program).Assembly" NotFoundPage="typeof(NotFound)">
2 <Found Context="routeData">
3 <RouteView RouteData="routeData" DefaultLayout="typeof(MainLayout)"/>
4 </Found>
5 </Router>
added forge/Components/StatusMessage.razor +27 −0View file
@@ -0,0 +1,27 @@
1 <section class="status-page">
2 <p class="status-code">@Code</p>
3 <h1>@Title</h1>
4 <p class="muted">@Detail</p>
5 <p class="status-action"><a class="button" href="/"><Icon Name="arrow-left"/> @T["Back to the repository list"]</a></p>
6 </section>
7
8 @code {
9 [Parameter]
10 public int Code { get; set; }
11
12 private string Title => Code switch
13 {
14 404 => T["This page does not exist"],
15 400 => T["The request could not be processed"],
16 429 => T["Too many attempts"],
17 _ => T["Something went wrong"],
18 };
19
20 private string Detail => Code switch
21 {
22 404 => T["The address is wrong, or you do not have access to this content."],
23 400 => T["The form may have expired. Reload the page and try again."],
24 429 => T["Wait a minute and try again."],
25 _ => T["Try again in a moment."],
26 };
27 }
added forge/Components/StatusPage.razor +11 −0View file
@@ -0,0 +1,11 @@
1 @page "/status/{Code:int}"
2
3 <PageTitle>@Code · Forge</PageTitle>
4
5 <StatusMessage Code="Code"/>
6
7 @code {
8 /// <summary>Target of UseStatusCodePagesWithReExecute: renders a page for a bare 4xx/5xx response.</summary>
9 [Parameter]
10 public int Code { get; set; }
11 }
added forge/Components/TimeAgo.razor +8 −0View file
@@ -0,0 +1,8 @@
1 @inject TimeProvider Clock
2
3 <time datetime="@Format.IsoTime(Value)" title="@Format.ExactTime(Value)">@T.RelativeTime(Value, Clock.GetUtcNow())</time>
4
5 @code {
6 [Parameter, EditorRequired]
7 public DateTimeOffset Value { get; set; }
8 }
added forge/Data/Entities.cs +154 −0View file
@@ -0,0 +1,154 @@
1 namespace Forge.Data;
2
3 public enum Visibility
4 {
5 Private = 0,
6 Public = 1,
7 }
8
9 public sealed class User
10 {
11 public long Id { get; set; }
12 public required string Username { get; set; }
13 public required string DisplayName { get; set; }
14 public string PasswordHash { get; set; } = "";
15 public DateTime CreatedAt { get; set; }
16 }
17
18 public sealed class Repository
19 {
20 public long Id { get; set; }
21 public long OwnerId { get; set; }
22 public User Owner { get; set; } = null!;
23 public required string Name { get; set; }
24 public string Description { get; set; } = "";
25 public Visibility Visibility { get; set; }
26 public string DefaultBranch { get; set; } = "main";
27 public DateTime CreatedAt { get; set; }
28 public DateTime? PushedAt { get; set; }
29 }
30
31 public sealed class AccessToken
32 {
33 public long Id { get; set; }
34 public long UserId { get; set; }
35 public User User { get; set; } = null!;
36 public required string Name { get; set; }
37
38 /// <summary>Lower-case hex SHA-256 of the token. The token itself is never stored.</summary>
39 public required string TokenHash { get; set; }
40
41 public bool CanWrite { get; set; }
42 public DateTime CreatedAt { get; set; }
43 public DateTime? LastUsedAt { get; set; }
44 public DateTime? ExpiresAt { get; set; }
45 }
46
47 public sealed class PushEvent
48 {
49 public long Id { get; set; }
50 public long RepoId { get; set; }
51 public Repository Repo { get; set; } = null!;
52 public required string RefName { get; set; }
53 public required string OldSha { get; set; }
54 public required string NewSha { get; set; }
55 public DateTime PushedAt { get; set; }
56 }
57
58 public sealed class Webhook
59 {
60 public long Id { get; set; }
61 public long RepoId { get; set; }
62 public Repository Repo { get; set; } = null!;
63 public required string Url { get; set; }
64 public required string Secret { get; set; }
65 public bool Active { get; set; } = true;
66 public DateTime CreatedAt { get; set; }
67 }
68
69 public sealed class WebhookDelivery
70 {
71 public long Id { get; set; }
72 public long WebhookId { get; set; }
73 public Webhook Webhook { get; set; } = null!;
74
75 /// <summary>Null for test pings, which have no push behind them.</summary>
76 public long? PushEventId { get; set; }
77
78 public PushEvent? PushEvent { get; set; }
79 public int? StatusCode { get; set; }
80 public int DurationMs { get; set; }
81 public string? Error { get; set; }
82 public int Attempt { get; set; }
83 public DateTime DeliveredAt { get; set; }
84
85 public bool Succeeded => StatusCode is >= 200 and < 300;
86 }
87
88 public enum PullRequestStatus
89 {
90 Open = 0,
91 Merged = 1,
92 Closed = 2,
93 }
94
95 /// <summary>A saved proposal to merge one branch of a repository into another.</summary>
96 public sealed class PullRequest
97 {
98 public long Id { get; set; }
99 public long RepoId { get; set; }
100 public Repository Repo { get; set; } = null!;
101
102 /// <summary>Counts from 1 within a repository; this is the number in the URL.</summary>
103 public int Number { get; set; }
104
105 public required string Title { get; set; }
106 public string Description { get; set; } = "";
107 public required string BaseBranch { get; set; }
108 public required string HeadBranch { get; set; }
109 public PullRequestStatus Status { get; set; }
110 public long AuthorId { get; set; }
111 public User Author { get; set; } = null!;
112 public DateTime CreatedAt { get; set; }
113 public DateTime UpdatedAt { get; set; }
114 public DateTime? ClosedAt { get; set; }
115
116 /// <summary>The commit the base branch pointed at right after the merge.</summary>
117 public string? MergeCommitSha { get; set; }
118
119 /// <summary>
120 /// Frozen when the pull request is merged or closed: where the branches diverged and the head's tip.
121 /// The page keeps showing the same commits and diff after the branches move on or are deleted.
122 /// </summary>
123 public string? BaseSha { get; set; }
124
125 public string? HeadSha { get; set; }
126 }
127
128 public sealed class PullRequestComment
129 {
130 public long Id { get; set; }
131 public long PullRequestId { get; set; }
132 public PullRequest PullRequest { get; set; } = null!;
133 public long AuthorId { get; set; }
134 public User Author { get; set; } = null!;
135 public required string Body { get; set; }
136 public DateTime CreatedAt { get; set; }
137 }
138
139 /// <summary>
140 /// Protects branches from force-pushes and deletion. <see cref="Pattern"/> is a branch name,
141 /// or a prefix ending in "/*" (release/*) covering every branch below it.
142 /// </summary>
143 public sealed class BranchProtection
144 {
145 public long Id { get; set; }
146 public long RepoId { get; set; }
147 public Repository Repo { get; set; } = null!;
148 public required string Pattern { get; set; }
149
150 /// <summary>Also refuse ordinary pushes: the branch then only changes through merges made in the web UI.</summary>
151 public bool BlockPush { get; set; }
152
153 public DateTime CreatedAt { get; set; }
154 }
added forge/Data/ForgeDb.cs +158 −0View file
@@ -0,0 +1,158 @@
1 using System.Data.Common;
2 using System.Text.RegularExpressions;
3 using Microsoft.EntityFrameworkCore;
4 using Microsoft.EntityFrameworkCore.Design;
5 using Microsoft.EntityFrameworkCore.Diagnostics;
6 using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
7
8 namespace Forge.Data;
9
10 public sealed partial class ForgeDb(DbContextOptions<ForgeDb> options) : DbContext(options)
11 {
12 public DbSet<User> Users => Set<User>();
13 public DbSet<Repository> Repositories => Set<Repository>();
14 public DbSet<AccessToken> AccessTokens => Set<AccessToken>();
15 public DbSet<PushEvent> PushEvents => Set<PushEvent>();
16 public DbSet<Webhook> Webhooks => Set<Webhook>();
17 public DbSet<WebhookDelivery> WebhookDeliveries => Set<WebhookDelivery>();
18 public DbSet<PullRequest> PullRequests => Set<PullRequest>();
19 public DbSet<PullRequestComment> PullRequestComments => Set<PullRequestComment>();
20 public DbSet<BranchProtection> BranchProtections => Set<BranchProtection>();
21
22 public static void Configure(DbContextOptionsBuilder builder, string databasePath) =>
23 builder
24 .UseSqlite($"Data Source={databasePath}")
25 .AddInterceptors(SqlitePragmaInterceptor.Instance);
26
27 protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
28 {
29 // SQLite has no date type: store UTC and hand UTC back.
30 configurationBuilder.Properties<DateTime>().HaveConversion<UtcDateTimeConverter>();
31 }
32
33 protected override void OnModelCreating(ModelBuilder b)
34 {
35 b.Entity<User>(e =>
36 {
37 e.ToTable("users");
38 e.Property(u => u.Username).UseCollation("NOCASE");
39 e.HasIndex(u => u.Username).IsUnique();
40 });
41
42 b.Entity<Repository>(e =>
43 {
44 e.ToTable("repositories");
45 e.Property(r => r.Name).UseCollation("NOCASE");
46 e.Property(r => r.Visibility).HasConversion<string>();
47 e.HasOne(r => r.Owner).WithMany().HasForeignKey(r => r.OwnerId).OnDelete(DeleteBehavior.Cascade);
48 e.HasIndex(r => new { r.OwnerId, r.Name }).IsUnique();
49 });
50
51 b.Entity<AccessToken>(e =>
52 {
53 e.ToTable("access_tokens");
54 e.HasOne(t => t.User).WithMany().HasForeignKey(t => t.UserId).OnDelete(DeleteBehavior.Cascade);
55 e.HasIndex(t => t.TokenHash).IsUnique();
56 });
57
58 b.Entity<PushEvent>(e =>
59 {
60 e.ToTable("push_events");
61 e.HasOne(p => p.Repo).WithMany().HasForeignKey(p => p.RepoId).OnDelete(DeleteBehavior.Cascade);
62 e.HasIndex(p => new { p.RepoId, p.PushedAt });
63 });
64
65 b.Entity<Webhook>(e =>
66 {
67 e.ToTable("webhooks");
68 e.HasOne(w => w.Repo).WithMany().HasForeignKey(w => w.RepoId).OnDelete(DeleteBehavior.Cascade);
69 });
70
71 b.Entity<WebhookDelivery>(e =>
72 {
73 e.ToTable("webhook_deliveries");
74 e.Ignore(d => d.Succeeded);
75 e.HasOne(d => d.Webhook).WithMany().HasForeignKey(d => d.WebhookId).OnDelete(DeleteBehavior.Cascade);
76 e.HasOne(d => d.PushEvent).WithMany().HasForeignKey(d => d.PushEventId).OnDelete(DeleteBehavior.Cascade);
77 e.HasIndex(d => new { d.WebhookId, d.PushEventId });
78 });
79
80 b.Entity<PullRequest>(e =>
81 {
82 e.ToTable("pull_requests");
83 e.Property(p => p.Status).HasConversion<string>();
84 e.HasOne(p => p.Repo).WithMany().HasForeignKey(p => p.RepoId).OnDelete(DeleteBehavior.Cascade);
85 e.HasOne(p => p.Author).WithMany().HasForeignKey(p => p.AuthorId).OnDelete(DeleteBehavior.Cascade);
86 e.HasIndex(p => new { p.RepoId, p.Number }).IsUnique();
87 });
88
89 b.Entity<PullRequestComment>(e =>
90 {
91 e.ToTable("pull_request_comments");
92 e.HasOne(c => c.PullRequest).WithMany().HasForeignKey(c => c.PullRequestId).OnDelete(DeleteBehavior.Cascade);
93 e.HasOne(c => c.Author).WithMany().HasForeignKey(c => c.AuthorId).OnDelete(DeleteBehavior.Cascade);
94 });
95
96 b.Entity<BranchProtection>(e =>
97 {
98 e.ToTable("branch_protections");
99 e.HasOne(p => p.Repo).WithMany().HasForeignKey(p => p.RepoId).OnDelete(DeleteBehavior.Cascade);
100 e.HasIndex(p => new { p.RepoId, p.Pattern }).IsUnique();
101 });
102
103 foreach (var entity in b.Model.GetEntityTypes())
104 {
105 foreach (var property in entity.GetProperties())
106 {
107 property.SetColumnName(SnakeCase(property.Name));
108 }
109 }
110 }
111
112 internal static string SnakeCase(string name) =>
113 UpperAfterLower().Replace(name, "_$1").ToLowerInvariant();
114
115 [GeneratedRegex("(?<=[a-z0-9])([A-Z])")]
116 private static partial Regex UpperAfterLower();
117 }
118
119 public sealed class UtcDateTimeConverter() : ValueConverter<DateTime, DateTime>(
120 v => v.Kind == DateTimeKind.Local ? v.ToUniversalTime() : v,
121 v => DateTime.SpecifyKind(v, DateTimeKind.Utc));
122
123 /// <summary>Applies the per-connection SQLite settings every time a connection is opened.</summary>
124 public sealed class SqlitePragmaInterceptor : DbConnectionInterceptor
125 {
126 public static readonly SqlitePragmaInterceptor Instance = new();
127
128 private const string Pragmas =
129 "PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;";
130
131 public override void ConnectionOpened(DbConnection connection, ConnectionEndEventData eventData)
132 {
133 using var command = connection.CreateCommand();
134 command.CommandText = Pragmas;
135 command.ExecuteNonQuery();
136 }
137
138 public override async Task ConnectionOpenedAsync(
139 DbConnection connection,
140 ConnectionEndEventData eventData,
141 CancellationToken cancellationToken = default)
142 {
143 await using var command = connection.CreateCommand();
144 command.CommandText = Pragmas;
145 await command.ExecuteNonQueryAsync(cancellationToken);
146 }
147 }
148
149 /// <summary>Lets `dotnet ef` build the context without starting the web app.</summary>
150 public sealed class ForgeDbDesignFactory : IDesignTimeDbContextFactory<ForgeDb>
151 {
152 public ForgeDb CreateDbContext(string[] args)
153 {
154 var builder = new DbContextOptionsBuilder<ForgeDb>();
155 ForgeDb.Configure(builder, "design-time.db");
156 return new ForgeDb(builder.Options);
157 }
158 }
added forge/Data/Migrations/20261115000224_Initial.Designer.cs +333 −0View file
@@ -0,0 +1,333 @@
1 // <auto-generated />
2 using System;
3 using Forge.Data;
4 using Microsoft.EntityFrameworkCore;
5 using Microsoft.EntityFrameworkCore.Infrastructure;
6 using Microsoft.EntityFrameworkCore.Migrations;
7 using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
8
9 #nullable disable
10
11 namespace Forge.Data.Migrations;
12
13 [DbContext(typeof(ForgeDb))]
14 [Migration("20261115000224_Initial")]
15 partial class _20261115000224_Initial
16 {
17 /// <inheritdoc />
18 protected override void BuildTargetModel(ModelBuilder modelBuilder)
19 {
20 #pragma warning disable 612, 618
21 modelBuilder.HasAnnotation("ProductVersion", "11.0.0");
22
23 modelBuilder.Entity("Forge.Data.AccessToken", b =>
24 {
25 b.Property<long>("Id")
26 .ValueGeneratedOnAdd()
27 .HasColumnType("INTEGER")
28 .HasColumnName("id");
29
30 b.Property<bool>("CanWrite")
31 .HasColumnType("INTEGER")
32 .HasColumnName("can_write");
33
34 b.Property<DateTime>("CreatedAt")
35 .HasColumnType("TEXT")
36 .HasColumnName("created_at");
37
38 b.Property<DateTime?>("ExpiresAt")
39 .HasColumnType("TEXT")
40 .HasColumnName("expires_at");
41
42 b.Property<DateTime?>("LastUsedAt")
43 .HasColumnType("TEXT")
44 .HasColumnName("last_used_at");
45
46 b.Property<string>("Name")
47 .IsRequired()
48 .HasColumnType("TEXT")
49 .HasColumnName("name");
50
51 b.Property<string>("TokenHash")
52 .IsRequired()
53 .HasColumnType("TEXT")
54 .HasColumnName("token_hash");
55
56 b.Property<long>("UserId")
57 .HasColumnType("INTEGER")
58 .HasColumnName("user_id");
59
60 b.HasKey("Id");
61
62 b.HasIndex("TokenHash")
63 .IsUnique();
64
65 b.HasIndex("UserId");
66
67 b.ToTable("access_tokens");
68 });
69
70 modelBuilder.Entity("Forge.Data.PushEvent", b =>
71 {
72 b.Property<long>("Id")
73 .ValueGeneratedOnAdd()
74 .HasColumnType("INTEGER")
75 .HasColumnName("id");
76
77 b.Property<string>("NewSha")
78 .IsRequired()
79 .HasColumnType("TEXT")
80 .HasColumnName("new_sha");
81
82 b.Property<string>("OldSha")
83 .IsRequired()
84 .HasColumnType("TEXT")
85 .HasColumnName("old_sha");
86
87 b.Property<DateTime>("PushedAt")
88 .HasColumnType("TEXT")
89 .HasColumnName("pushed_at");
90
91 b.Property<string>("RefName")
92 .IsRequired()
93 .HasColumnType("TEXT")
94 .HasColumnName("ref_name");
95
96 b.Property<long>("RepoId")
97 .HasColumnType("INTEGER")
98 .HasColumnName("repo_id");
99
100 b.HasKey("Id");
101
102 b.HasIndex("RepoId", "PushedAt");
103
104 b.ToTable("push_events");
105 });
106
107 modelBuilder.Entity("Forge.Data.Repository", b =>
108 {
109 b.Property<long>("Id")
110 .ValueGeneratedOnAdd()
111 .HasColumnType("INTEGER")
112 .HasColumnName("id");
113
114 b.Property<DateTime>("CreatedAt")
115 .HasColumnType("TEXT")
116 .HasColumnName("created_at");
117
118 b.Property<string>("DefaultBranch")
119 .IsRequired()
120 .HasColumnType("TEXT")
121 .HasColumnName("default_branch");
122
123 b.Property<string>("Description")
124 .IsRequired()
125 .HasColumnType("TEXT")
126 .HasColumnName("description");
127
128 b.Property<string>("Name")
129 .IsRequired()
130 .HasColumnType("TEXT")
131 .HasColumnName("name")
132 .UseCollation("NOCASE");
133
134 b.Property<long>("OwnerId")
135 .HasColumnType("INTEGER")
136 .HasColumnName("owner_id");
137
138 b.Property<DateTime?>("PushedAt")
139 .HasColumnType("TEXT")
140 .HasColumnName("pushed_at");
141
142 b.Property<string>("Visibility")
143 .IsRequired()
144 .HasColumnType("TEXT")
145 .HasColumnName("visibility");
146
147 b.HasKey("Id");
148
149 b.HasIndex("OwnerId", "Name")
150 .IsUnique();
151
152 b.ToTable("repositories");
153 });
154
155 modelBuilder.Entity("Forge.Data.User", b =>
156 {
157 b.Property<long>("Id")
158 .ValueGeneratedOnAdd()
159 .HasColumnType("INTEGER")
160 .HasColumnName("id");
161
162 b.Property<DateTime>("CreatedAt")
163 .HasColumnType("TEXT")
164 .HasColumnName("created_at");
165
166 b.Property<string>("DisplayName")
167 .IsRequired()
168 .HasColumnType("TEXT")
169 .HasColumnName("display_name");
170
171 b.Property<string>("PasswordHash")
172 .IsRequired()
173 .HasColumnType("TEXT")
174 .HasColumnName("password_hash");
175
176 b.Property<string>("Username")
177 .IsRequired()
178 .HasColumnType("TEXT")
179 .HasColumnName("username")
180 .UseCollation("NOCASE");
181
182 b.HasKey("Id");
183
184 b.HasIndex("Username")
185 .IsUnique();
186
187 b.ToTable("users");
188 });
189
190 modelBuilder.Entity("Forge.Data.Webhook", b =>
191 {
192 b.Property<long>("Id")
193 .ValueGeneratedOnAdd()
194 .HasColumnType("INTEGER")
195 .HasColumnName("id");
196
197 b.Property<bool>("Active")
198 .HasColumnType("INTEGER")
199 .HasColumnName("active");
200
201 b.Property<DateTime>("CreatedAt")
202 .HasColumnType("TEXT")
203 .HasColumnName("created_at");
204
205 b.Property<long>("RepoId")
206 .HasColumnType("INTEGER")
207 .HasColumnName("repo_id");
208
209 b.Property<string>("Secret")
210 .IsRequired()
211 .HasColumnType("TEXT")
212 .HasColumnName("secret");
213
214 b.Property<string>("Url")
215 .IsRequired()
216 .HasColumnType("TEXT")
217 .HasColumnName("url");
218
219 b.HasKey("Id");
220
221 b.HasIndex("RepoId");
222
223 b.ToTable("webhooks");
224 });
225
226 modelBuilder.Entity("Forge.Data.WebhookDelivery", b =>
227 {
228 b.Property<long>("Id")
229 .ValueGeneratedOnAdd()
230 .HasColumnType("INTEGER")
231 .HasColumnName("id");
232
233 b.Property<int>("Attempt")
234 .HasColumnType("INTEGER")
235 .HasColumnName("attempt");
236
237 b.Property<DateTime>("DeliveredAt")
238 .HasColumnType("TEXT")
239 .HasColumnName("delivered_at");
240
241 b.Property<int>("DurationMs")
242 .HasColumnType("INTEGER")
243 .HasColumnName("duration_ms");
244
245 b.Property<string>("Error")
246 .HasColumnType("TEXT")
247 .HasColumnName("error");
248
249 b.Property<long?>("PushEventId")
250 .HasColumnType("INTEGER")
251 .HasColumnName("push_event_id");
252
253 b.Property<int?>("StatusCode")
254 .HasColumnType("INTEGER")
255 .HasColumnName("status_code");
256
257 b.Property<long>("WebhookId")
258 .HasColumnType("INTEGER")
259 .HasColumnName("webhook_id");
260
261 b.HasKey("Id");
262
263 b.HasIndex("PushEventId");
264
265 b.HasIndex("WebhookId", "PushEventId");
266
267 b.ToTable("webhook_deliveries");
268 });
269
270 modelBuilder.Entity("Forge.Data.AccessToken", b =>
271 {
272 b.HasOne("Forge.Data.User", "User")
273 .WithMany()
274 .HasForeignKey("UserId")
275 .OnDelete(DeleteBehavior.Cascade)
276 .IsRequired();
277
278 b.Navigation("User");
279 });
280
281 modelBuilder.Entity("Forge.Data.PushEvent", b =>
282 {
283 b.HasOne("Forge.Data.Repository", "Repo")
284 .WithMany()
285 .HasForeignKey("RepoId")
286 .OnDelete(DeleteBehavior.Cascade)
287 .IsRequired();
288
289 b.Navigation("Repo");
290 });
291
292 modelBuilder.Entity("Forge.Data.Repository", b =>
293 {
294 b.HasOne("Forge.Data.User", "Owner")
295 .WithMany()
296 .HasForeignKey("OwnerId")
297 .OnDelete(DeleteBehavior.Cascade)
298 .IsRequired();
299
300 b.Navigation("Owner");
301 });
302
303 modelBuilder.Entity("Forge.Data.Webhook", b =>
304 {
305 b.HasOne("Forge.Data.Repository", "Repo")
306 .WithMany()
307 .HasForeignKey("RepoId")
308 .OnDelete(DeleteBehavior.Cascade)
309 .IsRequired();
310
311 b.Navigation("Repo");
312 });
313
314 modelBuilder.Entity("Forge.Data.WebhookDelivery", b =>
315 {
316 b.HasOne("Forge.Data.PushEvent", "PushEvent")
317 .WithMany()
318 .HasForeignKey("PushEventId")
319 .OnDelete(DeleteBehavior.Cascade);
320
321 b.HasOne("Forge.Data.Webhook", "Webhook")
322 .WithMany()
323 .HasForeignKey("WebhookId")
324 .OnDelete(DeleteBehavior.Cascade)
325 .IsRequired();
326
327 b.Navigation("PushEvent");
328
329 b.Navigation("Webhook");
330 });
331 #pragma warning restore 612, 618
332 }
333 }
added forge/Data/Migrations/20261115000224_Initial.cs +222 −0View file
@@ -0,0 +1,222 @@
1 using System;
2 using Microsoft.EntityFrameworkCore.Migrations;
3
4 #nullable disable
5
6 namespace Forge.Data.Migrations;
7
8 /// <inheritdoc />
9 public partial class _20261115000224_Initial : Migration
10 {
11 /// <inheritdoc />
12 protected override void Up(MigrationBuilder migrationBuilder)
13 {
14 migrationBuilder.CreateTable(
15 name: "users",
16 columns: table => new
17 {
18 id = table.Column<long>(type: "INTEGER", nullable: false)
19 .Annotation("Sqlite:Autoincrement", true),
20 username = table.Column<string>(type: "TEXT", nullable: false, collation: "NOCASE"),
21 display_name = table.Column<string>(type: "TEXT", nullable: false),
22 password_hash = table.Column<string>(type: "TEXT", nullable: false),
23 created_at = table.Column<DateTime>(type: "TEXT", nullable: false)
24 },
25 constraints: table =>
26 {
27 table.PrimaryKey("PK_users", x => x.id);
28 });
29
30 migrationBuilder.CreateTable(
31 name: "access_tokens",
32 columns: table => new
33 {
34 id = table.Column<long>(type: "INTEGER", nullable: false)
35 .Annotation("Sqlite:Autoincrement", true),
36 user_id = table.Column<long>(type: "INTEGER", nullable: false),
37 name = table.Column<string>(type: "TEXT", nullable: false),
38 token_hash = table.Column<string>(type: "TEXT", nullable: false),
39 can_write = table.Column<bool>(type: "INTEGER", nullable: false),
40 created_at = table.Column<DateTime>(type: "TEXT", nullable: false),
41 last_used_at = table.Column<DateTime>(type: "TEXT", nullable: true),
42 expires_at = table.Column<DateTime>(type: "TEXT", nullable: true)
43 },
44 constraints: table =>
45 {
46 table.PrimaryKey("PK_access_tokens", x => x.id);
47 table.ForeignKey(
48 name: "FK_access_tokens_users_user_id",
49 column: x => x.user_id,
50 principalTable: "users",
51 principalColumn: "id",
52 onDelete: ReferentialAction.Cascade);
53 });
54
55 migrationBuilder.CreateTable(
56 name: "repositories",
57 columns: table => new
58 {
59 id = table.Column<long>(type: "INTEGER", nullable: false)
60 .Annotation("Sqlite:Autoincrement", true),
61 owner_id = table.Column<long>(type: "INTEGER", nullable: false),
62 name = table.Column<string>(type: "TEXT", nullable: false, collation: "NOCASE"),
63 description = table.Column<string>(type: "TEXT", nullable: false),
64 visibility = table.Column<string>(type: "TEXT", nullable: false),
65 default_branch = table.Column<string>(type: "TEXT", nullable: false),
66 created_at = table.Column<DateTime>(type: "TEXT", nullable: false),
67 pushed_at = table.Column<DateTime>(type: "TEXT", nullable: true)
68 },
69 constraints: table =>
70 {
71 table.PrimaryKey("PK_repositories", x => x.id);
72 table.ForeignKey(
73 name: "FK_repositories_users_owner_id",
74 column: x => x.owner_id,
75 principalTable: "users",
76 principalColumn: "id",
77 onDelete: ReferentialAction.Cascade);
78 });
79
80 migrationBuilder.CreateTable(
81 name: "push_events",
82 columns: table => new
83 {
84 id = table.Column<long>(type: "INTEGER", nullable: false)
85 .Annotation("Sqlite:Autoincrement", true),
86 repo_id = table.Column<long>(type: "INTEGER", nullable: false),
87 ref_name = table.Column<string>(type: "TEXT", nullable: false),
88 old_sha = table.Column<string>(type: "TEXT", nullable: false),
89 new_sha = table.Column<string>(type: "TEXT", nullable: false),
90 pushed_at = table.Column<DateTime>(type: "TEXT", nullable: false)
91 },
92 constraints: table =>
93 {
94 table.PrimaryKey("PK_push_events", x => x.id);
95 table.ForeignKey(
96 name: "FK_push_events_repositories_repo_id",
97 column: x => x.repo_id,
98 principalTable: "repositories",
99 principalColumn: "id",
100 onDelete: ReferentialAction.Cascade);
101 });
102
103 migrationBuilder.CreateTable(
104 name: "webhooks",
105 columns: table => new
106 {
107 id = table.Column<long>(type: "INTEGER", nullable: false)
108 .Annotation("Sqlite:Autoincrement", true),
109 repo_id = table.Column<long>(type: "INTEGER", nullable: false),
110 url = table.Column<string>(type: "TEXT", nullable: false),
111 secret = table.Column<string>(type: "TEXT", nullable: false),
112 active = table.Column<bool>(type: "INTEGER", nullable: false),
113 created_at = table.Column<DateTime>(type: "TEXT", nullable: false)
114 },
115 constraints: table =>
116 {
117 table.PrimaryKey("PK_webhooks", x => x.id);
118 table.ForeignKey(
119 name: "FK_webhooks_repositories_repo_id",
120 column: x => x.repo_id,
121 principalTable: "repositories",
122 principalColumn: "id",
123 onDelete: ReferentialAction.Cascade);
124 });
125
126 migrationBuilder.CreateTable(
127 name: "webhook_deliveries",
128 columns: table => new
129 {
130 id = table.Column<long>(type: "INTEGER", nullable: false)
131 .Annotation("Sqlite:Autoincrement", true),
132 webhook_id = table.Column<long>(type: "INTEGER", nullable: false),
133 push_event_id = table.Column<long>(type: "INTEGER", nullable: true),
134 status_code = table.Column<int>(type: "INTEGER", nullable: true),
135 duration_ms = table.Column<int>(type: "INTEGER", nullable: false),
136 error = table.Column<string>(type: "TEXT", nullable: true),
137 attempt = table.Column<int>(type: "INTEGER", nullable: false),
138 delivered_at = table.Column<DateTime>(type: "TEXT", nullable: false)
139 },
140 constraints: table =>
141 {
142 table.PrimaryKey("PK_webhook_deliveries", x => x.id);
143 table.ForeignKey(
144 name: "FK_webhook_deliveries_push_events_push_event_id",
145 column: x => x.push_event_id,
146 principalTable: "push_events",
147 principalColumn: "id",
148 onDelete: ReferentialAction.Cascade);
149 table.ForeignKey(
150 name: "FK_webhook_deliveries_webhooks_webhook_id",
151 column: x => x.webhook_id,
152 principalTable: "webhooks",
153 principalColumn: "id",
154 onDelete: ReferentialAction.Cascade);
155 });
156
157 migrationBuilder.CreateIndex(
158 name: "IX_access_tokens_token_hash",
159 table: "access_tokens",
160 column: "token_hash",
161 unique: true);
162
163 migrationBuilder.CreateIndex(
164 name: "IX_access_tokens_user_id",
165 table: "access_tokens",
166 column: "user_id");
167
168 migrationBuilder.CreateIndex(
169 name: "IX_push_events_repo_id_pushed_at",
170 table: "push_events",
171 columns: new[] { "repo_id", "pushed_at" });
172
173 migrationBuilder.CreateIndex(
174 name: "IX_repositories_owner_id_name",
175 table: "repositories",
176 columns: new[] { "owner_id", "name" },
177 unique: true);
178
179 migrationBuilder.CreateIndex(
180 name: "IX_users_username",
181 table: "users",
182 column: "username",
183 unique: true);
184
185 migrationBuilder.CreateIndex(
186 name: "IX_webhook_deliveries_push_event_id",
187 table: "webhook_deliveries",
188 column: "push_event_id");
189
190 migrationBuilder.CreateIndex(
191 name: "IX_webhook_deliveries_webhook_id_push_event_id",
192 table: "webhook_deliveries",
193 columns: new[] { "webhook_id", "push_event_id" });
194
195 migrationBuilder.CreateIndex(
196 name: "IX_webhooks_repo_id",
197 table: "webhooks",
198 column: "repo_id");
199 }
200
201 /// <inheritdoc />
202 protected override void Down(MigrationBuilder migrationBuilder)
203 {
204 migrationBuilder.DropTable(
205 name: "access_tokens");
206
207 migrationBuilder.DropTable(
208 name: "webhook_deliveries");
209
210 migrationBuilder.DropTable(
211 name: "push_events");
212
213 migrationBuilder.DropTable(
214 name: "webhooks");
215
216 migrationBuilder.DropTable(
217 name: "repositories");
218
219 migrationBuilder.DropTable(
220 name: "users");
221 }
222 }
added forge/Data/Migrations/20261115121154_PullRequestsAndBranchProtection.Designer.cs +525 −0View file
@@ -0,0 +1,525 @@
1 // <auto-generated />
2 using System;
3 using Forge.Data;
4 using Microsoft.EntityFrameworkCore;
5 using Microsoft.EntityFrameworkCore.Infrastructure;
6 using Microsoft.EntityFrameworkCore.Migrations;
7 using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
8
9 #nullable disable
10
11 namespace Forge.Data.Migrations;
12
13 [DbContext(typeof(ForgeDb))]
14 [Migration("20261115121154_PullRequestsAndBranchProtection")]
15 partial class _20261115121154_PullRequestsAndBranchProtection
16 {
17 /// <inheritdoc />
18 protected override void BuildTargetModel(ModelBuilder modelBuilder)
19 {
20 #pragma warning disable 612, 618
21 modelBuilder.HasAnnotation("ProductVersion", "11.0.0");
22
23 modelBuilder.Entity("Forge.Data.AccessToken", b =>
24 {
25 b.Property<long>("Id")
26 .ValueGeneratedOnAdd()
27 .HasColumnType("INTEGER")
28 .HasColumnName("id");
29
30 b.Property<bool>("CanWrite")
31 .HasColumnType("INTEGER")
32 .HasColumnName("can_write");
33
34 b.Property<DateTime>("CreatedAt")
35 .HasColumnType("TEXT")
36 .HasColumnName("created_at");
37
38 b.Property<DateTime?>("ExpiresAt")
39 .HasColumnType("TEXT")
40 .HasColumnName("expires_at");
41
42 b.Property<DateTime?>("LastUsedAt")
43 .HasColumnType("TEXT")
44 .HasColumnName("last_used_at");
45
46 b.Property<string>("Name")
47 .IsRequired()
48 .HasColumnType("TEXT")
49 .HasColumnName("name");
50
51 b.Property<string>("TokenHash")
52 .IsRequired()
53 .HasColumnType("TEXT")
54 .HasColumnName("token_hash");
55
56 b.Property<long>("UserId")
57 .HasColumnType("INTEGER")
58 .HasColumnName("user_id");
59
60 b.HasKey("Id");
61
62 b.HasIndex("TokenHash")
63 .IsUnique();
64
65 b.HasIndex("UserId");
66
67 b.ToTable("access_tokens");
68 });
69
70 modelBuilder.Entity("Forge.Data.BranchProtection", b =>
71 {
72 b.Property<long>("Id")
73 .ValueGeneratedOnAdd()
74 .HasColumnType("INTEGER")
75 .HasColumnName("id");
76
77 b.Property<bool>("BlockPush")
78 .HasColumnType("INTEGER")
79 .HasColumnName("block_push");
80
81 b.Property<DateTime>("CreatedAt")
82 .HasColumnType("TEXT")
83 .HasColumnName("created_at");
84
85 b.Property<string>("Pattern")
86 .IsRequired()
87 .HasColumnType("TEXT")
88 .HasColumnName("pattern");
89
90 b.Property<long>("RepoId")
91 .HasColumnType("INTEGER")
92 .HasColumnName("repo_id");
93
94 b.HasKey("Id");
95
96 b.HasIndex("RepoId", "Pattern")
97 .IsUnique();
98
99 b.ToTable("branch_protections");
100 });
101
102 modelBuilder.Entity("Forge.Data.PullRequest", b =>
103 {
104 b.Property<long>("Id")
105 .ValueGeneratedOnAdd()
106 .HasColumnType("INTEGER")
107 .HasColumnName("id");
108
109 b.Property<long>("AuthorId")
110 .HasColumnType("INTEGER")
111 .HasColumnName("author_id");
112
113 b.Property<string>("BaseBranch")
114 .IsRequired()
115 .HasColumnType("TEXT")
116 .HasColumnName("base_branch");
117
118 b.Property<string>("BaseSha")
119 .HasColumnType("TEXT")
120 .HasColumnName("base_sha");
121
122 b.Property<DateTime?>("ClosedAt")
123 .HasColumnType("TEXT")
124 .HasColumnName("closed_at");
125
126 b.Property<DateTime>("CreatedAt")
127 .HasColumnType("TEXT")
128 .HasColumnName("created_at");
129
130 b.Property<string>("Description")
131 .IsRequired()
132 .HasColumnType("TEXT")
133 .HasColumnName("description");
134
135 b.Property<string>("HeadBranch")
136 .IsRequired()
137 .HasColumnType("TEXT")
138 .HasColumnName("head_branch");
139
140 b.Property<string>("HeadSha")
141 .HasColumnType("TEXT")
142 .HasColumnName("head_sha");
143
144 b.Property<string>("MergeCommitSha")
145 .HasColumnType("TEXT")
146 .HasColumnName("merge_commit_sha");
147
148 b.Property<int>("Number")
149 .HasColumnType("INTEGER")
150 .HasColumnName("number");
151
152 b.Property<long>("RepoId")
153 .HasColumnType("INTEGER")
154 .HasColumnName("repo_id");
155
156 b.Property<string>("Status")
157 .IsRequired()
158 .HasColumnType("TEXT")
159 .HasColumnName("status");
160
161 b.Property<string>("Title")
162 .IsRequired()
163 .HasColumnType("TEXT")
164 .HasColumnName("title");
165
166 b.Property<DateTime>("UpdatedAt")
167 .HasColumnType("TEXT")
168 .HasColumnName("updated_at");
169
170 b.HasKey("Id");
171
172 b.HasIndex("AuthorId");
173
174 b.HasIndex("RepoId", "Number")
175 .IsUnique();
176
177 b.ToTable("pull_requests");
178 });
179
180 modelBuilder.Entity("Forge.Data.PullRequestComment", b =>
181 {
182 b.Property<long>("Id")
183 .ValueGeneratedOnAdd()
184 .HasColumnType("INTEGER")
185 .HasColumnName("id");
186
187 b.Property<long>("AuthorId")
188 .HasColumnType("INTEGER")
189 .HasColumnName("author_id");
190
191 b.Property<string>("Body")
192 .IsRequired()
193 .HasColumnType("TEXT")
194 .HasColumnName("body");
195
196 b.Property<DateTime>("CreatedAt")
197 .HasColumnType("TEXT")
198 .HasColumnName("created_at");
199
200 b.Property<long>("PullRequestId")
201 .HasColumnType("INTEGER")
202 .HasColumnName("pull_request_id");
203
204 b.HasKey("Id");
205
206 b.HasIndex("AuthorId");
207
208 b.HasIndex("PullRequestId");
209
210 b.ToTable("pull_request_comments");
211 });
212
213 modelBuilder.Entity("Forge.Data.PushEvent", b =>
214 {
215 b.Property<long>("Id")
216 .ValueGeneratedOnAdd()
217 .HasColumnType("INTEGER")
218 .HasColumnName("id");
219
220 b.Property<string>("NewSha")
221 .IsRequired()
222 .HasColumnType("TEXT")
223 .HasColumnName("new_sha");
224
225 b.Property<string>("OldSha")
226 .IsRequired()
227 .HasColumnType("TEXT")
228 .HasColumnName("old_sha");
229
230 b.Property<DateTime>("PushedAt")
231 .HasColumnType("TEXT")
232 .HasColumnName("pushed_at");
233
234 b.Property<string>("RefName")
235 .IsRequired()
236 .HasColumnType("TEXT")
237 .HasColumnName("ref_name");
238
239 b.Property<long>("RepoId")
240 .HasColumnType("INTEGER")
241 .HasColumnName("repo_id");
242
243 b.HasKey("Id");
244
245 b.HasIndex("RepoId", "PushedAt");
246
247 b.ToTable("push_events");
248 });
249
250 modelBuilder.Entity("Forge.Data.Repository", b =>
251 {
252 b.Property<long>("Id")
253 .ValueGeneratedOnAdd()
254 .HasColumnType("INTEGER")
255 .HasColumnName("id");
256
257 b.Property<DateTime>("CreatedAt")
258 .HasColumnType("TEXT")
259 .HasColumnName("created_at");
260
261 b.Property<string>("DefaultBranch")
262 .IsRequired()
263 .HasColumnType("TEXT")
264 .HasColumnName("default_branch");
265
266 b.Property<string>("Description")
267 .IsRequired()
268 .HasColumnType("TEXT")
269 .HasColumnName("description");
270
271 b.Property<string>("Name")
272 .IsRequired()
273 .HasColumnType("TEXT")
274 .HasColumnName("name")
275 .UseCollation("NOCASE");
276
277 b.Property<long>("OwnerId")
278 .HasColumnType("INTEGER")
279 .HasColumnName("owner_id");
280
281 b.Property<DateTime?>("PushedAt")
282 .HasColumnType("TEXT")
283 .HasColumnName("pushed_at");
284
285 b.Property<string>("Visibility")
286 .IsRequired()
287 .HasColumnType("TEXT")
288 .HasColumnName("visibility");
289
290 b.HasKey("Id");
291
292 b.HasIndex("OwnerId", "Name")
293 .IsUnique();
294
295 b.ToTable("repositories");
296 });
297
298 modelBuilder.Entity("Forge.Data.User", b =>
299 {
300 b.Property<long>("Id")
301 .ValueGeneratedOnAdd()
302 .HasColumnType("INTEGER")
303 .HasColumnName("id");
304
305 b.Property<DateTime>("CreatedAt")
306 .HasColumnType("TEXT")
307 .HasColumnName("created_at");
308
309 b.Property<string>("DisplayName")
310 .IsRequired()
311 .HasColumnType("TEXT")
312 .HasColumnName("display_name");
313
314 b.Property<string>("PasswordHash")
315 .IsRequired()
316 .HasColumnType("TEXT")
317 .HasColumnName("password_hash");
318
319 b.Property<string>("Username")
320 .IsRequired()
321 .HasColumnType("TEXT")
322 .HasColumnName("username")
323 .UseCollation("NOCASE");
324
325 b.HasKey("Id");
326
327 b.HasIndex("Username")
328 .IsUnique();
329
330 b.ToTable("users");
331 });
332
333 modelBuilder.Entity("Forge.Data.Webhook", b =>
334 {
335 b.Property<long>("Id")
336 .ValueGeneratedOnAdd()
337 .HasColumnType("INTEGER")
338 .HasColumnName("id");
339
340 b.Property<bool>("Active")
341 .HasColumnType("INTEGER")
342 .HasColumnName("active");
343
344 b.Property<DateTime>("CreatedAt")
345 .HasColumnType("TEXT")
346 .HasColumnName("created_at");
347
348 b.Property<long>("RepoId")
349 .HasColumnType("INTEGER")
350 .HasColumnName("repo_id");
351
352 b.Property<string>("Secret")
353 .IsRequired()
354 .HasColumnType("TEXT")
355 .HasColumnName("secret");
356
357 b.Property<string>("Url")
358 .IsRequired()
359 .HasColumnType("TEXT")
360 .HasColumnName("url");
361
362 b.HasKey("Id");
363
364 b.HasIndex("RepoId");
365
366 b.ToTable("webhooks");
367 });
368
369 modelBuilder.Entity("Forge.Data.WebhookDelivery", b =>
370 {
371 b.Property<long>("Id")
372 .ValueGeneratedOnAdd()
373 .HasColumnType("INTEGER")
374 .HasColumnName("id");
375
376 b.Property<int>("Attempt")
377 .HasColumnType("INTEGER")
378 .HasColumnName("attempt");
379
380 b.Property<DateTime>("DeliveredAt")
381 .HasColumnType("TEXT")
382 .HasColumnName("delivered_at");
383
384 b.Property<int>("DurationMs")
385 .HasColumnType("INTEGER")
386 .HasColumnName("duration_ms");
387
388 b.Property<string>("Error")
389 .HasColumnType("TEXT")
390 .HasColumnName("error");
391
392 b.Property<long?>("PushEventId")
393 .HasColumnType("INTEGER")
394 .HasColumnName("push_event_id");
395
396 b.Property<int?>("StatusCode")
397 .HasColumnType("INTEGER")
398 .HasColumnName("status_code");
399
400 b.Property<long>("WebhookId")
401 .HasColumnType("INTEGER")
402 .HasColumnName("webhook_id");
403
404 b.HasKey("Id");
405
406 b.HasIndex("PushEventId");
407
408 b.HasIndex("WebhookId", "PushEventId");
409
410 b.ToTable("webhook_deliveries");
411 });
412
413 modelBuilder.Entity("Forge.Data.AccessToken", b =>
414 {
415 b.HasOne("Forge.Data.User", "User")
416 .WithMany()
417 .HasForeignKey("UserId")
418 .OnDelete(DeleteBehavior.Cascade)
419 .IsRequired();
420
421 b.Navigation("User");
422 });
423
424 modelBuilder.Entity("Forge.Data.BranchProtection", b =>
425 {
426 b.HasOne("Forge.Data.Repository", "Repo")
427 .WithMany()
428 .HasForeignKey("RepoId")
429 .OnDelete(DeleteBehavior.Cascade)
430 .IsRequired();
431
432 b.Navigation("Repo");
433 });
434
435 modelBuilder.Entity("Forge.Data.PullRequest", b =>
436 {
437 b.HasOne("Forge.Data.User", "Author")
438 .WithMany()
439 .HasForeignKey("AuthorId")
440 .OnDelete(DeleteBehavior.Cascade)
441 .IsRequired();
442
443 b.HasOne("Forge.Data.Repository", "Repo")
444 .WithMany()
445 .HasForeignKey("RepoId")
446 .OnDelete(DeleteBehavior.Cascade)
447 .IsRequired();
448
449 b.Navigation("Author");
450
451 b.Navigation("Repo");
452 });
453
454 modelBuilder.Entity("Forge.Data.PullRequestComment", b =>
455 {
456 b.HasOne("Forge.Data.User", "Author")
457 .WithMany()
458 .HasForeignKey("AuthorId")
459 .OnDelete(DeleteBehavior.Cascade)
460 .IsRequired();
461
462 b.HasOne("Forge.Data.PullRequest", "PullRequest")
463 .WithMany()
464 .HasForeignKey("PullRequestId")
465 .OnDelete(DeleteBehavior.Cascade)
466 .IsRequired();
467
468 b.Navigation("Author");
469
470 b.Navigation("PullRequest");
471 });
472
473 modelBuilder.Entity("Forge.Data.PushEvent", b =>
474 {
475 b.HasOne("Forge.Data.Repository", "Repo")
476 .WithMany()
477 .HasForeignKey("RepoId")
478 .OnDelete(DeleteBehavior.Cascade)
479 .IsRequired();
480
481 b.Navigation("Repo");
482 });
483
484 modelBuilder.Entity("Forge.Data.Repository", b =>
485 {
486 b.HasOne("Forge.Data.User", "Owner")
487 .WithMany()
488 .HasForeignKey("OwnerId")
489 .OnDelete(DeleteBehavior.Cascade)
490 .IsRequired();
491
492 b.Navigation("Owner");
493 });
494
495 modelBuilder.Entity("Forge.Data.Webhook", b =>
496 {
497 b.HasOne("Forge.Data.Repository", "Repo")
498 .WithMany()
499 .HasForeignKey("RepoId")
500 .OnDelete(DeleteBehavior.Cascade)
501 .IsRequired();
502
503 b.Navigation("Repo");
504 });
505
506 modelBuilder.Entity("Forge.Data.WebhookDelivery", b =>
507 {
508 b.HasOne("Forge.Data.PushEvent", "PushEvent")
509 .WithMany()
510 .HasForeignKey("PushEventId")
511 .OnDelete(DeleteBehavior.Cascade);
512
513 b.HasOne("Forge.Data.Webhook", "Webhook")
514 .WithMany()
515 .HasForeignKey("WebhookId")
516 .OnDelete(DeleteBehavior.Cascade)
517 .IsRequired();
518
519 b.Navigation("PushEvent");
520
521 b.Navigation("Webhook");
522 });
523 #pragma warning restore 612, 618
524 }
525 }
added forge/Data/Migrations/20261115121154_PullRequestsAndBranchProtection.cs +142 −0View file
@@ -0,0 +1,142 @@
1 using System;
2 using Microsoft.EntityFrameworkCore.Migrations;
3
4 #nullable disable
5
6 namespace Forge.Data.Migrations;
7
8 /// <inheritdoc />
9 public partial class _20261115121154_PullRequestsAndBranchProtection : Migration
10 {
11 /// <inheritdoc />
12 protected override void Up(MigrationBuilder migrationBuilder)
13 {
14 migrationBuilder.CreateTable(
15 name: "branch_protections",
16 columns: table => new
17 {
18 id = table.Column<long>(type: "INTEGER", nullable: false)
19 .Annotation("Sqlite:Autoincrement", true),
20 repo_id = table.Column<long>(type: "INTEGER", nullable: false),
21 pattern = table.Column<string>(type: "TEXT", nullable: false),
22 block_push = table.Column<bool>(type: "INTEGER", nullable: false),
23 created_at = table.Column<DateTime>(type: "TEXT", nullable: false)
24 },
25 constraints: table =>
26 {
27 table.PrimaryKey("PK_branch_protections", x => x.id);
28 table.ForeignKey(
29 name: "FK_branch_protections_repositories_repo_id",
30 column: x => x.repo_id,
31 principalTable: "repositories",
32 principalColumn: "id",
33 onDelete: ReferentialAction.Cascade);
34 });
35
36 migrationBuilder.CreateTable(
37 name: "pull_requests",
38 columns: table => new
39 {
40 id = table.Column<long>(type: "INTEGER", nullable: false)
41 .Annotation("Sqlite:Autoincrement", true),
42 repo_id = table.Column<long>(type: "INTEGER", nullable: false),
43 number = table.Column<int>(type: "INTEGER", nullable: false),
44 title = table.Column<string>(type: "TEXT", nullable: false),
45 description = table.Column<string>(type: "TEXT", nullable: false),
46 base_branch = table.Column<string>(type: "TEXT", nullable: false),
47 head_branch = table.Column<string>(type: "TEXT", nullable: false),
48 status = table.Column<string>(type: "TEXT", nullable: false),
49 author_id = table.Column<long>(type: "INTEGER", nullable: false),
50 created_at = table.Column<DateTime>(type: "TEXT", nullable: false),
51 updated_at = table.Column<DateTime>(type: "TEXT", nullable: false),
52 closed_at = table.Column<DateTime>(type: "TEXT", nullable: true),
53 merge_commit_sha = table.Column<string>(type: "TEXT", nullable: true),
54 base_sha = table.Column<string>(type: "TEXT", nullable: true),
55 head_sha = table.Column<string>(type: "TEXT", nullable: true)
56 },
57 constraints: table =>
58 {
59 table.PrimaryKey("PK_pull_requests", x => x.id);
60 table.ForeignKey(
61 name: "FK_pull_requests_repositories_repo_id",
62 column: x => x.repo_id,
63 principalTable: "repositories",
64 principalColumn: "id",
65 onDelete: ReferentialAction.Cascade);
66 table.ForeignKey(
67 name: "FK_pull_requests_users_author_id",
68 column: x => x.author_id,
69 principalTable: "users",
70 principalColumn: "id",
71 onDelete: ReferentialAction.Cascade);
72 });
73
74 migrationBuilder.CreateTable(
75 name: "pull_request_comments",
76 columns: table => new
77 {
78 id = table.Column<long>(type: "INTEGER", nullable: false)
79 .Annotation("Sqlite:Autoincrement", true),
80 pull_request_id = table.Column<long>(type: "INTEGER", nullable: false),
81 author_id = table.Column<long>(type: "INTEGER", nullable: false),
82 body = table.Column<string>(type: "TEXT", nullable: false),
83 created_at = table.Column<DateTime>(type: "TEXT", nullable: false)
84 },
85 constraints: table =>
86 {
87 table.PrimaryKey("PK_pull_request_comments", x => x.id);
88 table.ForeignKey(
89 name: "FK_pull_request_comments_pull_requests_pull_request_id",
90 column: x => x.pull_request_id,
91 principalTable: "pull_requests",
92 principalColumn: "id",
93 onDelete: ReferentialAction.Cascade);
94 table.ForeignKey(
95 name: "FK_pull_request_comments_users_author_id",
96 column: x => x.author_id,
97 principalTable: "users",
98 principalColumn: "id",
99 onDelete: ReferentialAction.Cascade);
100 });
101
102 migrationBuilder.CreateIndex(
103 name: "IX_branch_protections_repo_id_pattern",
104 table: "branch_protections",
105 columns: new[] { "repo_id", "pattern" },
106 unique: true);
107
108 migrationBuilder.CreateIndex(
109 name: "IX_pull_request_comments_author_id",
110 table: "pull_request_comments",
111 column: "author_id");
112
113 migrationBuilder.CreateIndex(
114 name: "IX_pull_request_comments_pull_request_id",
115 table: "pull_request_comments",
116 column: "pull_request_id");
117
118 migrationBuilder.CreateIndex(
119 name: "IX_pull_requests_author_id",
120 table: "pull_requests",
121 column: "author_id");
122
123 migrationBuilder.CreateIndex(
124 name: "IX_pull_requests_repo_id_number",
125 table: "pull_requests",
126 columns: new[] { "repo_id", "number" },
127 unique: true);
128 }
129
130 /// <inheritdoc />
131 protected override void Down(MigrationBuilder migrationBuilder)
132 {
133 migrationBuilder.DropTable(
134 name: "branch_protections");
135
136 migrationBuilder.DropTable(
137 name: "pull_request_comments");
138
139 migrationBuilder.DropTable(
140 name: "pull_requests");
141 }
142 }
added forge/Data/Migrations/ForgeDbModelSnapshot.cs +527 −0View file
@@ -0,0 +1,527 @@
1 // <auto-generated />
2 using System;
3 using Forge.Data;
4 using Microsoft.EntityFrameworkCore;
5 using Microsoft.EntityFrameworkCore.Infrastructure;
6 using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
7
8 #nullable disable
9
10 namespace Forge.Data.Migrations;
11
12 [DbContext(typeof(ForgeDb))]
13 partial class ForgeDbModelSnapshot : ModelSnapshot
14 {
15 // If you encounter a merge conflict in the line below, it means you need to
16 // discard one of the migration branches and recreate its migrations on top of
17 // the other branch. See https://aka.ms/efcore-docs-migrations-conflicts for more info.
18 public override string LastMigrationId => "20261115121154_PullRequestsAndBranchProtection";
19
20 protected override void BuildModel(ModelBuilder modelBuilder)
21 {
22 #pragma warning disable 612, 618
23 modelBuilder.HasAnnotation("ProductVersion", "11.0.0");
24
25 modelBuilder.Entity("Forge.Data.AccessToken", b =>
26 {
27 b.Property<long>("Id")
28 .ValueGeneratedOnAdd()
29 .HasColumnType("INTEGER")
30 .HasColumnName("id");
31
32 b.Property<bool>("CanWrite")
33 .HasColumnType("INTEGER")
34 .HasColumnName("can_write");
35
36 b.Property<DateTime>("CreatedAt")
37 .HasColumnType("TEXT")
38 .HasColumnName("created_at");
39
40 b.Property<DateTime?>("ExpiresAt")
41 .HasColumnType("TEXT")
42 .HasColumnName("expires_at");
43
44 b.Property<DateTime?>("LastUsedAt")
45 .HasColumnType("TEXT")
46 .HasColumnName("last_used_at");
47
48 b.Property<string>("Name")
49 .IsRequired()
50 .HasColumnType("TEXT")
51 .HasColumnName("name");
52
53 b.Property<string>("TokenHash")
54 .IsRequired()
55 .HasColumnType("TEXT")
56 .HasColumnName("token_hash");
57
58 b.Property<long>("UserId")
59 .HasColumnType("INTEGER")
60 .HasColumnName("user_id");
61
62 b.HasKey("Id");
63
64 b.HasIndex("TokenHash")
65 .IsUnique();
66
67 b.HasIndex("UserId");
68
69 b.ToTable("access_tokens");
70 });
71
72 modelBuilder.Entity("Forge.Data.BranchProtection", b =>
73 {
74 b.Property<long>("Id")
75 .ValueGeneratedOnAdd()
76 .HasColumnType("INTEGER")
77 .HasColumnName("id");
78
79 b.Property<bool>("BlockPush")
80 .HasColumnType("INTEGER")
81 .HasColumnName("block_push");
82
83 b.Property<DateTime>("CreatedAt")
84 .HasColumnType("TEXT")
85 .HasColumnName("created_at");
86
87 b.Property<string>("Pattern")
88 .IsRequired()
89 .HasColumnType("TEXT")
90 .HasColumnName("pattern");
91
92 b.Property<long>("RepoId")
93 .HasColumnType("INTEGER")
94 .HasColumnName("repo_id");
95
96 b.HasKey("Id");
97
98 b.HasIndex("RepoId", "Pattern")
99 .IsUnique();
100
101 b.ToTable("branch_protections");
102 });
103
104 modelBuilder.Entity("Forge.Data.PullRequest", b =>
105 {
106 b.Property<long>("Id")
107 .ValueGeneratedOnAdd()
108 .HasColumnType("INTEGER")
109 .HasColumnName("id");
110
111 b.Property<long>("AuthorId")
112 .HasColumnType("INTEGER")
113 .HasColumnName("author_id");
114
115 b.Property<string>("BaseBranch")
116 .IsRequired()
117 .HasColumnType("TEXT")
118 .HasColumnName("base_branch");
119
120 b.Property<string>("BaseSha")
121 .HasColumnType("TEXT")
122 .HasColumnName("base_sha");
123
124 b.Property<DateTime?>("ClosedAt")
125 .HasColumnType("TEXT")
126 .HasColumnName("closed_at");
127
128 b.Property<DateTime>("CreatedAt")
129 .HasColumnType("TEXT")
130 .HasColumnName("created_at");
131
132 b.Property<string>("Description")
133 .IsRequired()
134 .HasColumnType("TEXT")
135 .HasColumnName("description");
136
137 b.Property<string>("HeadBranch")
138 .IsRequired()
139 .HasColumnType("TEXT")
140 .HasColumnName("head_branch");
141
142 b.Property<string>("HeadSha")
143 .HasColumnType("TEXT")
144 .HasColumnName("head_sha");
145
146 b.Property<string>("MergeCommitSha")
147 .HasColumnType("TEXT")
148 .HasColumnName("merge_commit_sha");
149
150 b.Property<int>("Number")
151 .HasColumnType("INTEGER")
152 .HasColumnName("number");
153
154 b.Property<long>("RepoId")
155 .HasColumnType("INTEGER")
156 .HasColumnName("repo_id");
157
158 b.Property<string>("Status")
159 .IsRequired()
160 .HasColumnType("TEXT")
161 .HasColumnName("status");
162
163 b.Property<string>("Title")
164 .IsRequired()
165 .HasColumnType("TEXT")
166 .HasColumnName("title");
167
168 b.Property<DateTime>("UpdatedAt")
169 .HasColumnType("TEXT")
170 .HasColumnName("updated_at");
171
172 b.HasKey("Id");
173
174 b.HasIndex("AuthorId");
175
176 b.HasIndex("RepoId", "Number")
177 .IsUnique();
178
179 b.ToTable("pull_requests");
180 });
181
182 modelBuilder.Entity("Forge.Data.PullRequestComment", b =>
183 {
184 b.Property<long>("Id")
185 .ValueGeneratedOnAdd()
186 .HasColumnType("INTEGER")
187 .HasColumnName("id");
188
189 b.Property<long>("AuthorId")
190 .HasColumnType("INTEGER")
191 .HasColumnName("author_id");
192
193 b.Property<string>("Body")
194 .IsRequired()
195 .HasColumnType("TEXT")
196 .HasColumnName("body");
197
198 b.Property<DateTime>("CreatedAt")
199 .HasColumnType("TEXT")
200 .HasColumnName("created_at");
201
202 b.Property<long>("PullRequestId")
203 .HasColumnType("INTEGER")
204 .HasColumnName("pull_request_id");
205
206 b.HasKey("Id");
207
208 b.HasIndex("AuthorId");
209
210 b.HasIndex("PullRequestId");
211
212 b.ToTable("pull_request_comments");
213 });
214
215 modelBuilder.Entity("Forge.Data.PushEvent", b =>
216 {
217 b.Property<long>("Id")
218 .ValueGeneratedOnAdd()
219 .HasColumnType("INTEGER")
220 .HasColumnName("id");
221
222 b.Property<string>("NewSha")
223 .IsRequired()
224 .HasColumnType("TEXT")
225 .HasColumnName("new_sha");
226
227 b.Property<string>("OldSha")
228 .IsRequired()
229 .HasColumnType("TEXT")
230 .HasColumnName("old_sha");
231
232 b.Property<DateTime>("PushedAt")
233 .HasColumnType("TEXT")
234 .HasColumnName("pushed_at");
235
236 b.Property<string>("RefName")
237 .IsRequired()
238 .HasColumnType("TEXT")
239 .HasColumnName("ref_name");
240
241 b.Property<long>("RepoId")
242 .HasColumnType("INTEGER")
243 .HasColumnName("repo_id");
244
245 b.HasKey("Id");
246
247 b.HasIndex("RepoId", "PushedAt");
248
249 b.ToTable("push_events");
250 });
251
252 modelBuilder.Entity("Forge.Data.Repository", b =>
253 {
254 b.Property<long>("Id")
255 .ValueGeneratedOnAdd()
256 .HasColumnType("INTEGER")
257 .HasColumnName("id");
258
259 b.Property<DateTime>("CreatedAt")
260 .HasColumnType("TEXT")
261 .HasColumnName("created_at");
262
263 b.Property<string>("DefaultBranch")
264 .IsRequired()
265 .HasColumnType("TEXT")
266 .HasColumnName("default_branch");
267
268 b.Property<string>("Description")
269 .IsRequired()
270 .HasColumnType("TEXT")
271 .HasColumnName("description");
272
273 b.Property<string>("Name")
274 .IsRequired()
275 .HasColumnType("TEXT")
276 .HasColumnName("name")
277 .UseCollation("NOCASE");
278
279 b.Property<long>("OwnerId")
280 .HasColumnType("INTEGER")
281 .HasColumnName("owner_id");
282
283 b.Property<DateTime?>("PushedAt")
284 .HasColumnType("TEXT")
285 .HasColumnName("pushed_at");
286
287 b.Property<string>("Visibility")
288 .IsRequired()
289 .HasColumnType("TEXT")
290 .HasColumnName("visibility");
291
292 b.HasKey("Id");
293
294 b.HasIndex("OwnerId", "Name")
295 .IsUnique();
296
297 b.ToTable("repositories");
298 });
299
300 modelBuilder.Entity("Forge.Data.User", b =>
301 {
302 b.Property<long>("Id")
303 .ValueGeneratedOnAdd()
304 .HasColumnType("INTEGER")
305 .HasColumnName("id");
306
307 b.Property<DateTime>("CreatedAt")
308 .HasColumnType("TEXT")
309 .HasColumnName("created_at");
310
311 b.Property<string>("DisplayName")
312 .IsRequired()
313 .HasColumnType("TEXT")
314 .HasColumnName("display_name");
315
316 b.Property<string>("PasswordHash")
317 .IsRequired()
318 .HasColumnType("TEXT")
319 .HasColumnName("password_hash");
320
321 b.Property<string>("Username")
322 .IsRequired()
323 .HasColumnType("TEXT")
324 .HasColumnName("username")
325 .UseCollation("NOCASE");
326
327 b.HasKey("Id");
328
329 b.HasIndex("Username")
330 .IsUnique();
331
332 b.ToTable("users");
333 });
334
335 modelBuilder.Entity("Forge.Data.Webhook", b =>
336 {
337 b.Property<long>("Id")
338 .ValueGeneratedOnAdd()
339 .HasColumnType("INTEGER")
340 .HasColumnName("id");
341
342 b.Property<bool>("Active")
343 .HasColumnType("INTEGER")
344 .HasColumnName("active");
345
346 b.Property<DateTime>("CreatedAt")
347 .HasColumnType("TEXT")
348 .HasColumnName("created_at");
349
350 b.Property<long>("RepoId")
351 .HasColumnType("INTEGER")
352 .HasColumnName("repo_id");
353
354 b.Property<string>("Secret")
355 .IsRequired()
356 .HasColumnType("TEXT")
357 .HasColumnName("secret");
358
359 b.Property<string>("Url")
360 .IsRequired()
361 .HasColumnType("TEXT")
362 .HasColumnName("url");
363
364 b.HasKey("Id");
365
366 b.HasIndex("RepoId");
367
368 b.ToTable("webhooks");
369 });
370
371 modelBuilder.Entity("Forge.Data.WebhookDelivery", b =>
372 {
373 b.Property<long>("Id")
374 .ValueGeneratedOnAdd()
375 .HasColumnType("INTEGER")
376 .HasColumnName("id");
377
378 b.Property<int>("Attempt")
379 .HasColumnType("INTEGER")
380 .HasColumnName("attempt");
381
382 b.Property<DateTime>("DeliveredAt")
383 .HasColumnType("TEXT")
384 .HasColumnName("delivered_at");
385
386 b.Property<int>("DurationMs")
387 .HasColumnType("INTEGER")
388 .HasColumnName("duration_ms");
389
390 b.Property<string>("Error")
391 .HasColumnType("TEXT")
392 .HasColumnName("error");
393
394 b.Property<long?>("PushEventId")
395 .HasColumnType("INTEGER")
396 .HasColumnName("push_event_id");
397
398 b.Property<int?>("StatusCode")
399 .HasColumnType("INTEGER")
400 .HasColumnName("status_code");
401
402 b.Property<long>("WebhookId")
403 .HasColumnType("INTEGER")
404 .HasColumnName("webhook_id");
405
406 b.HasKey("Id");
407
408 b.HasIndex("PushEventId");
409
410 b.HasIndex("WebhookId", "PushEventId");
411
412 b.ToTable("webhook_deliveries");
413 });
414
415 modelBuilder.Entity("Forge.Data.AccessToken", b =>
416 {
417 b.HasOne("Forge.Data.User", "User")
418 .WithMany()
419 .HasForeignKey("UserId")
420 .OnDelete(DeleteBehavior.Cascade)
421 .IsRequired();
422
423 b.Navigation("User");
424 });
425
426 modelBuilder.Entity("Forge.Data.BranchProtection", b =>
427 {
428 b.HasOne("Forge.Data.Repository", "Repo")
429 .WithMany()
430 .HasForeignKey("RepoId")
431 .OnDelete(DeleteBehavior.Cascade)
432 .IsRequired();
433
434 b.Navigation("Repo");
435 });
436
437 modelBuilder.Entity("Forge.Data.PullRequest", b =>
438 {
439 b.HasOne("Forge.Data.User", "Author")
440 .WithMany()
441 .HasForeignKey("AuthorId")
442 .OnDelete(DeleteBehavior.Cascade)
443 .IsRequired();
444
445 b.HasOne("Forge.Data.Repository", "Repo")
446 .WithMany()
447 .HasForeignKey("RepoId")
448 .OnDelete(DeleteBehavior.Cascade)
449 .IsRequired();
450
451 b.Navigation("Author");
452
453 b.Navigation("Repo");
454 });
455
456 modelBuilder.Entity("Forge.Data.PullRequestComment", b =>
457 {
458 b.HasOne("Forge.Data.User", "Author")
459 .WithMany()
460 .HasForeignKey("AuthorId")
461 .OnDelete(DeleteBehavior.Cascade)
462 .IsRequired();
463
464 b.HasOne("Forge.Data.PullRequest", "PullRequest")
465 .WithMany()
466 .HasForeignKey("PullRequestId")
467 .OnDelete(DeleteBehavior.Cascade)
468 .IsRequired();
469
470 b.Navigation("Author");
471
472 b.Navigation("PullRequest");
473 });
474
475 modelBuilder.Entity("Forge.Data.PushEvent", b =>
476 {
477 b.HasOne("Forge.Data.Repository", "Repo")
478 .WithMany()
479 .HasForeignKey("RepoId")
480 .OnDelete(DeleteBehavior.Cascade)
481 .IsRequired();
482
483 b.Navigation("Repo");
484 });
485
486 modelBuilder.Entity("Forge.Data.Repository", b =>
487 {
488 b.HasOne("Forge.Data.User", "Owner")
489 .WithMany()
490 .HasForeignKey("OwnerId")
491 .OnDelete(DeleteBehavior.Cascade)
492 .IsRequired();
493
494 b.Navigation("Owner");
495 });
496
497 modelBuilder.Entity("Forge.Data.Webhook", b =>
498 {
499 b.HasOne("Forge.Data.Repository", "Repo")
500 .WithMany()
501 .HasForeignKey("RepoId")
502 .OnDelete(DeleteBehavior.Cascade)
503 .IsRequired();
504
505 b.Navigation("Repo");
506 });
507
508 modelBuilder.Entity("Forge.Data.WebhookDelivery", b =>
509 {
510 b.HasOne("Forge.Data.PushEvent", "PushEvent")
511 .WithMany()
512 .HasForeignKey("PushEventId")
513 .OnDelete(DeleteBehavior.Cascade);
514
515 b.HasOne("Forge.Data.Webhook", "Webhook")
516 .WithMany()
517 .HasForeignKey("WebhookId")
518 .OnDelete(DeleteBehavior.Cascade)
519 .IsRequired();
520
521 b.Navigation("PushEvent");
522
523 b.Navigation("Webhook");
524 });
525 #pragma warning restore 612, 618
526 }
527 }
added forge/Features/Auth/AccountRules.cs +36 −0View file
@@ -0,0 +1,36 @@
1 using System.Text.RegularExpressions;
2 using Forge.Localization;
3
4 namespace Forge.Features.Auth;
5
6 public static partial class AccountRules
7 {
8 public const int MinPasswordLength = 8;
9
10 /// <summary>Names that would collide with top-level routes.</summary>
11 private static readonly HashSet<string> Reserved = new(StringComparer.OrdinalIgnoreCase)
12 {
13 "login", "logout", "setup", "new", "settings", "status", "not-found", "error", "language", "lib", "api",
14 "admin", "assets", "static", "_framework", "_content",
15 };
16
17 /// <summary>Returns an English message (a translation key) for the user, or null when the username is acceptable.</summary>
18 public static string? ValidateUsername(string? username)
19 {
20 if (string.IsNullOrWhiteSpace(username) || !UsernamePattern().IsMatch(username))
21 {
22 return Localizer.Key("A username may contain letters, digits, hyphens and underscores (1 to 39 characters) and must start with a letter or digit.");
23 }
24
25 return Reserved.Contains(username) ? Localizer.Key("This username is reserved.") : null;
26 }
27
28 /// <summary>Returns an English message template with {0} for <see cref="MinPasswordLength"/>, or null.</summary>
29 public static string? ValidatePassword(string? password) =>
30 password is null || password.Length < MinPasswordLength
31 ? Localizer.Key("The password must be at least {0} characters long.")
32 : null;
33
34 [GeneratedRegex(@"^[A-Za-z0-9][A-Za-z0-9_-]{0,38}\z")]
35 private static partial Regex UsernamePattern();
36 }
added forge/Features/Auth/CurrentUser.cs +64 −0View file
@@ -0,0 +1,64 @@
1 using System.Globalization;
2 using System.Security.Claims;
3 using Forge.Data;
4 using Microsoft.AspNetCore.Authentication;
5 using Microsoft.AspNetCore.Authentication.Cookies;
6
7 namespace Forge.Features.Auth;
8
9 /// <summary>Who is asking: a user ID (null for anonymous) and whether the credential may write.</summary>
10 public readonly record struct Actor(long? UserId, bool MayWrite)
11 {
12 public static Actor Anonymous => new(null, false);
13 public bool IsAnonymous => UserId is null;
14 }
15
16 /// <summary>The signed-in user of the current web request, read from the auth cookie.</summary>
17 public sealed class CurrentUser(IHttpContextAccessor accessor)
18 {
19 private ClaimsPrincipal? Principal => accessor.HttpContext?.User;
20
21 public bool IsAuthenticated => UserId is not null;
22
23 public long? UserId =>
24 Principal?.Identity?.IsAuthenticated == true
25 && long.TryParse(
26 Principal.FindFirstValue(ClaimTypes.NameIdentifier),
27 NumberStyles.Integer,
28 CultureInfo.InvariantCulture,
29 out var id)
30 ? id
31 : null;
32
33 public string? Username => IsAuthenticated ? Principal?.FindFirstValue(ClaimTypes.Name) : null;
34
35 /// <summary>A browser session carries the user's full rights.</summary>
36 public Actor Actor => new(UserId, MayWrite: UserId is not null);
37
38 public static ClaimsPrincipal CreatePrincipal(User user)
39 {
40 var identity = new ClaimsIdentity(
41 [
42 new Claim(ClaimTypes.NameIdentifier, user.Id.ToString(CultureInfo.InvariantCulture)),
43 new Claim(ClaimTypes.Name, user.Username),
44 ],
45 CookieAuthenticationDefaults.AuthenticationScheme);
46 return new ClaimsPrincipal(identity);
47 }
48
49 public static Task SignInAsync(HttpContext context, User user) =>
50 context.SignInAsync(
51 CookieAuthenticationDefaults.AuthenticationScheme,
52 CreatePrincipal(user),
53 new AuthenticationProperties { IsPersistent = true });
54
55 /// <summary>Accepts only same-site relative paths, so a login link cannot bounce to another site.</summary>
56 public static string SafeReturnUrl(string? returnUrl) =>
57 !string.IsNullOrEmpty(returnUrl)
58 && returnUrl[0] == '/'
59 && (returnUrl.Length == 1 || (returnUrl[1] != '/' && returnUrl[1] != '\\'))
60 && !returnUrl.Contains('\r')
61 && !returnUrl.Contains('\n')
62 ? returnUrl
63 : "/";
64 }
added forge/Features/Auth/Login.razor +82 −0View file
@@ -0,0 +1,82 @@
1 @page "/login"
2 @attribute [EnableRateLimiting(ForgeApp.LoginRateLimit)]
3 @using Microsoft.AspNetCore.Identity
4 @inject ForgeDb Db
5 @inject IPasswordHasher<User> Hasher
6 @inject IHttpContextAccessor Http
7 @inject NavigationManager Nav
8
9 <PageTitle>@T["Sign in"] · Forge</PageTitle>
10
11 <section class="narrow">
12 <div class="auth-logo"><Icon Name="logo" Size="36" Class="logo-mark"/></div>
13 <h1>@T["Sign in"]</h1>
14
15 @if (_error is not null)
16 {
17 <p class="alert error">@_error</p>
18 }
19
20 <form method="post" @formname="login" @onsubmit="SignInAsync" class="form">
21 <AntiforgeryToken/>
22 <label>
23 @T["Username"]
24 <input name="Username" value="@Username" required autocomplete="username" autofocus/>
25 </label>
26 <label>
27 @T["Password"]
28 <input name="Password" type="password" required autocomplete="current-password"/>
29 </label>
30 <button type="submit" class="button primary">@T["Sign in"]</button>
31 </form>
32 </section>
33
34 @code {
35 [SupplyParameterFromForm]
36 private string? Username { get; set; }
37
38 [SupplyParameterFromForm]
39 private string? Password { get; set; }
40
41 [SupplyParameterFromQuery(Name = "returnUrl")]
42 private string? ReturnUrl { get; set; }
43
44 private string? _error;
45
46 protected override async Task OnInitializedAsync()
47 {
48 if (!await Db.Users.AnyAsync())
49 {
50 Nav.NavigateTo("/setup");
51 }
52 }
53
54 private async Task SignInAsync()
55 {
56 var username = Username?.Trim() ?? "";
57 var user = await Db.Users.FirstOrDefaultAsync(u => u.Username == username);
58
59 // Hash even when the user does not exist, so the response time does not reveal which names are real.
60 var probe = user ?? new User { Username = "", DisplayName = "" };
61 var hash = user?.PasswordHash ?? DummyHash.Value;
62 var result = Hasher.VerifyHashedPassword(probe, hash, Password ?? "");
63
64 if (user is null || result == PasswordVerificationResult.Failed)
65 {
66 _error = T["Wrong username or password."];
67 return;
68 }
69
70 if (result == PasswordVerificationResult.SuccessRehashNeeded)
71 {
72 user.PasswordHash = Hasher.HashPassword(user, Password!);
73 await Db.SaveChangesAsync();
74 }
75
76 await CurrentUser.SignInAsync(Http.HttpContext!, user);
77 Nav.NavigateTo(CurrentUser.SafeReturnUrl(ReturnUrl));
78 }
79
80 private static readonly Lazy<string> DummyHash = new(() =>
81 new PasswordHasher<User>().HashPassword(new User { Username = "", DisplayName = "" }, Guid.NewGuid().ToString()));
82 }
added forge/Features/Auth/RepoAccess.cs +22 −0View file
@@ -0,0 +1,22 @@
1 using Forge.Data;
2
3 namespace Forge.Features.Auth;
4
5 /// <summary>
6 /// The only place that decides who may do what with a repository.
7 /// Callers turn "cannot read" into 404 (never 403), so a private repo is indistinguishable from a missing one.
8 /// </summary>
9 public static class RepoAccess
10 {
11 public static bool CanRead(Repository repo, Actor actor) =>
12 repo.Visibility == Visibility.Public || IsOwner(repo, actor);
13
14 public static bool CanWrite(Repository repo, Actor actor) =>
15 IsOwner(repo, actor) && actor.MayWrite;
16
17 /// <summary>Settings, webhooks and deletion. Same rule as writing today; kept separate so it can diverge.</summary>
18 public static bool CanAdmin(Repository repo, Actor actor) => CanWrite(repo, actor);
19
20 private static bool IsOwner(Repository repo, Actor actor) =>
21 actor.UserId is { } id && id == repo.OwnerId;
22 }
added forge/Features/Auth/Setup.razor +119 −0View file
@@ -0,0 +1,119 @@
1 @page "/setup"
2 @attribute [EnableRateLimiting(ForgeApp.LoginRateLimit)]
3 @using Microsoft.AspNetCore.Identity
4 @inject ForgeDb Db
5 @inject IPasswordHasher<User> Hasher
6 @inject IHttpContextAccessor Http
7 @inject NavigationManager Nav
8
9 @if (_open)
10 {
11 <PageTitle>@T["First run"] · Forge</PageTitle>
12
13 <section class="narrow">
14 <div class="auth-logo"><Icon Name="logo" Size="36" Class="logo-mark"/></div>
15 <h1>@T["Welcome to Forge"]</h1>
16 <p class="muted">@T["Create your account. This page then closes for good."]</p>
17
18 @if (_error is not null)
19 {
20 <p class="alert error">@_error</p>
21 }
22
23 <form method="post" @formname="setup" @onsubmit="CreateAsync" class="form">
24 <AntiforgeryToken/>
25 <label>
26 @T["Username"]
27 <input name="Username" value="@Username" required maxlength="39" autocomplete="username" autofocus/>
28 <small class="muted">@T["It becomes part of your repository addresses."]</small>
29 </label>
30 <label>
31 @T["Display name"]
32 <input name="DisplayName" value="@DisplayName" maxlength="100" autocomplete="name"/>
33 </label>
34 <label>
35 @T["Password"]
36 <input name="Password" type="password" required minlength="@AccountRules.MinPasswordLength" autocomplete="new-password"/>
37 </label>
38 <label>
39 @T["Repeat password"]
40 <input name="PasswordRepeat" type="password" required autocomplete="new-password"/>
41 </label>
42 <button type="submit" class="button primary">@T["Create account"]</button>
43 </form>
44 </section>
45 }
46
47 @code {
48 [SupplyParameterFromForm]
49 private string? Username { get; set; }
50
51 [SupplyParameterFromForm]
52 private string? DisplayName { get; set; }
53
54 [SupplyParameterFromForm]
55 private string? Password { get; set; }
56
57 [SupplyParameterFromForm]
58 private string? PasswordRepeat { get; set; }
59
60 private bool _open;
61 private string? _error;
62
63 protected override async Task OnInitializedAsync()
64 {
65 // Setup exists only while there is no account at all.
66 if (await Db.Users.AnyAsync())
67 {
68 Nav.NotFound();
69 return;
70 }
71
72 _open = true;
73 }
74
75 private async Task CreateAsync()
76 {
77 if (!_open)
78 {
79 return;
80 }
81
82 var username = Username?.Trim();
83 var invalid = AccountRules.ValidateUsername(username)
84 ?? AccountRules.ValidatePassword(Password)
85 ?? (Password != PasswordRepeat ? Localizer.Key("The passwords do not match.") : null);
86 if (invalid is not null)
87 {
88 // The rules return English templates; {0}, where present, is the minimum password length.
89 _error = T[invalid, AccountRules.MinPasswordLength];
90 return;
91 }
92
93 var user = new User
94 {
95 Username = username!,
96 DisplayName = string.IsNullOrWhiteSpace(DisplayName) ? username! : DisplayName.Trim(),
97 CreatedAt = DateTime.UtcNow,
98 };
99 user.PasswordHash = Hasher.HashPassword(user, Password!);
100
101 // The check and the insert share one write transaction, so two simultaneous setups cannot both win.
102 await using (var transaction = await Db.Database.BeginTransactionAsync())
103 {
104 if (await Db.Users.AnyAsync())
105 {
106 _open = false;
107 Nav.NotFound();
108 return;
109 }
110
111 Db.Users.Add(user);
112 await Db.SaveChangesAsync();
113 await transaction.CommitAsync();
114 }
115
116 await CurrentUser.SignInAsync(Http.HttpContext!, user);
117 Nav.NavigateTo("/");
118 }
119 }
added forge/Features/Auth/TokenService.cs +105 −0View file
@@ -0,0 +1,105 @@
1 using System.Collections.Concurrent;
2 using System.Security.Cryptography;
3 using System.Text;
4 using Forge.Data;
5 using Microsoft.EntityFrameworkCore;
6
7 namespace Forge.Features.Auth;
8
9 public sealed class TokenService(ForgeDb db)
10 {
11 public const string Prefix = "forge_";
12
13 /// <summary>Creates a token and returns its plaintext. This is the only moment the plaintext exists.</summary>
14 public async Task<(AccessToken Token, string Plaintext)> CreateAsync(
15 long userId,
16 string name,
17 bool canWrite,
18 DateTime? expiresAt,
19 CancellationToken ct = default)
20 {
21 var plaintext = Prefix + Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(32));
22 var token = new AccessToken
23 {
24 UserId = userId,
25 Name = name,
26 TokenHash = Hash(plaintext),
27 CanWrite = canWrite,
28 CreatedAt = DateTime.UtcNow,
29 ExpiresAt = expiresAt,
30 };
31 db.AccessTokens.Add(token);
32 await db.SaveChangesAsync(ct);
33 return (token, plaintext);
34 }
35
36 /// <summary>Returns the token row for a presented plaintext, or null when it is unknown or expired.</summary>
37 public async Task<AccessToken?> ValidateAsync(string? plaintext, CancellationToken ct = default)
38 {
39 if (string.IsNullOrEmpty(plaintext) || plaintext.Length > 200)
40 {
41 return null;
42 }
43
44 var hash = Hash(plaintext);
45 var token = await db.AccessTokens.FirstOrDefaultAsync(t => t.TokenHash == hash, ct);
46 if (token is null || (token.ExpiresAt is { } expires && expires <= DateTime.UtcNow))
47 {
48 return null;
49 }
50
51 // One clone is several requests; a write per minute is plenty for "last used".
52 var now = DateTime.UtcNow;
53 if (token.LastUsedAt is null || now - token.LastUsedAt.Value > TimeSpan.FromMinutes(1))
54 {
55 token.LastUsedAt = now;
56 await db.SaveChangesAsync(ct);
57 }
58
59 return token;
60 }
61
62 public static string Hash(string plaintext) =>
63 Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(plaintext)));
64 }
65
66 /// <summary>
67 /// Throttles Basic auth on the git endpoints by counting failed attempts per client address.
68 /// Counting failures (rather than all requests) leaves normal clones and pushes untouched.
69 /// </summary>
70 public sealed class AuthFailureLimiter(TimeProvider time)
71 {
72 public const int MaxFailures = 10;
73 public static readonly TimeSpan Window = TimeSpan.FromMinutes(5);
74
75 private readonly ConcurrentDictionary<string, Entry> _entries = new();
76
77 public bool IsBlocked(string client) =>
78 _entries.TryGetValue(client, out var entry)
79 && entry.WindowStart + Window > time.GetUtcNow()
80 && entry.Failures >= MaxFailures;
81
82 public void RecordFailure(string client)
83 {
84 var now = time.GetUtcNow();
85 _entries.AddOrUpdate(
86 client,
87 _ => new Entry(now, 1),
88 (_, existing) => existing.WindowStart + Window > now
89 ? existing with { Failures = existing.Failures + 1 }
90 : new Entry(now, 1));
91
92 if (_entries.Count > 10_000)
93 {
94 foreach (var (key, entry) in _entries)
95 {
96 if (entry.WindowStart + Window <= now)
97 {
98 _entries.TryRemove(key, out _);
99 }
100 }
101 }
102 }
103
104 private sealed record Entry(DateTimeOffset WindowStart, int Failures);
105 }
added forge/Features/Auth/Tokens.razor +178 −0View file
@@ -0,0 +1,178 @@
1 @page "/settings/tokens"
2 @attribute [Authorize]
3 @inject ForgeDb Db
4 @inject TokenService TokenService
5 @inject CurrentUser Me
6
7 <PageTitle>@T["Access tokens"] · Forge</PageTitle>
8
9 <h1>@T["Access tokens"]</h1>
10 <p class="muted">@T.Html("A token is the password for <code>git clone</code> and <code>git push</code> over HTTPS. Any username works.")</p>
11
12 @if (_created is not null)
13 {
14 <div class="alert success">
15 <p><strong>@T["The token is created. Copy it now, it will not be shown again."]</strong></p>
16 <CloneBox Url="@_created"/>
17 </div>
18 }
19
20 @if (_error is not null)
21 {
22 <p class="alert error">@_error</p>
23 }
24
25 <section class="card">
26 <h2>@T["New token"]</h2>
27 <form method="post" @formname="create-token" @onsubmit="CreateAsync" class="form">
28 <AntiforgeryToken/>
29 <label>
30 @T["Name"]
31 <input name="Name" value="@Name" required maxlength="100" placeholder="@T["e.g. laptop"]"/>
32 </label>
33 <label>
34 @T["Permission"]
35 <select name="Scope">
36 <option value="read">@T["Read only (clone, fetch)"]</option>
37 <option value="write">@T["Read and write (push)"]</option>
38 </select>
39 </label>
40 <label>
41 @T["Expires"]
42 <select name="ExpiresInDays">
43 <option value="30">@T["30 days"]</option>
44 <option value="90" selected>@T["90 days"]</option>
45 <option value="365">@T["1 year"]</option>
46 <option value="0">@T["No expiry"]</option>
47 </select>
48 </label>
49 <button type="submit" class="button primary">@T["Create token"]</button>
50 </form>
51 </section>
52
53 <section>
54 <h2>@T["Existing tokens"]</h2>
55 @if (_tokens.Count == 0)
56 {
57 <p class="muted">@T["You have no tokens yet."]</p>
58 }
59 else
60 {
61 <form method="post" @formname="revoke-token" @onsubmit="RevokeAsync">
62 <AntiforgeryToken/>
63 <table class="table">
64 <thead>
65 <tr>
66 <th>@T["Name"]</th>
67 <th>@T["Permission"]</th>
68 <th>@T["Created"]</th>
69 <th>@T["Last used"]</th>
70 <th>@T["Valid until"]</th>
71 <th></th>
72 </tr>
73 </thead>
74 <tbody>
75 @foreach (var token in _tokens)
76 {
77 <tr>
78 <td>@token.Name</td>
79 <td>@(token.CanWrite ? T["read and write"] : T["read only"])</td>
80 <td><TimeAgo Value="Format.Utc(token.CreatedAt)"/></td>
81 <td>
82 @if (token.LastUsedAt is { } used)
83 {
84 <TimeAgo Value="Format.Utc(used)"/>
85 }
86 else
87 {
88 <span class="muted">@T["never"]</span>
89 }
90 </td>
91 <td>
92 @if (token.ExpiresAt is not { } expires)
93 {
94 <span class="muted">@T["no expiry"]</span>
95 }
96 else if (expires <= DateTime.UtcNow)
97 {
98 <span class="danger-text">@T["expired {0}", Format.ExactTime(Format.Utc(expires))]</span>
99 }
100 else
101 {
102 <span>@Format.ExactTime(Format.Utc(expires))</span>
103 }
104 </td>
105 <td class="right">
106 <button type="submit" name="TokenId" value="@token.Id" class="button danger small">@T["Revoke"]</button>
107 </td>
108 </tr>
109 }
110 </tbody>
111 </table>
112 </form>
113 }
114 </section>
115
116 @code {
117 [SupplyParameterFromForm(FormName = "create-token")]
118 private string? Name { get; set; }
119
120 [SupplyParameterFromForm(FormName = "create-token")]
121 private string? Scope { get; set; }
122
123 [SupplyParameterFromForm(FormName = "create-token")]
124 private int? ExpiresInDays { get; set; }
125
126 [SupplyParameterFromForm(FormName = "revoke-token")]
127 private long? TokenId { get; set; }
128
129 private List<AccessToken> _tokens = [];
130 private string? _created;
131 private string? _error;
132
133 protected override Task OnInitializedAsync() => LoadAsync();
134
135 private async Task LoadAsync()
136 {
137 var userId = Me.UserId;
138 _tokens = await Db.AccessTokens
139 .Where(t => t.UserId == userId)
140 .OrderByDescending(t => t.CreatedAt)
141 .ToListAsync();
142 }
143
144 private async Task CreateAsync()
145 {
146 var name = Name?.Trim();
147 if (string.IsNullOrEmpty(name) || name.Length > 100)
148 {
149 _error = T["Enter a token name (at most 100 characters)."];
150 return;
151 }
152
153 if (ExpiresInDays is not (0 or 30 or 90 or 365))
154 {
155 _error = T["Choose an expiry from the list."];
156 return;
157 }
158
159 DateTime? expiresAt = ExpiresInDays == 0 ? null : DateTime.UtcNow.AddDays(ExpiresInDays.Value);
160 var (_, plaintext) = await TokenService.CreateAsync(Me.UserId!.Value, name, Scope == "write", expiresAt);
161 _created = plaintext;
162 Name = null;
163 await LoadAsync();
164 }
165
166 private async Task RevokeAsync()
167 {
168 var userId = Me.UserId;
169 var token = await Db.AccessTokens.FirstOrDefaultAsync(t => t.Id == TokenId && t.UserId == userId);
170 if (token is not null)
171 {
172 Db.AccessTokens.Remove(token);
173 await Db.SaveChangesAsync();
174 }
175
176 await LoadAsync();
177 }
178 }
added forge/Features/Browse/Activity.razor +168 −0View file
@@ -0,0 +1,168 @@
1 @page "/{Owner}/{Repo}/activity"
2 @inherits RepoPageBase
3 @inject RepoInsights Insights
4 @inject TimeProvider Clock
5
6 @if (Repository is not null && _activity is not null)
7 {
8 <PageTitle>@T["Activity"] · @Repository.Owner.Username/@Repository.Name</PageTitle>
9
10 <RepoHeader Repository="Repository" Active="activity" IsOwner="IsOwner"/>
11
12 <p class="muted activity-scope">
13 <Icon Name="branch" Size="14"/> @T["Activity on {0}", _branch]
14 @if (_activity.Truncated)
15 {
16 <span> · @T["Only the newest {0} commits are counted.", RepoInsights.MaxActivityCommits.ToString("N0", CultureInfo.CurrentCulture)]</span>
17 }
18 </p>
19
20 <dl class="stat-tiles">
21 <div class="stat-tile">
22 <dt>@T["Commits"]</dt>
23 <dd>@Number(_activity.Commits)</dd>
24 </div>
25 <div class="stat-tile">
26 <dt>@T["Contributors"]</dt>
27 <dd>@Number(_activity.Contributors.Count)</dd>
28 </div>
29 <div class="stat-tile">
30 <dt>@T["Commits in the last 30 days"]</dt>
31 <dd>@Number(_recent)</dd>
32 </div>
33 <div class="stat-tile">
34 <dt>@T["First commit"]</dt>
35 <dd class="stat-date">@_first.ToString("d MMM yyyy", CultureInfo.CurrentCulture)</dd>
36 </div>
37 </dl>
38
39 <section class="card">
40 <h2>@T["Commits per week"]</h2>
41 <p class="muted small chart-sub">@T["The last 52 weeks, {0} in total", T.Plural(_weeks.Sum(w => w.Count), "{0} commit", "{0} commits")]</p>
42 <div class="chart-scroll">
43 @* One series, so no legend: the heading names it. Every week has a tooltip on a full-height hit area. *@
44 <svg class="week-chart" viewBox="0 0 @ChartWidth @ChartHeight" role="img" aria-label="@T["Commits per week"]">
45 <line class="chart-grid" x1="@Left" x2="@ChartWidth" y1="@Top" y2="@Top"/>
46 <line class="chart-grid" x1="@Left" x2="@ChartWidth" y1="@(Top + PlotHeight / 2)" y2="@(Top + PlotHeight / 2)"/>
47 <line class="chart-axis" x1="@Left" x2="@ChartWidth" y1="@Baseline" y2="@Baseline"/>
48 <text class="chart-label" x="@(Left - 6)" y="@(Top + 4)" text-anchor="end">@_scaleMax</text>
49 <text class="chart-label" x="@(Left - 6)" y="@(Top + PlotHeight / 2 + 4)" text-anchor="end">@(_scaleMax / 2)</text>
50 <text class="chart-label" x="@(Left - 6)" y="@(Baseline + 4)" text-anchor="end">0</text>
51 @for (var i = 0; i < _weeks.Count; i++)
52 {
53 var week = _weeks[i];
54 var x = Left + i * Step + 2;
55 var height = week.Count == 0 ? 0 : Math.Max(2.0, (double)week.Count / _scaleMax * PlotHeight);
56 <g class="week">
57 <title>@T["Week of {0}", week.Start.ToString("d MMM yyyy", CultureInfo.CurrentCulture)]: @T.Plural(week.Count, "{0} commit", "{0} commits")</title>
58 <rect class="week-hit" x="@(x - 2)" y="@Top" width="@Step" height="@PlotHeight"/>
59 @if (week.Count > 0)
60 {
61 <rect class="week-bar" x="@x" y="@Coordinate(Baseline - height)" width="@BarWidth" height="@Coordinate(height)" rx="2"/>
62 }
63 </g>
64 @if (i > 0 && week.Start.Month != _weeks[i - 1].Start.Month && i < _weeks.Count - 2)
65 {
66 @* Inside a <g>: directly in a code block Razor would take <text> for its own text tag. *@
67 <g><text class="chart-label" x="@x" y="@(Baseline + 16)">@week.Start.ToString("MMM", CultureInfo.CurrentCulture)</text></g>
68 }
69 }
70 </svg>
71 </div>
72 </section>
73
74 <h2 class="section-title">@T["Contributors"] <Counter Value="_activity.Contributors.Count"/></h2>
75 <ol class="contributor-list">
76 @foreach (var person in _activity.Contributors.Take(MaxContributors))
77 {
78 <li class="contributor">
79 <Avatar Name="@person.Name" Size="md"/>
80 <div class="contributor-main">
81 <strong>@person.Name</strong>
82 <div class="muted small">@T["Last commit"] <TimeAgo Value="person.Last"/></div>
83 </div>
84 <div class="contributor-share">
85 <span class="small">@T.Plural(person.Commits, "{0} commit", "{0} commits")</span>
86 <svg class="share-bar" viewBox="0 0 100 6" preserveAspectRatio="none" width="100%" height="6" aria-hidden="true">
87 <rect x="0" y="0" height="6" width="@Coordinate(100.0 * person.Commits / _activity.Commits)"/>
88 </svg>
89 </div>
90 </li>
91 }
92 </ol>
93 @if (_activity.Contributors.Count > MaxContributors)
94 {
95 <p class="muted small">@T["Only the first {0} contributors are shown.", MaxContributors]</p>
96 }
97 }
98
99 @code {
100 private const int WeekCount = 52;
101 private const int MaxContributors = 100;
102
103 // Chart geometry in SVG user units.
104 private const int Left = 34;
105 private const int Top = 8;
106 private const int PlotHeight = 120;
107 private const int Step = 14;
108 private const int BarWidth = 10;
109 private const int Baseline = Top + PlotHeight;
110 private const int ChartWidth = Left + WeekCount * Step;
111 private const int ChartHeight = Baseline + 24;
112
113 private sealed record Week(DateOnly Start, int Count);
114
115 private RepoActivity? _activity;
116 private string _branch = "";
117 private List<Week> _weeks = [];
118 private int _scaleMax = 4;
119 private int _recent;
120 private DateTimeOffset _first;
121
122 private static string Number(int value) => value.ToString("N0", CultureInfo.CurrentCulture);
123
124 private static string Coordinate(double value) => value.ToString("0.##", CultureInfo.InvariantCulture);
125
126 protected override async Task OnInitializedAsync()
127 {
128 if (!await LoadRepoAsync())
129 {
130 return;
131 }
132
133 var repo = Repository!;
134 var refs = await Git.ListRefsAsync(RepoPath);
135 var branch = refs.FirstOrDefault(r => r.Kind == RefKind.Branch && r.Name == repo.DefaultBranch)
136 ?? refs.FirstOrDefault(r => r.Kind == RefKind.Branch);
137 if (branch is null)
138 {
139 Redirect(Urls.Repo(repo));
140 return;
141 }
142
143 _branch = branch.Name;
144 var activity = await Insights.GetActivityAsync(RepoPath, branch.TargetSha);
145 _first = activity.Contributors.Count == 0 ? default : activity.Contributors.Min(c => c.First);
146
147 // Weeks run Monday to Sunday (UTC); the last one is the current week.
148 var today = DateOnly.FromDateTime(Clock.GetUtcNow().UtcDateTime);
149 var thisMonday = today.AddDays(-(((int)today.DayOfWeek + 6) % 7));
150 for (var i = WeekCount - 1; i >= 0; i--)
151 {
152 var start = thisMonday.AddDays(-7 * i);
153 var count = 0;
154 for (var day = 0; day < 7; day++)
155 {
156 count += activity.CommitsByDay.GetValueOrDefault(start.AddDays(day));
157 }
158
159 _weeks.Add(new Week(start, count));
160 }
161
162 // An even maximum, so the half-way grid line has a whole-number label.
163 var max = Math.Max(4, _weeks.Max(w => w.Count));
164 _scaleMax = max + max % 2;
165 _recent = activity.CommitsByDay.Where(p => p.Key > today.AddDays(-30)).Sum(p => p.Value);
166 _activity = activity;
167 }
168 }
added forge/Features/Browse/Blob.razor +193 −0View file
@@ -0,0 +1,193 @@
1 @page "/{Owner}/{Repo}/blob/{*RefAndPath}"
2 @inherits RepoPageBase
3 @inject ContentCache Cache
4 @inject MarkdownRenderer Markdown
5
6 @if (Repository is not null && _resolved is not null && _entry is not null)
7 {
8 <PageTitle>@_resolved.Path · @Repository.Owner.Username/@Repository.Name</PageTitle>
9 @if (_text is not null && _language is not null)
10 {
11 @* Syntax highlighting is loaded on file pages only, and only from this server. *@
12 <HighlightAssets/>
13 }
14
15 <RepoHeader Repository="Repository" Active="code" IsOwner="IsOwner"/>
16
17 <div class="toolbar">
18 <RefSwitcher Refs="_refs" Current="@_resolved.Name" CurrentKind="_resolved.Kind"
19 UrlFor="@(name => Urls.Blob(Repository, name, _resolved.Path))"/>
20 <Breadcrumbs Repository="Repository" RefName="@_resolved.Name" Path="@_resolved.Path"/>
21 </div>
22
23 <div class="file-head">
24 <span class="file-info">
25 <Icon Name="file"/>
26 <strong class="file-name">@_entry.Name</strong>
27 <span class="muted small">
28 @Format.Size(_size)
29 @if (_text is not null)
30 {
31 <span> · @T.Plural(_lineCount, "{0} line", "{0} lines")</span>
32 }
33 </span>
34 </span>
35 <span class="file-actions">
36 @if (_canPreview)
37 {
38 <nav class="segmented">
39 <a class="@(ShowPreview ? "active" : "")" href="@Urls.Blob(Repository, _resolved.Name, _resolved.Path)">@T["Preview"]</a>
40 <a class="@(ShowPreview ? "" : "active")" href="@Urls.Blob(Repository, _resolved.Name, _resolved.Path)?plain=1">@T["Code"]</a>
41 </nav>
42 }
43 @if (_text is { Length: > 0 } && !ShowPreview)
44 {
45 <button type="button" class="button small js-only" data-copy-from="blob-code" data-copied-label="@T["Copied"]">
46 <Icon Name="copy" Size="14"/> <span class="copy-label">@T["Copy"]</span>
47 </button>
48 }
49 <a class="button small" href="@Urls.Raw(Repository, _resolved.Name, _resolved.Path)">@T["Raw"]</a>
50 @if (_resolved.Kind != ResolvedKind.Commit)
51 {
52 <a class="button small" href="@Urls.Blob(Repository, _resolved.CommitSha, _resolved.Path)" data-hotkey="y"
53 title="@T["A link to this exact version of the file"]">@T["Permalink"]</a>
54 }
55 <a class="button small" href="@Urls.Commits(Repository, _resolved.Name, _resolved.Path)">@T["History"]</a>
56 </span>
57 </div>
58
59 @if (_tooLarge)
60 {
61 <div class="card empty">
62 <p>@T["The file is {0} and too large to display.", Format.Size(_size)]</p>
63 <p><a href="@Urls.Raw(Repository, _resolved.Name, _resolved.Path)">@T["Open raw"]</a></p>
64 </div>
65 }
66 else if (_imageType is not null)
67 {
68 <div class="card image-view">
69 <img src="@Urls.Raw(Repository, _resolved.Name, _resolved.Path)" alt="@_entry.Name"/>
70 </div>
71 }
72 else if (_text is null)
73 {
74 <div class="card empty">
75 <p>@T["A binary file cannot be displayed."]</p>
76 <p><a href="@Urls.Raw(Repository, _resolved.Name, _resolved.Path)">@T["Download"]</a></p>
77 </div>
78 }
79 else if (_text.Length == 0)
80 {
81 <div class="card empty"><p>@T["The file is empty."]</p></div>
82 }
83 else if (ShowPreview)
84 {
85 <article class="card file-preview">
86 <div class="markdown">@((MarkupString)_previewHtml!)</div>
87 </article>
88 }
89 else
90 {
91 <div class="code-view">
92 <pre class="line-numbers" aria-hidden="true">@for (var n = 1; n <= _lineCount; n++)
93 {<a id="L@(n)" href="#L@(n)">@n</a>}</pre>
94 <pre class="code"><code id="blob-code" class="@(_language is null ? "nohighlight" : "language-" + _language)" data-highlight="@_language">@_text</code></pre>
95 </div>
96 }
97 }
98
99 @code {
100 [Parameter]
101 public string? RefAndPath { get; set; }
102
103 private IReadOnlyList<GitRef> _refs = [];
104 private ResolvedRef? _resolved;
105 private TreeEntry? _entry;
106 private long _size;
107 private bool _tooLarge;
108 private string? _imageType;
109 private string? _text;
110 private string? _language;
111 private int _lineCount;
112 private bool _canPreview;
113 private string? _previewHtml;
114
115 /// <summary>?plain=1 shows the source of a Markdown file instead of rendering it.</summary>
116 [SupplyParameterFromQuery(Name = "plain")]
117 private string? Plain { get; set; }
118
119 private bool ShowPreview => _previewHtml is not null && Plain != "1";
120
121 protected override async Task OnInitializedAsync()
122 {
123 if (!await LoadRepoAsync())
124 {
125 return;
126 }
127
128 var repo = Repository!;
129 _refs = await Git.ListRefsAsync(RepoPath);
130 _resolved = await Resolver.ResolveAsync(RepoPath, RefAndPath, _refs);
131 if (_resolved is null)
132 {
133 NotFound();
134 return;
135 }
136
137 if (_resolved.Path.Length == 0)
138 {
139 Redirect(Urls.Tree(repo, _resolved.Name));
140 return;
141 }
142
143 _entry = await Git.GetEntryAsync(RepoPath, _resolved.CommitSha, _resolved.Path);
144 if (_entry is { IsTree: true })
145 {
146 Redirect(Urls.Tree(repo, _resolved.Name, _resolved.Path));
147 return;
148 }
149
150 if (_entry is not { IsBlob: true })
151 {
152 NotFound();
153 return;
154 }
155
156 _size = _entry.Size ?? await Git.GetBlobSizeAsync(RepoPath, _entry.Sha);
157 if (_size > FileTypes.MaxRenderBytes)
158 {
159 _tooLarge = true;
160 return;
161 }
162
163 var blob = await Git.ReadBlobAsync(RepoPath, _entry.Sha, FileTypes.MaxRenderBytes);
164 if (blob.IsBinary)
165 {
166 // Only the known-safe image types are embedded; the raw endpoint serves them with the right type.
167 _imageType = FileTypes.InlineImageType(_entry.Name);
168 return;
169 }
170
171 _text = blob.Text.Replace("\r\n", "\n");
172 _language = FileTypes.Language(_entry.Name);
173 _lineCount = _text.Length == 0
174 ? 0
175 : _text.AsSpan().Count('\n') + (_text.EndsWith('\n') ? 0 : 1);
176
177 if (FileTypes.IsMarkdown(_entry.Name) && _text.Length > 0 && _size <= FileTypes.MaxReadmeBytes)
178 {
179 _canPreview = true;
180 var slash = _resolved.Path.LastIndexOf('/');
181 var links = new LinkContext(
182 Urls.Raw(repo, _resolved.Name, ""),
183 Urls.Blob(repo, _resolved.Name, ""),
184 slash < 0 ? "" : _resolved.Path[..slash]);
185 var text = _text;
186 // The same key as the README on the tree page: the HTML depends on the blob and on where relative links point.
187 _previewHtml = await Cache.GetOrCreateAsync(
188 $"readme:{_entry.Sha}:True:{links.RawBase}:{links.Directory}",
189 () => Task.FromResult(Markdown.Render(text, links)),
190 html => html.Length * 2L);
191 }
192 }
193 }
added forge/Features/Browse/ContentCache.cs +34 −0View file
@@ -0,0 +1,34 @@
1 using Microsoft.Extensions.Caching.Memory;
2
3 namespace Forge.Features.Browse;
4
5 /// <summary>
6 /// Cache for things derived from git objects. Keys include the object's SHA, and content under
7 /// a SHA never changes, so entries never need invalidating; they only age out to bound memory.
8 /// It owns its <see cref="MemoryCache"/> so the size limit applies to these entries alone.
9 /// </summary>
10 public sealed class ContentCache : IDisposable
11 {
12 private readonly MemoryCache _cache = new(new MemoryCacheOptions { SizeLimit = 64 * 1024 * 1024 });
13
14 public IMemoryCache Cache => _cache;
15
16 public async Task<T> GetOrCreateAsync<T>(string key, Func<Task<T>> create, Func<T, long> sizeOf)
17 where T : notnull
18 {
19 if (_cache.TryGetValue(key, out T? cached) && cached is not null)
20 {
21 return cached;
22 }
23
24 var value = await create();
25 _cache.Set(key, value, new MemoryCacheEntryOptions
26 {
27 Size = Math.Max(1, sizeOf(value)),
28 SlidingExpiration = TimeSpan.FromHours(6),
29 });
30 return value;
31 }
32
33 public void Dispose() => _cache.Dispose();
34 }
added forge/Features/Browse/FileTypes.cs +80 −0View file
@@ -0,0 +1,80 @@
1 namespace Forge.Features.Browse;
2
3 public static class FileTypes
4 {
5 public const long MaxRenderBytes = 1024 * 1024;
6 public const long MaxReadmeBytes = 512 * 1024;
7
8 /// <summary>Image types that are safe to show inline. SVG is deliberately absent: it can carry script.</summary>
9 private static readonly Dictionary<string, string> InlineImages = new(StringComparer.OrdinalIgnoreCase)
10 {
11 [".png"] = "image/png",
12 [".jpg"] = "image/jpeg",
13 [".jpeg"] = "image/jpeg",
14 [".gif"] = "image/gif",
15 [".webp"] = "image/webp",
16 };
17
18 /// <summary>File extension → highlight.js language name (languages in the "common" bundle).</summary>
19 private static readonly Dictionary<string, string> Languages = new(StringComparer.OrdinalIgnoreCase)
20 {
21 [".cs"] = "csharp", [".csx"] = "csharp", [".razor"] = "xml", [".cshtml"] = "xml",
22 [".csproj"] = "xml", [".props"] = "xml", [".targets"] = "xml", [".slnx"] = "xml",
23 [".xml"] = "xml", [".html"] = "xml", [".htm"] = "xml", [".svg"] = "xml", [".xaml"] = "xml",
24 [".js"] = "javascript", [".mjs"] = "javascript", [".cjs"] = "javascript", [".jsx"] = "javascript",
25 [".ts"] = "typescript", [".tsx"] = "typescript",
26 [".json"] = "json", [".yml"] = "yaml", [".yaml"] = "yaml", [".toml"] = "ini", [".ini"] = "ini",
27 [".css"] = "css", [".scss"] = "scss", [".less"] = "less",
28 [".md"] = "markdown", [".markdown"] = "markdown",
29 [".py"] = "python", [".rb"] = "ruby", [".go"] = "go", [".rs"] = "rust",
30 [".java"] = "java", [".kt"] = "kotlin", [".kts"] = "kotlin", [".swift"] = "swift",
31 [".c"] = "c", [".h"] = "c", [".cpp"] = "cpp", [".cc"] = "cpp", [".hpp"] = "cpp",
32 [".m"] = "objectivec", [".php"] = "php", [".pl"] = "perl", [".lua"] = "lua", [".r"] = "r",
33 [".sh"] = "bash", [".bash"] = "bash", [".zsh"] = "bash", [".ps1"] = "powershell",
34 [".sql"] = "sql", [".diff"] = "diff", [".patch"] = "diff", [".vb"] = "vbnet",
35 [".graphql"] = "graphql", [".wasm"] = "wasm",
36 };
37
38 private static readonly Dictionary<string, string> LanguagesByName = new(StringComparer.OrdinalIgnoreCase)
39 {
40 ["Makefile"] = "makefile", ["Dockerfile"] = "bash", [".gitignore"] = "plaintext", [".editorconfig"] = "ini",
41 };
42
43 public static string? InlineImageType(string fileName) =>
44 InlineImages.GetValueOrDefault(Path.GetExtension(fileName));
45
46 /// <summary>The highlight.js language for a file, or null when it should stay unhighlighted.</summary>
47 public static string? Language(string fileName) =>
48 LanguagesByName.GetValueOrDefault(fileName) ?? Languages.GetValueOrDefault(Path.GetExtension(fileName));
49
50 public static bool IsMarkdown(string fileName) =>
51 Path.GetExtension(fileName) is var ext
52 && (ext.Equals(".md", StringComparison.OrdinalIgnoreCase) || ext.Equals(".markdown", StringComparison.OrdinalIgnoreCase));
53
54 /// <summary>Picks the README among directory entries: README.md first, then other README variants.</summary>
55 public static T? FindReadme<T>(IEnumerable<T> files, Func<T, string> nameOf)
56 where T : class
57 {
58 T? best = null;
59 var bestRank = int.MaxValue;
60 foreach (var file in files)
61 {
62 var name = nameOf(file);
63 var rank = name.ToLowerInvariant() switch
64 {
65 "readme.md" => 0,
66 "readme.markdown" => 1,
67 "readme" => 2,
68 "readme.txt" => 3,
69 _ => int.MaxValue,
70 };
71 if (rank < bestRank)
72 {
73 best = file;
74 bestRank = rank;
75 }
76 }
77
78 return best;
79 }
80 }
added forge/Features/Browse/MarkdownRenderer.cs +115 −0View file
@@ -0,0 +1,115 @@
1 using System.Text.RegularExpressions;
2 using AngleSharp.Dom;
3 using Ganss.Xss;
4 using Markdig;
5
6 namespace Forge.Features.Browse;
7
8 /// <summary>Where relative links in a rendered document should point.</summary>
9 /// <param name="RawBase">For example /owner/repo/raw/main (images and other embedded files).</param>
10 /// <param name="BlobBase">For example /owner/repo/blob/main (links to other files).</param>
11 /// <param name="Directory">Directory of the document inside the repository; empty for the root.</param>
12 public sealed record LinkContext(string RawBase, string BlobBase, string Directory);
13
14 /// <summary>Markdown → sanitized HTML. Everything a repository author wrote is treated as hostile.</summary>
15 public sealed partial class MarkdownRenderer
16 {
17 private static readonly MarkdownPipeline Pipeline = new MarkdownPipelineBuilder()
18 .UsePipeTables()
19 .UseAutoLinks()
20 .UseTaskLists()
21 .UseEmphasisExtras()
22 .UseFootnotes()
23 .Build();
24
25 public string Render(string markdown, LinkContext links)
26 {
27 var html = Markdown.ToHtml(markdown, Pipeline);
28
29 // A sanitizer per call: its event handlers capture this document's link context.
30 var sanitizer = new HtmlSanitizer();
31 sanitizer.AllowedSchemes.Add("mailto");
32 // Inline styles are blocked by the CSP anyway, and forms have no place in a README.
33 sanitizer.AllowedAttributes.Remove("style");
34 foreach (var tag in (string[])["form", "button", "select", "textarea", "option", "optgroup", "fieldset", "style"])
35 {
36 sanitizer.AllowedTags.Remove(tag);
37 }
38
39 sanitizer.FilterUrl += (_, e) =>
40 {
41 if (e.SanitizedUrl is { } url && IsRelative(url))
42 {
43 var embedded = e.Tag.LocalName is "img" or "source" or "video" or "audio";
44 e.SanitizedUrl = Rewrite(url, links, embedded);
45 }
46 };
47
48 sanitizer.PostProcessNode += (_, e) =>
49 {
50 if (e.Node is IElement { LocalName: "a" } anchor
51 && anchor.GetAttribute("href") is { } href
52 && IsExternal(href))
53 {
54 anchor.SetAttribute("rel", "nofollow noopener");
55 }
56 };
57
58 return sanitizer.Sanitize(html);
59 }
60
61 internal static bool IsRelative(string url) =>
62 url.Length > 0
63 && url[0] != '#'
64 && !url.StartsWith("//", StringComparison.Ordinal)
65 && !SchemePattern().IsMatch(url);
66
67 internal static bool IsExternal(string url) =>
68 url.StartsWith("//", StringComparison.Ordinal)
69 || url.StartsWith("http:", StringComparison.OrdinalIgnoreCase)
70 || url.StartsWith("https:", StringComparison.OrdinalIgnoreCase);
71
72 /// <summary>Resolves a relative URL against the document's directory and points it into the repository.</summary>
73 internal static string Rewrite(string url, LinkContext links, bool embedded)
74 {
75 var suffixStart = url.IndexOfAny(['?', '#']);
76 var path = suffixStart >= 0 ? url[..suffixStart] : url;
77 var suffix = suffixStart >= 0 ? url[suffixStart..] : "";
78
79 // A leading slash means "from the repository root", as on other forges.
80 var segments = new List<string>();
81 if (!path.StartsWith('/') && links.Directory.Length > 0)
82 {
83 segments.AddRange(links.Directory.Split('/'));
84 }
85
86 foreach (var segment in path.Split('/', StringSplitOptions.RemoveEmptyEntries))
87 {
88 if (segment == ".")
89 {
90 continue;
91 }
92
93 if (segment == "..")
94 {
95 if (segments.Count > 0)
96 {
97 segments.RemoveAt(segments.Count - 1);
98 }
99
100 continue;
101 }
102
103 // The URL is already percent-encoded where needed; decode so it is not encoded twice.
104 segments.Add(Uri.UnescapeDataString(segment));
105 }
106
107 var basePath = embedded ? links.RawBase : links.BlobBase;
108 return segments.Count == 0
109 ? basePath + suffix
110 : basePath + "/" + Urls.EncodePath(string.Join('/', segments)) + suffix;
111 }
112
113 [GeneratedRegex("^[A-Za-z][A-Za-z0-9+.-]*:")]
114 private static partial Regex SchemePattern();
115 }
added forge/Features/Browse/RawEndpoint.cs +127 −0View file
@@ -0,0 +1,127 @@
1 using CliWrap;
2 using Forge.Features.Auth;
3 using Forge.Features.Repos;
4 using Forge.Git;
5 using Microsoft.Net.Http.Headers;
6
7 namespace Forge.Features.Browse;
8
9 /// <summary>
10 /// Serves file contents straight from the repository. Repository content is untrusted, so it is
11 /// never served as HTML: text goes out as text/plain, a short list of image types is shown inline,
12 /// and everything else (including SVG) is a download.
13 /// </summary>
14 public static class RawEndpoint
15 {
16 public static void MapRaw(this IEndpointRouteBuilder app) =>
17 app.MapGet("/{owner}/{repo}/raw/{**refAndPath}", HandleAsync);
18
19 private static async Task<IResult> HandleAsync(
20 HttpContext context,
21 string owner,
22 string repo,
23 string? refAndPath,
24 RepoService repos,
25 CurrentUser me,
26 RepoPaths paths,
27 RefResolver resolver,
28 GitRepo gitRepo,
29 GitCli git)
30 {
31 var ct = context.RequestAborted;
32 var repository = await repos.FindAsync(owner, repo, ct);
33 if (repository is null || !RepoAccess.CanRead(repository, me.Actor))
34 {
35 return Results.NotFound();
36 }
37
38 var repoPath = paths.For(repository.Id);
39 // Catch-all route values keep an encoded slash as %2F; nothing in a ref or path needs it.
40 var resolved = await resolver.ResolveAsync(repoPath, refAndPath, ct: ct);
41 if (resolved is null || resolved.Path.Length == 0)
42 {
43 return Results.NotFound();
44 }
45
46 var entry = await gitRepo.GetEntryAsync(repoPath, resolved.CommitSha, resolved.Path, ct);
47 if (entry is not { IsBlob: true })
48 {
49 return Results.NotFound();
50 }
51
52 var response = context.Response;
53 var etag = new EntityTagHeaderValue($"\"{entry.Sha}\"");
54 response.Headers.ETag = etag.ToString();
55 response.Headers.CacheControl = "no-cache";
56 response.Headers.XContentTypeOptions = "nosniff";
57 // Even if a browser were tricked into rendering this, nothing in it may run or load.
58 response.Headers.ContentSecurityPolicy = "default-src 'none'; sandbox";
59
60 if (context.Request.GetTypedHeaders().IfNoneMatch is { Count: > 0 } candidates
61 && candidates.Any(c => c.Equals(EntityTagHeaderValue.Any) || c.Compare(etag, useStrongComparison: false)))
62 {
63 return Results.StatusCode(StatusCodes.Status304NotModified);
64 }
65
66 var fileName = entry.Name;
67 var imageType = FileTypes.InlineImageType(fileName);
68 var forceDownload = Path.GetExtension(fileName).Equals(".svg", StringComparison.OrdinalIgnoreCase);
69 if (entry.Size is { } size)
70 {
71 response.ContentLength = size;
72 }
73
74 var target = PipeTarget.Create(async (stream, token) =>
75 {
76 // The first 8000 bytes decide text or binary, the same way git decides.
77 var head = new byte[8000];
78 var filled = 0;
79 while (filled < head.Length)
80 {
81 var n = await stream.ReadAsync(head.AsMemory(filled), token);
82 if (n == 0)
83 {
84 break;
85 }
86
87 filled += n;
88 }
89
90 if (imageType is not null)
91 {
92 response.ContentType = imageType;
93 }
94 else if (forceDownload || GitParsers.IsBinary(head.AsSpan(0, filled)))
95 {
96 response.ContentType = "application/octet-stream";
97 var disposition = new ContentDispositionHeaderValue("attachment");
98 disposition.SetHttpFileName(fileName);
99 response.Headers.ContentDisposition = disposition.ToString();
100 }
101 else
102 {
103 response.ContentType = "text/plain; charset=utf-8";
104 }
105
106 await response.Body.WriteAsync(head.AsMemory(0, filled), token);
107 await stream.CopyToAsync(response.Body, token);
108 });
109
110 try
111 {
112 await git.StreamAsync(
113 repoPath,
114 ["cat-file", "blob", entry.Sha],
115 PipeSource.Null,
116 target,
117 timeout: TimeSpan.FromMinutes(10),
118 ct: ct);
119 }
120 catch (OperationCanceledException) when (ct.IsCancellationRequested)
121 {
122 // The client stopped the download.
123 }
124
125 return Results.Empty;
126 }
127 }
added forge/Features/Browse/RepoInsights.cs +179 −0View file
@@ -0,0 +1,179 @@
1 using Forge.Git;
2
3 namespace Forge.Features.Browse;
4
5 /// <summary>One slice of the language bar.</summary>
6 /// <param name="Key">CSS suffix (lang-csharp) that carries the colour; "other" for the rest.</param>
7 /// <param name="Name">Display name; null for "other", which the page translates.</param>
8 public sealed record LanguageShare(string Key, string? Name, double Percent);
9
10 public sealed record Contributor(string Name, int Commits, DateTimeOffset First, DateTimeOffset Last);
11
12 /// <param name="CommitsByDay">Commit counts by UTC day; days without commits are absent.</param>
13 /// <param name="Truncated">The history is longer than what was counted.</param>
14 public sealed record RepoActivity(
15 IReadOnlyList<Contributor> Contributors,
16 IReadOnlyDictionary<DateOnly, int> CommitsByDay,
17 int Commits,
18 bool Truncated);
19
20 /// <summary>
21 /// Facts about a commit that cost more than one cheap git call: language shares, commit count,
22 /// the file list, and the last commit that touched each entry of a directory. Everything is keyed
23 /// by commit SHA, so it is cached without invalidation (see <see cref="ContentCache"/>).
24 /// </summary>
25 public sealed class RepoInsights(GitRepo git, ContentCache cache)
26 {
27 /// <summary>Directories with more entries than this do not get per-entry commits: one git process each is too slow.</summary>
28 public const int MaxEntriesWithCommits = 100;
29
30 private const int MaxLanguages = 6;
31
32 private static readonly Dictionary<string, (string Key, string Name)> Languages = new(StringComparer.OrdinalIgnoreCase)
33 {
34 [".cs"] = ("csharp", "C#"), [".csx"] = ("csharp", "C#"),
35 [".js"] = ("javascript", "JavaScript"), [".mjs"] = ("javascript", "JavaScript"),
36 [".cjs"] = ("javascript", "JavaScript"), [".jsx"] = ("javascript", "JavaScript"),
37 [".ts"] = ("typescript", "TypeScript"), [".tsx"] = ("typescript", "TypeScript"),
38 [".html"] = ("html", "HTML"), [".htm"] = ("html", "HTML"),
39 [".razor"] = ("html", "HTML"), [".cshtml"] = ("html", "HTML"),
40 [".css"] = ("css", "CSS"), [".scss"] = ("css", "CSS"), [".less"] = ("css", "CSS"),
41 [".py"] = ("python", "Python"), [".go"] = ("go", "Go"), [".rs"] = ("rust", "Rust"),
42 [".java"] = ("java", "Java"), [".kt"] = ("kotlin", "Kotlin"), [".kts"] = ("kotlin", "Kotlin"),
43 [".swift"] = ("swift", "Swift"), [".c"] = ("c", "C"), [".h"] = ("c", "C"),
44 [".cpp"] = ("cpp", "C++"), [".cc"] = ("cpp", "C++"), [".hpp"] = ("cpp", "C++"),
45 [".rb"] = ("ruby", "Ruby"), [".php"] = ("php", "PHP"), [".lua"] = ("lua", "Lua"),
46 [".sh"] = ("shell", "Shell"), [".bash"] = ("shell", "Shell"), [".zsh"] = ("shell", "Shell"),
47 [".ps1"] = ("powershell", "PowerShell"), [".sql"] = ("sql", "SQL"), [".vb"] = ("vb", "Visual Basic"),
48 };
49
50 /// <summary>Third-party code checked into a repository would drown out the project's own languages.</summary>
51 private static readonly string[] VendoredSegments = ["node_modules/", "vendor/", "wwwroot/lib/", "dist/", "third_party/"];
52
53 public Task<IReadOnlyList<FileEntry>> ListFilesAsync(string repoPath, string commitSha) =>
54 cache.GetOrCreateAsync(
55 "files:" + commitSha,
56 async () => (await git.ListFilesAsync(repoPath, commitSha)).Files,
57 files => files.Sum(f => 60L + f.Path.Length * 2));
58
59 public Task<int> CountCommitsAsync(string repoPath, string commitSha) =>
60 cache.GetOrCreateAsync("count:" + commitSha, () => git.CountCommitsAsync(repoPath, commitSha), _ => 32);
61
62 /// <summary>Share of each programming language by bytes, largest first. Empty when no file is in a known language.</summary>
63 public Task<IReadOnlyList<LanguageShare>> GetLanguagesAsync(string repoPath, string commitSha) =>
64 cache.GetOrCreateAsync(
65 "languages:" + commitSha,
66 async () => ComputeLanguages(await ListFilesAsync(repoPath, commitSha)),
67 shares => 200L * (shares.Count + 1));
68
69 public static IReadOnlyList<LanguageShare> ComputeLanguages(IEnumerable<FileEntry> files)
70 {
71 var bytes = new Dictionary<string, (string Name, long Bytes)>(StringComparer.Ordinal);
72 foreach (var file in files)
73 {
74 if (file.Size == 0
75 || file.Path.Contains(".min.", StringComparison.OrdinalIgnoreCase)
76 || IsVendored(file.Path)
77 || !Languages.TryGetValue(Path.GetExtension(file.Path), out var language))
78 {
79 continue;
80 }
81
82 bytes[language.Key] = (language.Name, bytes.GetValueOrDefault(language.Key).Bytes + file.Size);
83 }
84
85 var total = bytes.Values.Sum(v => v.Bytes);
86 if (total == 0)
87 {
88 return [];
89 }
90
91 var ordered = bytes.OrderByDescending(p => p.Value.Bytes).ThenBy(p => p.Key, StringComparer.Ordinal).ToList();
92 var shares = ordered
93 .Take(MaxLanguages)
94 .Select(p => new LanguageShare(p.Key, p.Value.Name, 100.0 * p.Value.Bytes / total))
95 .ToList();
96 var rest = ordered.Skip(MaxLanguages).Sum(p => p.Value.Bytes);
97 if (rest > 0)
98 {
99 shares.Add(new LanguageShare("other", null, 100.0 * rest / total));
100 }
101
102 return shares;
103 }
104
105 /// <summary>Who committed, and when, over the newest <see cref="MaxActivityCommits"/> commits.</summary>
106 public Task<RepoActivity> GetActivityAsync(string repoPath, string commitSha) =>
107 cache.GetOrCreateAsync(
108 "activity:" + commitSha,
109 async () => ComputeActivity(await git.ListAuthorshipAsync(repoPath, commitSha, MaxActivityCommits), MaxActivityCommits),
110 activity => 200L * activity.Contributors.Count + 40L * activity.CommitsByDay.Count + 200);
111
112 public const int MaxActivityCommits = 20_000;
113
114 public static RepoActivity ComputeActivity(IReadOnlyList<(string Name, string Email, DateTimeOffset When)> commits, int limit)
115 {
116 // One person is one e-mail address, whatever the capitalisation; the newest name wins.
117 var contributors = commits
118 .GroupBy(c => c.Email.Length > 0 ? c.Email.ToLowerInvariant() : c.Name, StringComparer.Ordinal)
119 .Select(g => new Contributor(g.First().Name, g.Count(), g.Min(c => c.When), g.Max(c => c.When)))
120 .OrderByDescending(c => c.Commits)
121 .ThenBy(c => c.Name, StringComparer.OrdinalIgnoreCase)
122 .ToList();
123 var byDay = commits
124 .GroupBy(c => DateOnly.FromDateTime(c.When.UtcDateTime))
125 .ToDictionary(g => g.Key, g => g.Count());
126 return new RepoActivity(contributors, byDay, commits.Count, commits.Count >= limit);
127 }
128
129 private static bool IsVendored(string path)
130 {
131 foreach (var segment in VendoredSegments)
132 {
133 if (path.StartsWith(segment, StringComparison.OrdinalIgnoreCase)
134 || path.Contains("/" + segment, StringComparison.OrdinalIgnoreCase))
135 {
136 return true;
137 }
138 }
139
140 return false;
141 }
142
143 /// <summary>
144 /// The newest commit that changed each entry of a directory, by entry name. Returns an empty map
145 /// for a directory with more than <see cref="MaxEntriesWithCommits"/> entries.
146 /// </summary>
147 public Task<IReadOnlyDictionary<string, CommitInfo>> GetLastCommitsAsync(
148 string repoPath,
149 string commitSha,
150 string directory,
151 IReadOnlyList<string> names)
152 {
153 if (names.Count is 0 or > MaxEntriesWithCommits)
154 {
155 return Task.FromResult<IReadOnlyDictionary<string, CommitInfo>>(new Dictionary<string, CommitInfo>());
156 }
157
158 return cache.GetOrCreateAsync<IReadOnlyDictionary<string, CommitInfo>>(
159 $"last:{commitSha}:{directory}",
160 async () =>
161 {
162 var found = new System.Collections.Concurrent.ConcurrentDictionary<string, CommitInfo>(StringComparer.Ordinal);
163 await Parallel.ForEachAsync(
164 names,
165 new ParallelOptions { MaxDegreeOfParallelism = 6 },
166 async (name, ct) =>
167 {
168 var path = directory.Length == 0 ? name : directory + "/" + name;
169 var log = await git.LogAsync(repoPath, commitSha, path, take: 1, ct: ct);
170 if (log.Count > 0)
171 {
172 found[name] = log[0];
173 }
174 });
175 return found;
176 },
177 map => map.Count * 600L + 100);
178 }
179 }
added forge/Features/Browse/Search.razor +178 −0View file
@@ -0,0 +1,178 @@
1 @page "/{Owner}/{Repo}/search"
2 @inherits RepoPageBase
3 @inject RepoInsights Insights
4
5 @if (Repository is not null)
6 {
7 <PageTitle>@T["Search"] · @Repository.Owner.Username/@Repository.Name</PageTitle>
8
9 <RepoHeader Repository="Repository" Active="code" IsOwner="IsOwner"/>
10
11 <form class="toolbar" method="get" action="@Urls.Search(Repository)" role="search">
12 <div class="search repo-search">
13 <Icon Name="search" Size="15"/>
14 <input type="search" name="q" value="@Query" placeholder="@T["Search file names and code"]"
15 aria-label="@T["Search file names and code"]" autocomplete="off" autofocus maxlength="@MaxQueryLength"/>
16 </div>
17 @if (_resolved is not null)
18 {
19 <input type="hidden" name="ref" value="@_resolved.Name"/>
20 }
21 <button type="submit" class="button">@T["Search"]</button>
22 </form>
23
24 @if (_resolved is null)
25 {
26 <div class="empty-state">
27 <Icon Name="inbox" Size="32"/>
28 <h2>@T["The repository is empty"]</h2>
29 </div>
30 }
31 else if (_term is null)
32 {
33 <div class="empty-state">
34 <Icon Name="search" Size="32"/>
35 <h2>@T["Search this repository"]</h2>
36 <p>@T["Type at least {0} characters. Upper and lower case do not matter.", MinQueryLength]</p>
37 </div>
38 }
39 else if (_files.Count == 0 && _groups.Count == 0)
40 {
41 <div class="empty-state">
42 <Icon Name="search" Size="32"/>
43 <h2>@T["Nothing in {0} matches “{1}”.", RefLabel, _term]</h2>
44 </div>
45 }
46 else
47 {
48 <p class="muted">
49 @T["Results for “{0}” in {1}", _term, RefLabel]
50 </p>
51
52 @if (_files.Count > 0)
53 {
54 <h3 class="result-heading"><Icon Name="file"/> @T["File names"] <Counter Value="_files.Count"/></h3>
55 <ul class="result-files">
56 @foreach (var file in _files)
57 {
58 <li>
59 <Icon Name="file" Size="14"/>
60 <a href="@Urls.Blob(Repository, _resolved.Name, file.Path)"><Highlighted Text="@file.Path" Term="@_term"/></a>
61 </li>
62 }
63 </ul>
64 @if (_moreFiles)
65 {
66 <p class="muted small">@T["Only the first {0} files are shown.", MaxFiles]</p>
67 }
68 }
69
70 @if (_groups.Count > 0)
71 {
72 <h3 class="result-heading"><Icon Name="code"/> @T["Code"] <Counter Value="_matchCount"/></h3>
73 @foreach (var group in _groups)
74 {
75 <section class="result-file">
76 <header class="result-file-head">
77 <Icon Name="file" Size="14"/>
78 <a href="@Urls.Blob(Repository, _resolved.Name, group.Key)">@group.Key</a>
79 </header>
80 <table class="result-lines">
81 <tbody>
82 @foreach (var match in group)
83 {
84 <tr>
85 <td class="ln"><a href="@LineUrl(match)">@match.Line</a></td>
86 <td class="result-code"><Highlighted Text="@match.Text" Term="@_term"/></td>
87 </tr>
88 }
89 </tbody>
90 </table>
91 </section>
92 }
93 @if (_truncated)
94 {
95 <p class="alert warning">@T["There are more matches than shown. Make the search more specific."]</p>
96 }
97 }
98 }
99 }
100
101 @code {
102 public const int MinQueryLength = 2;
103 public const int MaxQueryLength = 200;
104 public const int MaxFiles = 30;
105 public const int MaxCodeFiles = 40;
106
107 [SupplyParameterFromQuery(Name = "q")]
108 private string? Query { get; set; }
109
110 /// <summary>A branch, tag or commit SHA; the default branch when absent.</summary>
111 [SupplyParameterFromQuery(Name = "ref")]
112 private string? RefName { get; set; }
113
114 private ResolvedRef? _resolved;
115 private string? _term;
116 private List<FileEntry> _files = [];
117 private bool _moreFiles;
118 private List<IGrouping<string, GrepMatch>> _groups = [];
119 private int _matchCount;
120 private bool _truncated;
121
122 private string RefLabel => _resolved!.Kind == ResolvedKind.Commit ? _resolved.Name[..8] : _resolved.Name;
123
124 /// <summary>A Markdown file opens as a preview, which has no line numbers to jump to.</summary>
125 private string LineUrl(GrepMatch match) =>
126 Urls.Blob(Repository!, _resolved!.Name, match.Path)
127 + (FileTypes.IsMarkdown(match.Path) ? "?plain=1" : "")
128 + "#L" + match.Line.ToString(CultureInfo.InvariantCulture);
129
130 protected override async Task OnInitializedAsync()
131 {
132 if (!await LoadRepoAsync())
133 {
134 return;
135 }
136
137 var refs = await Git.ListRefsAsync(RepoPath);
138 if (string.IsNullOrEmpty(RefName))
139 {
140 var branch = refs.FirstOrDefault(r => r.Kind == RefKind.Branch && r.Name == Repository!.DefaultBranch)
141 ?? refs.FirstOrDefault(r => r.Kind == RefKind.Branch);
142 if (branch is null)
143 {
144 return; // Empty repository.
145 }
146
147 _resolved = new ResolvedRef(branch.Name, ResolvedKind.Branch, branch.TargetSha, "");
148 }
149 else
150 {
151 // Only names from the repository's own ref list, or a hex SHA, get through.
152 _resolved = await Resolver.ResolveExactAsync(RepoPath, RefName, refs);
153 if (_resolved is null)
154 {
155 NotFound();
156 return;
157 }
158 }
159
160 var term = Query?.Trim() ?? "";
161 if (term.Length < MinQueryLength || term.Length > MaxQueryLength || term.Any(char.IsControl))
162 {
163 return;
164 }
165
166 _term = term;
167 var allFiles = await Insights.ListFilesAsync(RepoPath, _resolved.CommitSha);
168 var named = allFiles.Where(f => f.Path.Contains(term, StringComparison.OrdinalIgnoreCase)).Take(MaxFiles + 1).ToList();
169 _moreFiles = named.Count > MaxFiles;
170 _files = named.Take(MaxFiles).ToList();
171
172 var (matches, truncated) = await Git.GrepAsync(RepoPath, _resolved.CommitSha, term);
173 var groups = matches.GroupBy(m => m.Path).ToList();
174 _truncated = truncated || groups.Count > MaxCodeFiles;
175 _groups = groups.Take(MaxCodeFiles).ToList();
176 _matchCount = _groups.Sum(g => g.Count());
177 }
178 }
added forge/Features/Browse/Tree.razor +328 −0View file
@@ -0,0 +1,328 @@
1 @page "/{Owner}/{Repo}"
2 @page "/{Owner}/{Repo}/tree/{*RefAndPath}"
3 @inherits RepoPageBase
4 @inject ContentCache Cache
5 @inject RepoInsights Insights
6 @inject MarkdownRenderer Markdown
7 @inject IOptions<ForgeOptions> Options
8
9 @if (Repository is not null)
10 {
11 <PageTitle>@(_resolved is { Path.Length: > 0 } ? $"{_resolved.Path} · " : "")@Repository.Owner.Username/@Repository.Name</PageTitle>
12 <HeadContent>
13 <link rel="alternate" type="application/atom+xml" title="@T["Commits"]" href="@Urls.Atom(Repository)"/>
14 </HeadContent>
15
16 <RepoHeader Repository="Repository" Active="code" IsOwner="IsOwner"/>
17
18 @if (_resolved is null)
19 {
20 var cloneUrl = Urls.Clone(Options.Value, Repository);
21 <section class="card">
22 <h2>@T["The repository is empty"]</h2>
23 <p>@T["Clone it and push the first commit:"]</p>
24 <pre class="snippet">git clone @cloneUrl
25 cd @Repository.Name
26 echo "# @Repository.Name" > README.md
27 git add README.md
28 git commit -m "First commit"
29 git push -u origin main</pre>
30 <p>@T["Or push an existing repository:"]</p>
31 <pre class="snippet">git remote add origin @cloneUrl
32 git push -u origin main</pre>
33 <p class="muted">
34 @T["Use an access token with write permission as the password."]
35 @if (IsOwner)
36 {
37 <a href="/settings/tokens">@T["Create a token"]</a>
38 }
39 </p>
40 </section>
41 }
42 else
43 {
44 var atRoot = _resolved.Path.Length == 0;
45 <div class="@(atRoot ? "repo-layout with-side" : "repo-layout")">
46 <div class="repo-content">
47 <div class="toolbar">
48 <RefSwitcher Refs="_refs" Current="@_resolved.Name" CurrentKind="_resolved.Kind"
49 UrlFor="@(name => Urls.Tree(Repository, name, _resolved.Path))"/>
50 <Breadcrumbs Repository="Repository" RefName="@_resolved.Name" Path="@_resolved.Path"/>
51 <form class="search repo-search toolbar-end" method="get" action="@Urls.Search(Repository)" role="search">
52 <Icon Name="search" Size="15"/>
53 <input type="search" name="q" placeholder="@T["Search file names and code"]"
54 aria-label="@T["Search file names and code"]" autocomplete="off" data-hotkey="s"/>
55 <input type="hidden" name="ref" value="@_resolved.Name"/>
56 <kbd class="js-only">s</kbd>
57 </form>
58 <a class="button" href="@Urls.Commits(Repository, _resolved.Name, _resolved.Path)">
59 <Icon Name="history"/> @T["History"]
60 </a>
61 </div>
62
63 <div class="file-box">
64 @if (_latest is not null)
65 {
66 <div class="latest-commit">
67 <span class="latest-subject">
68 <Avatar Name="@_latest.AuthorName"/>
69 <strong>@_latest.AuthorName</strong>
70 <a class="latest-message" href="@Urls.Commit(Repository, _latest.Sha)">@(_latest.Subject.Length == 0 ? T["(no message)"] : _latest.Subject)</a>
71 </span>
72 <span class="muted small latest-meta">
73 <a class="sha" href="@Urls.Commit(Repository, _latest.Sha)">@_latest.ShortSha</a>
74 <span class="sep">·</span>
75 <TimeAgo Value="_latest.AuthorDate"/>
76 </span>
77 </div>
78 }
79
80 <table class="table tree">
81 <tbody>
82 @if (!atRoot)
83 {
84 <tr>
85 <td class="icon"><Icon Name="folder" Class="icon-folder"/></td>
86 <td colspan="3"><a href="@Urls.Tree(Repository, _resolved.Name, ParentPath)" title="@T["Parent directory"]">..</a></td>
87 </tr>
88 }
89 @foreach (var entry in _entries)
90 {
91 var path = atRoot ? entry.Name : _resolved.Path + "/" + entry.Name;
92 var last = _lastCommits.GetValueOrDefault(entry.Name);
93 <tr>
94 <td class="icon">
95 @if (entry.IsTree)
96 {
97 <Icon Name="folder" Class="icon-folder"/>
98 }
99 else
100 {
101 <Icon Name="@(entry.IsSubmodule ? "package" : "file")"/>
102 }
103 </td>
104 <td class="name">
105 @if (entry.IsTree)
106 {
107 <a href="@Urls.Tree(Repository, _resolved.Name, path)">@entry.Name</a>
108 }
109 else if (entry.IsBlob)
110 {
111 <a href="@Urls.Blob(Repository, _resolved.Name, path)" title="@(entry.Size is { } size ? Format.Size(size) : null)">@entry.Name</a>
112 }
113 else
114 {
115 <span title="@T["Submodule {0}", entry.Sha]">@entry.Name</span>
116 }
117 </td>
118 <td class="tree-commit small">
119 @if (last is not null)
120 {
121 <a class="muted" href="@Urls.Commit(Repository, last.Sha)">@(last.Subject.Length == 0 ? T["(no message)"] : last.Subject)</a>
122 }
123 </td>
124 <td class="tree-age muted small right">
125 @if (last is not null)
126 {
127 <TimeAgo Value="last.AuthorDate"/>
128 }
129 else if (entry is { IsBlob: true, Size: { } bytes })
130 {
131 @Format.Size(bytes)
132 }
133 </td>
134 </tr>
135 }
136 </tbody>
137 </table>
138 </div>
139
140 @if (_readmeHtml is not null)
141 {
142 <article class="card readme">
143 <p class="readme-name"><Icon Name="book"/> @_readmeName</p>
144 @if (_readmeIsMarkdown)
145 {
146 <div class="markdown">@((MarkupString)_readmeHtml)</div>
147 }
148 else
149 {
150 <pre class="plain">@_readmeHtml</pre>
151 }
152 </article>
153 }
154 </div>
155
156 @if (atRoot)
157 {
158 <aside class="repo-side">
159 <section class="side-section">
160 <h2>@T["About"]</h2>
161 <p class="@(Repository.Description.Length > 0 ? "" : "muted")">
162 @(Repository.Description.Length > 0 ? Repository.Description : T["No description."])
163 </p>
164 <ul class="side-list">
165 <li>
166 <Icon Name="commit"/>
167 <a href="@Urls.Commits(Repository, _resolved.Name)">@T.Plural(_commitCount, "{0} commit", "{0} commits")</a>
168 </li>
169 <li>
170 <Icon Name="branch"/>
171 <a href="@Urls.Branches(Repository)">@T.Plural(_refs.Count(r => r.Kind == RefKind.Branch), "{0} branch", "{0} branches")</a>
172 </li>
173 <li>
174 <Icon Name="tag"/>
175 <a href="@Urls.Tags(Repository)">@T.Plural(_refs.Count(r => r.Kind == RefKind.Tag), "{0} tag", "{0} tags")</a>
176 </li>
177 <li>
178 <Icon Name="rss"/>
179 <a href="@Urls.Atom(Repository)">@T["Commit feed (Atom)"]</a>
180 </li>
181 </ul>
182 </section>
183
184 @if (_languages.Count > 0)
185 {
186 <section class="side-section">
187 <h2>@T["Languages"]</h2>
188 <LanguageBar Shares="_languages"/>
189 </section>
190 }
191 </aside>
192 }
193 </div>
194 }
195 }
196
197 @code {
198 [Parameter]
199 public string? RefAndPath { get; set; }
200
201 private IReadOnlyList<GitRef> _refs = [];
202 private ResolvedRef? _resolved;
203 private IReadOnlyList<TreeEntry> _entries = [];
204 private CommitInfo? _latest;
205 private IReadOnlyDictionary<string, CommitInfo> _lastCommits = new Dictionary<string, CommitInfo>();
206 private int _commitCount;
207 private IReadOnlyList<LanguageShare> _languages = [];
208 private string? _readmeHtml;
209 private string? _readmeName;
210 private bool _readmeIsMarkdown;
211
212 private string ParentPath =>
213 _resolved!.Path.LastIndexOf('/') is var slash and >= 0 ? _resolved.Path[..slash] : "";
214
215 protected override async Task OnInitializedAsync()
216 {
217 if (!await LoadRepoAsync())
218 {
219 return;
220 }
221
222 var repo = Repository!;
223 _refs = await Git.ListRefsAsync(RepoPath);
224
225 if (string.IsNullOrEmpty(RefAndPath))
226 {
227 // Repository home: the default branch, or any branch if the default one is gone.
228 var branch = _refs.FirstOrDefault(r => r.Kind == RefKind.Branch && r.Name == repo.DefaultBranch)
229 ?? _refs.FirstOrDefault(r => r.Kind == RefKind.Branch);
230 if (branch is null)
231 {
232 return; // Empty repository: the markup shows clone instructions.
233 }
234
235 _resolved = new ResolvedRef(branch.Name, ResolvedKind.Branch, branch.TargetSha, "");
236 }
237 else
238 {
239 _resolved = await Resolver.ResolveAsync(RepoPath, RefAndPath, _refs);
240 if (_resolved is null)
241 {
242 NotFound();
243 return;
244 }
245 }
246
247 string? treeSha;
248 if (_resolved.Path.Length == 0)
249 {
250 treeSha = await Git.GetRootTreeShaAsync(RepoPath, _resolved.CommitSha);
251 }
252 else
253 {
254 var entry = await Git.GetEntryAsync(RepoPath, _resolved.CommitSha, _resolved.Path);
255 if (entry is { IsBlob: true })
256 {
257 Redirect(Urls.Blob(repo, _resolved.Name, _resolved.Path));
258 return;
259 }
260
261 treeSha = entry is { IsTree: true } ? entry.Sha : null;
262 }
263
264 if (treeSha is null)
265 {
266 NotFound();
267 return;
268 }
269
270 // A tree SHA names its content forever, so the listing can be cached without invalidation.
271 var listing = await Cache.GetOrCreateAsync(
272 "tree:" + treeSha,
273 () => Git.ListTreeAsync(RepoPath, treeSha),
274 entries => entries.Sum(e => 120L + e.Name.Length * 2));
275 _entries = listing
276 .OrderByDescending(e => e.IsTree)
277 .ThenBy(e => e.Name, StringComparer.OrdinalIgnoreCase)
278 .ToList();
279
280 _latest = await Git.GetCommitAsync(RepoPath, _resolved.CommitSha);
281 _lastCommits = await Insights.GetLastCommitsAsync(
282 RepoPath, _resolved.CommitSha, _resolved.Path, _entries.Select(e => e.Name).ToList());
283 if (_resolved.Path.Length == 0)
284 {
285 _commitCount = await Insights.CountCommitsAsync(RepoPath, _resolved.CommitSha);
286 _languages = await Insights.GetLanguagesAsync(RepoPath, _resolved.CommitSha);
287 }
288
289 await LoadReadmeAsync(repo, _resolved);
290 }
291
292 private async Task LoadReadmeAsync(Repository repo, ResolvedRef resolved)
293 {
294 var readme = FileTypes.FindReadme(_entries.Where(e => e.IsBlob && !e.IsSymlink), e => e.Name);
295 if (readme is null || readme.Size is null or > FileTypes.MaxReadmeBytes)
296 {
297 return;
298 }
299
300 _readmeName = readme.Name;
301 _readmeIsMarkdown = FileTypes.IsMarkdown(readme.Name);
302 var links = new LinkContext(
303 Urls.Raw(repo, resolved.Name, ""),
304 Urls.Blob(repo, resolved.Name, ""),
305 resolved.Path);
306
307 // Rendered HTML depends on the blob and on where its relative links point.
308 var key = $"readme:{readme.Sha}:{_readmeIsMarkdown}:{links.RawBase}:{links.Directory}";
309 _readmeHtml = await Cache.GetOrCreateAsync(
310 key,
311 async () =>
312 {
313 var blob = await Git.ReadBlobAsync(RepoPath, readme.Sha, FileTypes.MaxReadmeBytes);
314 if (blob.IsBinary)
315 {
316 return "";
317 }
318
319 return _readmeIsMarkdown ? Markdown.Render(blob.Text, links) : blob.Text;
320 },
321 html => html.Length * 2L);
322
323 if (_readmeHtml.Length == 0)
324 {
325 _readmeHtml = null;
326 }
327 }
328 }
added forge/Features/History/AtomEndpoint.cs +101 −0View file
@@ -0,0 +1,101 @@
1 using System.Text;
2 using System.Xml;
3 using System.Xml.Linq;
4 using Forge.Data;
5 using Forge.Features.Auth;
6 using Forge.Features.Repos;
7 using Forge.Git;
8 using Microsoft.Extensions.Options;
9
10 namespace Forge.Features.History;
11
12 /// <summary>Atom feed of the latest commits on the default branch.</summary>
13 public static class AtomEndpoint
14 {
15 private static readonly XNamespace Atom = "http://www.w3.org/2005/Atom";
16
17 public static void MapAtom(this IEndpointRouteBuilder app) =>
18 app.MapGet("/{owner}/{repo}/atom", HandleAsync);
19
20 private static async Task<IResult> HandleAsync(
21 HttpContext context,
22 string owner,
23 string repo,
24 RepoService repos,
25 CurrentUser me,
26 RepoPaths paths,
27 GitRepo git,
28 IOptions<ForgeOptions> options)
29 {
30 var ct = context.RequestAborted;
31 var repository = await repos.FindAsync(owner, repo, ct);
32 if (repository is null || !RepoAccess.CanRead(repository, me.Actor))
33 {
34 return Results.NotFound();
35 }
36
37 var repoPath = paths.For(repository.Id);
38 var refs = await git.ListRefsAsync(repoPath, ct);
39 var branch = refs.FirstOrDefault(r => r.Kind == RefKind.Branch && r.Name == repository.DefaultBranch)
40 ?? refs.FirstOrDefault(r => r.Kind == RefKind.Branch);
41 IReadOnlyList<CommitInfo> commits = branch is null
42 ? []
43 : await git.LogAsync(repoPath, branch.TargetSha, take: 30, ct: ct);
44
45 var document = Build(options.Value, repository, commits);
46 var bytes = Encoding.UTF8.GetBytes(document);
47 return Results.Bytes(bytes, "application/atom+xml; charset=utf-8");
48 }
49
50 public static string Build(ForgeOptions options, Repository repository, IReadOnlyList<CommitInfo> commits)
51 {
52 var repoUrl = Urls.Absolute(options, Urls.Repo(repository));
53 var feedUrl = Urls.Absolute(options, Urls.Atom(repository));
54 var updated = commits.Count > 0
55 ? commits[0].CommitDate
56 : Format.Utc(repository.PushedAt ?? repository.CreatedAt);
57
58 var feed = new XElement(Atom + "feed",
59 new XElement(Atom + "id", feedUrl),
60 new XElement(Atom + "title", $"{repository.Owner.Username}/{repository.Name}: commits"),
61 new XElement(Atom + "updated", Format.IsoTime(updated)),
62 new XElement(Atom + "link", new XAttribute("rel", "self"), new XAttribute("href", feedUrl)),
63 new XElement(Atom + "link", new XAttribute("rel", "alternate"), new XAttribute("href", repoUrl)),
64 commits.Select(c =>
65 {
66 var url = Urls.Absolute(options, Urls.Commit(repository, c.Sha));
67 return new XElement(Atom + "entry",
68 new XElement(Atom + "id", url),
69 new XElement(Atom + "title", Clean(c.Subject)),
70 new XElement(Atom + "updated", Format.IsoTime(c.CommitDate)),
71 new XElement(Atom + "link", new XAttribute("rel", "alternate"), new XAttribute("href", url)),
72 new XElement(Atom + "author", new XElement(Atom + "name", Clean(c.AuthorName))),
73 new XElement(Atom + "content", new XAttribute("type", "text"),
74 Clean(c.Body.Length == 0 ? c.Subject : c.Subject + "\n\n" + c.Body)));
75 }));
76
77 var settings = new XmlWriterSettings { Indent = true, Encoding = new UTF8Encoding(false) };
78 using var buffer = new MemoryStream();
79 using (var writer = XmlWriter.Create(buffer, settings))
80 {
81 new XDocument(feed).Save(writer);
82 }
83
84 return Encoding.UTF8.GetString(buffer.ToArray());
85 }
86
87 /// <summary>Drops characters XML 1.0 cannot represent; commit messages can contain any byte.</summary>
88 private static string Clean(string value)
89 {
90 var builder = new StringBuilder(value.Length);
91 foreach (var rune in value.EnumerateRunes())
92 {
93 if (rune.Value is 0x9 or 0xA or 0xD or >= 0x20 and <= 0xD7FF or >= 0xE000 and <= 0xFFFD or >= 0x10000)
94 {
95 builder.Append(rune.ToString());
96 }
97 }
98
99 return builder.ToString();
100 }
101 }
added forge/Features/History/BranchRules.cs +27 −0View file
@@ -0,0 +1,27 @@
1 using Forge.Data;
2
3 namespace Forge.Features.History;
4
5 /// <summary>Matching of branch names against protection rules.</summary>
6 public static class BranchRules
7 {
8 /// <summary>A pattern is a branch name, or a prefix ending in "/*" that covers every branch below it.</summary>
9 public static bool Matches(string pattern, string branch) =>
10 pattern.EndsWith("/*", StringComparison.Ordinal)
11 ? branch.StartsWith(pattern[..^1], StringComparison.Ordinal)
12 : string.Equals(pattern, branch, StringComparison.Ordinal);
13
14 public static BranchProtection? Find(IEnumerable<BranchProtection> rules, string branch) =>
15 rules.FirstOrDefault(r => Matches(r.Pattern, branch));
16
17 /// <summary>
18 /// The ref prefix git's receive.hideRefs needs to refuse pushes to the pattern:
19 /// "refs/heads/main" for a name, "refs/heads/release/" for "release/*".
20 /// </summary>
21 public static string RefPrefix(string pattern) =>
22 "refs/heads/" + (pattern.EndsWith("/*", StringComparison.Ordinal) ? pattern[..^1] : pattern);
23
24 /// <summary>The part of a pattern that must be a valid branch name.</summary>
25 public static string NamePart(string pattern) =>
26 pattern.EndsWith("/*", StringComparison.Ordinal) ? pattern[..^2] : pattern;
27 }
added forge/Features/History/Branches.razor +209 −0View file
@@ -0,0 +1,209 @@
1 @page "/{Owner}/{Repo}/branches"
2 @inherits RepoPageBase
3 @inject ContentCache Cache
4 @inject RefService Refs
5
6 @if (Repository is not null)
7 {
8 <PageTitle>@T["Branches"] · @Repository.Owner.Username/@Repository.Name</PageTitle>
9
10 <RepoHeader Repository="Repository" Active="branches" IsOwner="IsOwner"/>
11
12 @if (_message is not null)
13 {
14 <p class="alert success">@_message</p>
15 }
16 @if (_error is not null)
17 {
18 <p class="alert error">@_error</p>
19 }
20
21 @if (_rows.Count == 0)
22 {
23 <div class="empty-state">
24 <Icon Name="branch" Size="32"/>
25 <h2>@T["This repository has no branches yet."]</h2>
26 </div>
27 }
28 else
29 {
30 <form method="post" @formname="delete-branch" @onsubmit="DeleteAsync">
31 <AntiforgeryToken/>
32 <table class="table">
33 <thead>
34 <tr>
35 <th>@T["Branch"]</th>
36 <th>@T["Last commit"]</th>
37 <th class="right" title="@T["Commits ahead of and behind the default branch"]">@T["Compared to {0}", _defaultName]</th>
38 <th></th>
39 </tr>
40 </thead>
41 <tbody>
42 @foreach (var row in _rows)
43 {
44 <tr>
45 <td>
46 <Icon Name="branch" Class="cell-icon"/>
47 <a href="@Urls.Tree(Repository, row.Ref.Name)"><strong>@row.Ref.Name</strong></a>
48 @if (row.IsDefault)
49 {
50 <span class="badge">@T["default"]</span>
51 }
52 </td>
53 <td>
54 <a href="@Urls.Commit(Repository, row.Ref.TargetSha)">@row.Ref.Subject</a>
55 @if (row.Ref.Date is { } date)
56 {
57 <span class="muted small"> · <TimeAgo Value="date"/></span>
58 }
59 </td>
60 <td class="right small">
61 @if (row.IsDefault)
62 {
63 <span class="muted">—</span>
64 }
65 else if (row.AheadBehind is { } ab)
66 {
67 <span title="@T["{0} ahead, {1} behind", ab.Ahead, ab.Behind]">↑@ab.Ahead ↓@ab.Behind</span>
68 }
69 </td>
70 <td class="right actions">
71 @if (!row.IsDefault)
72 {
73 <a class="button small" href="@Urls.Compare(Repository, _defaultName, row.Ref.Name)">@T["Compare"]</a>
74 @if (IsOwner)
75 {
76 <button type="submit" name="DeleteName" value="@row.Ref.Name" class="button danger small">@T["Delete"]</button>
77 }
78 }
79 </td>
80 </tr>
81 }
82 </tbody>
83 </table>
84 </form>
85
86 @if (IsOwner)
87 {
88 <section class="card">
89 <h2>@T["New branch"]</h2>
90 <form method="post" @formname="create-branch" @onsubmit="CreateAsync" class="form">
91 <AntiforgeryToken/>
92 <label>
93 @T["Name"]
94 <input name="NewName" value="@NewName" required maxlength="200"/>
95 </label>
96 <label>
97 <span>@T["From"] <span class="muted">@T["(branch, tag or commit SHA)"]</span></span>
98 <input name="From" value="@(From ?? _defaultName)" required maxlength="250"/>
99 </label>
100 <button type="submit" class="button primary">@T["Create branch"]</button>
101 </form>
102 </section>
103 }
104 }
105 }
106
107 @code {
108 /// <summary>Ahead/behind costs one git process per branch, so it is computed for the first branches only.</summary>
109 private const int MaxCompared = 50;
110
111 private sealed record Row(GitRef Ref, bool IsDefault, (int Ahead, int Behind)? AheadBehind);
112
113 [SupplyParameterFromForm(FormName = "delete-branch")]
114 private string? DeleteName { get; set; }
115
116 [SupplyParameterFromForm(FormName = "create-branch")]
117 private string? NewName { get; set; }
118
119 [SupplyParameterFromForm(FormName = "create-branch")]
120 private string? From { get; set; }
121
122 private List<Row> _rows = [];
123 private string _defaultName = "";
124 private string? _message;
125 private string? _error;
126
127 protected override async Task OnInitializedAsync()
128 {
129 if (await LoadRepoAsync())
130 {
131 await LoadAsync();
132 }
133 }
134
135 private async Task LoadAsync()
136 {
137 var repo = Repository!;
138 _rows = [];
139 var branches = (await Git.ListRefsAsync(RepoPath)).Where(r => r.Kind == RefKind.Branch).ToList();
140 var defaultBranch = branches.FirstOrDefault(b => b.Name == repo.DefaultBranch) ?? branches.FirstOrDefault();
141 if (defaultBranch is null)
142 {
143 return;
144 }
145
146 _defaultName = defaultBranch.Name;
147 _rows.Add(new Row(defaultBranch, true, null));
148
149 var compared = 0;
150 foreach (var branch in branches.Where(b => b != defaultBranch).OrderByDescending(b => b.Date))
151 {
152 (int Ahead, int Behind)? counts = null;
153 if (compared++ < MaxCompared)
154 {
155 // Both SHAs are in the key, so the cached answer stays valid until either branch moves.
156 counts = await Cache.GetOrCreateAsync(
157 $"ab:{defaultBranch.TargetSha}:{branch.TargetSha}",
158 () => Git.AheadBehindAsync(RepoPath, defaultBranch.TargetSha, branch.TargetSha),
159 _ => 64);
160 }
161
162 _rows.Add(new Row(branch, false, counts));
163 }
164 }
165
166 private async Task CreateAsync()
167 {
168 if (Repository is null || !IsOwner)
169 {
170 return;
171 }
172
173 var name = NewName?.Trim() ?? "";
174 var result = await Refs.CreateBranchAsync(Repository, name, From);
175 if (result.Ok)
176 {
177 _message = T["Branch {0} was created.", name];
178 NewName = null;
179 From = null;
180 }
181 else
182 {
183 _error = T[result.Error!];
184 }
185
186 await LoadAsync();
187 }
188
189 private async Task DeleteAsync()
190 {
191 if (Repository is null || !IsOwner)
192 {
193 return;
194 }
195
196 var result = await Refs.DeleteBranchAsync(Repository, DeleteName);
197 if (result.Ok)
198 {
199 // The SHA is shown so that a branch deleted by mistake can be created again from it.
200 _message = T["Branch {0} was deleted (it pointed at {1}).", DeleteName, result.Sha];
201 }
202 else
203 {
204 _error = T[result.Error!];
205 }
206
207 await LoadAsync();
208 }
209 }
added forge/Features/History/Commit.razor +171 −0View file
@@ -0,0 +1,171 @@
1 @page "/{Owner}/{Repo}/commit/{Sha}"
2 @inherits RepoPageBase
3 @inject RefService Refs
4 @inject ForgeDb Db
5
6 @if (Repository is not null && _commit is not null && _diff is not null)
7 {
8 <PageTitle>@_commit.Subject · @_commit.ShortSha</PageTitle>
9 <HighlightAssets/>
10
11 <RepoHeader Repository="Repository" Active="commits" IsOwner="IsOwner"/>
12
13 @if (_error is not null)
14 {
15 <div class="alert error">
16 <p>@_error</p>
17 @if (_conflicts.Count > 0)
18 {
19 <ul>
20 @foreach (var file in _conflicts)
21 {
22 <li><code>@file</code></li>
23 }
24 </ul>
25 }
26 </div>
27 }
28
29 <section class="card commit-detail">
30 <h2 class="commit-title">@(_commit.Subject.Length == 0 ? T["(no message)"] : _commit.Subject)</h2>
31 @if (_commit.Body.Length > 0)
32 {
33 <pre class="commit-body">@_commit.Body</pre>
34 }
35 <dl class="meta">
36 <dt>@T["Author"]</dt>
37 <dd><Avatar Name="@_commit.AuthorName"/> @_commit.AuthorName &lt;@_commit.AuthorEmail&gt; · <TimeAgo Value="_commit.AuthorDate"/></dd>
38 @if (_commit.CommitterName != _commit.AuthorName || _commit.CommitterEmail != _commit.AuthorEmail)
39 {
40 <dt>@T["Committer"]</dt>
41 <dd>@_commit.CommitterName &lt;@_commit.CommitterEmail&gt; · <TimeAgo Value="_commit.CommitDate"/></dd>
42 }
43 <dt>@T["Commit"]</dt>
44 <dd>
45 <code>@_commit.Sha</code>
46 <button type="button" class="icon-button inline js-only" data-copy="@_commit.Sha"
47 title="@T["Copy the full SHA"]" aria-label="@T["Copy the full SHA"]">
48 <Icon Name="copy" Size="14"/>
49 </button>
50 </dd>
51 <dt>@(_commit.Parents.Count == 1 ? T["Parent"] : T["Parents"])</dt>
52 <dd>
53 @if (_commit.Parents.Count == 0)
54 {
55 <span class="muted">@T["none (first commit)"]</span>
56 }
57 @foreach (var parent in _commit.Parents)
58 {
59 <a class="sha" href="@Urls.Commit(Repository, parent)">@(parent[..8])</a>
60 }
61 </dd>
62 </dl>
63 <p><a class="button" href="@Urls.Tree(Repository, _commit.Sha)"><Icon Name="code"/> @T["Browse files at this commit"]</a></p>
64
65 @* Reverting and cherry-picking need exactly one parent to know what "this commit's change" is. *@
66 @if (IsOwner && _commit.Parents.Count == 1 && _branches.Count > 0)
67 {
68 <form method="post" @formname="apply-commit" @onsubmit="ApplyAsync" class="toolbar apply-form">
69 <AntiforgeryToken/>
70 <label>
71 <span class="muted">@T["Apply to branch"]</span>
72 <select name="Branch">
73 @foreach (var branch in _branches)
74 {
75 <option value="@branch" selected="@(branch == Repository.DefaultBranch)">@branch</option>
76 }
77 </select>
78 </label>
79 <button type="submit" name="Action" value="revert" class="button">@T["Revert"]</button>
80 <button type="submit" name="Action" value="pick" class="button">@T["Cherry-pick"]</button>
81 </form>
82 }
83 </section>
84
85 <h3>
86 @T.Plural(_diff.Stats.Count, "{0} changed file", "{0} changed files"):
87 <span class="added">+@_diff.Stats.Sum(s => s.Added ?? 0)</span>
88 <span class="deleted">−@_diff.Stats.Sum(s => s.Deleted ?? 0)</span>
89 </h3>
90 @if (_commit.Parents.Count > 1)
91 {
92 <p class="muted">@T["Merge commit: changes are shown against the first parent."]</p>
93 }
94
95 <DiffOptions Path="@Urls.Commit(Repository, _commit.Sha)" Split="Split" IgnoreWhitespace="IgnoreWhitespace"/>
96 <DiffView Diff="_diff.Patch" Split="Split" Repository="Repository" HeadSha="@_commit.Sha"/>
97 }
98
99 @code {
100 [Parameter]
101 public string Sha { get; set; } = "";
102
103 [SupplyParameterFromQuery(Name = "view")]
104 private string? View { get; set; }
105
106 [SupplyParameterFromQuery(Name = "w")]
107 private string? Whitespace { get; set; }
108
109 [SupplyParameterFromForm(FormName = "apply-commit")]
110 private string? Branch { get; set; }
111
112 [SupplyParameterFromForm(FormName = "apply-commit")]
113 private string? Action { get; set; }
114
115 private CommitInfo? _commit;
116 private CommitDiff? _diff;
117 private List<string> _branches = [];
118 private string? _error;
119 private IReadOnlyList<string> _conflicts = [];
120
121 private bool Split => View == "split";
122 private bool IgnoreWhitespace => Whitespace == "1";
123
124 protected override async Task OnInitializedAsync()
125 {
126 if (!await LoadRepoAsync())
127 {
128 return;
129 }
130
131 // ResolveCommitAsync accepts hex only, so nothing else from the URL reaches git.
132 var sha = await Git.ResolveCommitAsync(RepoPath, Sha);
133 _commit = sha is null ? null : await Git.GetCommitAsync(RepoPath, sha);
134 if (_commit is null)
135 {
136 NotFound();
137 return;
138 }
139
140 _diff = await Git.GetDiffAsync(RepoPath, _commit.Sha, IgnoreWhitespace);
141 if (IsOwner)
142 {
143 _branches = (await Git.ListRefsAsync(RepoPath)).Where(r => r.Kind == RefKind.Branch).Select(r => r.Name).ToList();
144 }
145 }
146
147 private async Task ApplyAsync()
148 {
149 if (Repository is null || _commit is null || !IsOwner || Action is not ("revert" or "pick"))
150 {
151 return;
152 }
153
154 var user = await Db.Users.FindAsync(Me.UserId);
155 if (user is null)
156 {
157 return;
158 }
159
160 var revert = Action == "revert";
161 var result = await Refs.ApplyCommitAsync(Repository, Refs.IdentityFor(user), Branch ?? "", _commit.Sha, revert);
162 if (!result.Ok)
163 {
164 _error = T[result.Error!];
165 _conflicts = result.Conflicts ?? [];
166 return;
167 }
168
169 Redirect(Urls.Commit(Repository, result.Sha!));
170 }
171 }
added forge/Features/History/Commits.razor +104 −0View file
@@ -0,0 +1,104 @@
1 @page "/{Owner}/{Repo}/commits/{*RefAndPath}"
2 @inherits RepoPageBase
3
4 @if (Repository is not null && _resolved is not null)
5 {
6 <PageTitle>@T["Commits"] · @Repository.Owner.Username/@Repository.Name</PageTitle>
7
8 <RepoHeader Repository="Repository" Active="commits" IsOwner="IsOwner"/>
9
10 <div class="toolbar">
11 <RefSwitcher Refs="_refs" Current="@_resolved.Name" CurrentKind="_resolved.Kind"
12 UrlFor="@(name => Urls.Commits(Repository, name, _resolved.Path))"/>
13 @if (_resolved.Path.Length > 0)
14 {
15 <span class="muted">@T["History of path"]</span>
16 <Breadcrumbs Repository="Repository" RefName="@_resolved.Name" Path="@_resolved.Path"/>
17 <a class="toolbar-end" href="@Urls.Commits(Repository, _resolved.Name)">@T["Full history"]</a>
18 }
19 </div>
20
21 @if (_commits.Count == 0)
22 {
23 <div class="card empty"><p>@T["No more commits."]</p></div>
24 }
25 else
26 {
27 <CommitList Repository="Repository" Commits="_commits" GroupByDay="true"/>
28 }
29
30 <nav class="pager">
31 @if (CurrentPage > 1)
32 {
33 <a class="button" href="@PageUrl(CurrentPage - 1)" rel="prev">@T["← Newer"]</a>
34 }
35 @if (_hasMore)
36 {
37 <a class="button" href="@PageUrl(CurrentPage + 1)" rel="next">@T["Older →"]</a>
38 }
39 </nav>
40 }
41
42 @code {
43 public const int PageSize = 30;
44
45 [Parameter]
46 public string? RefAndPath { get; set; }
47
48 [SupplyParameterFromQuery(Name = "page")]
49 private int? PageNumber { get; set; }
50
51 private IReadOnlyList<GitRef> _refs = [];
52 private ResolvedRef? _resolved;
53 private IReadOnlyList<CommitInfo> _commits = [];
54 private bool _hasMore;
55
56 private int CurrentPage => Math.Clamp(PageNumber ?? 1, 1, 100_000);
57
58 private string PageUrl(int page) =>
59 Urls.Commits(Repository!, _resolved!.Name, _resolved.Path)
60 + (page > 1 ? "?page=" + page.ToString(CultureInfo.InvariantCulture) : "");
61
62 protected override async Task OnInitializedAsync()
63 {
64 if (!await LoadRepoAsync())
65 {
66 return;
67 }
68
69 var repo = Repository!;
70 _refs = await Git.ListRefsAsync(RepoPath);
71
72 if (string.IsNullOrEmpty(RefAndPath))
73 {
74 var branch = _refs.FirstOrDefault(r => r.Kind == RefKind.Branch && r.Name == repo.DefaultBranch)
75 ?? _refs.FirstOrDefault(r => r.Kind == RefKind.Branch);
76 if (branch is null)
77 {
78 Redirect(Urls.Repo(repo));
79 return;
80 }
81
82 _resolved = new ResolvedRef(branch.Name, ResolvedKind.Branch, branch.TargetSha, "");
83 }
84 else
85 {
86 _resolved = await Resolver.ResolveAsync(RepoPath, RefAndPath, _refs);
87 if (_resolved is null)
88 {
89 NotFound();
90 return;
91 }
92 }
93
94 // One extra row tells whether there is a next page, without counting the whole history.
95 var rows = await Git.LogAsync(
96 RepoPath,
97 _resolved.CommitSha,
98 _resolved.Path.Length == 0 ? null : _resolved.Path,
99 skip: (CurrentPage - 1) * PageSize,
100 take: PageSize + 1);
101 _hasMore = rows.Count > PageSize;
102 _commits = _hasMore ? rows.Take(PageSize).ToList() : rows;
103 }
104 }
added forge/Features/History/Compare.razor +326 −0View file
@@ -0,0 +1,326 @@
1 @page "/{Owner}/{Repo}/compare/{*Range}"
2 @inherits RepoPageBase
3 @inject RefService Refs
4 @inject PullRequestService Pulls
5 @inject ForgeDb Db
6
7 @if (Repository is not null)
8 {
9 <PageTitle>@T["Compare"] · @Repository.Owner.Username/@Repository.Name</PageTitle>
10 <HighlightAssets/>
11
12 <RepoHeader Repository="Repository" Active="branches" IsOwner="IsOwner"/>
13
14 @* A plain GET form: the page turns ?base=&head= into the canonical /compare/base...head address. *@
15 <form method="get" action="@Urls.Compare(Repository)" class="toolbar compare-form">
16 <label>
17 <span class="muted">@T["Merge into"]</span>
18 <select name="base">
19 @foreach (var name in _choices)
20 {
21 <option value="@name" selected="@(name == (_base?.Name ?? Repository.DefaultBranch))">@name</option>
22 }
23 </select>
24 </label>
25 <label>
26 <span class="muted">@T["from"]</span>
27 <select name="head">
28 @foreach (var name in _choices)
29 {
30 <option value="@name" selected="@(name == _head?.Name)">@name</option>
31 }
32 </select>
33 </label>
34 <button type="submit" class="button">@T["Show comparison"]</button>
35 </form>
36
37 @if (_error is not null)
38 {
39 <div class="alert error">
40 <p>@_error</p>
41 @if (_errorConflicts.Count > 0)
42 {
43 <ul>
44 @foreach (var file in _errorConflicts)
45 {
46 <li><code>@file</code></li>
47 }
48 </ul>
49 }
50 </div>
51 }
52
53 @if (_base is null || _head is null)
54 {
55 <div class="card empty"><p>@T["Choose two branches to compare."]</p></div>
56 }
57 else if (_base.CommitSha == _head.CommitSha)
58 {
59 <div class="card empty"><p>@T["These are the same commit. There is nothing to compare."]</p></div>
60 }
61 else
62 {
63 @if (_check is not null)
64 {
65 @if (_openPull is not null)
66 {
67 <p class="alert success">
68 @T["There is an open pull request for these branches:"]
69 <a href="@Urls.Pull(Repository, _openPull.Number)">#@_openPull.Number @_openPull.Title</a>
70 </p>
71 }
72 else if (!_check.NothingToMerge && !_check.Unrelated)
73 {
74 <details class="card">
75 <summary><strong>@T["Open a pull request"]</strong></summary>
76 <form method="post" @formname="open-pull" @onsubmit="OpenPullAsync" class="form">
77 <AntiforgeryToken/>
78 <label>
79 @T["Title"]
80 <input name="Title" value="@(Title ?? _defaultTitle)" required maxlength="@PullRequestService.MaxTitleLength"/>
81 </label>
82 <label>
83 <span>@T["Description"] <span class="muted">@T["(optional, Markdown)"]</span></span>
84 <textarea name="Description" rows="5">@Description</textarea>
85 </label>
86 <button type="submit" class="button primary">@T["Open pull request"]</button>
87 </form>
88 </details>
89 }
90
91 <section class="card">
92 <h2>@T["Merge {0} into {1}", _head.Name, _base.Name]</h2>
93 @if (_check.NothingToMerge)
94 {
95 <p class="muted">@T["{0} is already part of {1}. There is nothing to merge.", _head.Name, _base.Name]</p>
96 }
97 else if (_check.Unrelated)
98 {
99 <p class="alert warning">@T["The branches have no common history and cannot be merged here."]</p>
100 }
101 else if (_check.Conflicts.Count > 0)
102 {
103 <p class="alert warning">@T["These branches have conflicts."]</p>
104 <p>@T["Conflicting files:"]</p>
105 <ul>
106 @foreach (var file in _check.Conflicts)
107 {
108 <li><code>@file</code></li>
109 }
110 </ul>
111 <a class="button primary" href="@Urls.Conflicts(Repository, _base.Name, _head.Name)">@T["Resolve conflicts"]</a>
112 }
113 else
114 {
115 <p class="alert success">@T["These branches can be merged automatically."]</p>
116 <form method="post" @formname="merge" @onsubmit="MergeAsync" class="form">
117 <AntiforgeryToken/>
118 <MergeFields CanFastForward="_check.CanFastForward" AllowDelete="@(_head.Name != Repository.DefaultBranch)"
119 HeadName="@_head.Name" Message="@Message"/>
120 <button type="submit" class="button primary">@T["Merge"]</button>
121 </form>
122 }
123 </section>
124 }
125
126 <h3>@T.Plural(_commits.Count, "{0} commit", "{0} commits")</h3>
127 @if (_commits.Count == 0)
128 {
129 <div class="card empty"><p>@T["There are no new commits between these two commits."]</p></div>
130 }
131 else
132 {
133 <CommitList Repository="Repository" Commits="_commits"/>
134 @if (_commits.Count == MaxCommits)
135 {
136 <p class="muted">@T["Showing the first {0} commits.", MaxCommits]</p>
137 }
138 }
139
140 @if (_diff is not null)
141 {
142 <h3>
143 @T.Plural(_diff.Stats.Count, "{0} changed file", "{0} changed files"):
144 <span class="added">+@_diff.Stats.Sum(s => s.Added ?? 0)</span>
145 <span class="deleted">−@_diff.Stats.Sum(s => s.Deleted ?? 0)</span>
146 </h3>
147 <DiffOptions Path="@PageUrl(_direct)" Split="Split" IgnoreWhitespace="IgnoreWhitespace">
148 @* "..." shows what the head added since the branches diverged; ".." is the plain difference between the two tips. *@
149 <a href="@(PageUrl(!_direct) + DiffOptions.Query(Split, IgnoreWhitespace))">
150 @(_direct ? T["Show changes since the branches diverged"] : T["Show the direct difference between both ends"])
151 </a>
152 </DiffOptions>
153 <DiffView Diff="_diff.Patch" Split="Split" Repository="Repository" HeadSha="@_head.CommitSha"/>
154 }
155 }
156 }
157
158 @code {
159 private const int MaxCommits = 250;
160
161 /// <summary>
162 /// "&lt;base&gt;...&lt;head&gt;" or "&lt;base&gt;..&lt;head&gt;". Each side is a branch, a tag or a commit SHA.
163 /// Three dots diff from the point where the two diverged, two dots diff the two ends directly.
164 /// </summary>
165 [Parameter]
166 public string? Range { get; set; }
167
168 [SupplyParameterFromQuery(Name = "base")]
169 private string? BaseQuery { get; set; }
170
171 [SupplyParameterFromQuery(Name = "head")]
172 private string? HeadQuery { get; set; }
173
174 [SupplyParameterFromQuery(Name = "view")]
175 private string? View { get; set; }
176
177 [SupplyParameterFromQuery(Name = "w")]
178 private string? Whitespace { get; set; }
179
180 [SupplyParameterFromForm(FormName = "merge")]
181 private string? Method { get; set; }
182
183 [SupplyParameterFromForm(FormName = "merge")]
184 private string? Message { get; set; }
185
186 [SupplyParameterFromForm(FormName = "merge")]
187 private bool DeleteBranch { get; set; }
188
189 [SupplyParameterFromForm(FormName = "open-pull")]
190 private string? Title { get; set; }
191
192 [SupplyParameterFromForm(FormName = "open-pull")]
193 private string? Description { get; set; }
194
195 private List<string> _choices = [];
196 private ResolvedRef? _base;
197 private ResolvedRef? _head;
198 private bool _direct;
199 private string? _mergeBase;
200 private IReadOnlyList<CommitInfo> _commits = [];
201 private CommitDiff? _diff;
202 private MergeCheck? _check;
203 private PullRequest? _openPull;
204 private string _defaultTitle = "";
205 private string? _error;
206 private IReadOnlyList<string> _errorConflicts = [];
207
208 private bool Split => View == "split";
209 private bool IgnoreWhitespace => Whitespace == "1";
210
211 private string PageUrl(bool direct)
212 {
213 var url = Urls.Compare(Repository!, _base!.Name, _head!.Name);
214 return direct ? url.Replace("...", "..", StringComparison.Ordinal) : url;
215 }
216
217 protected override async Task OnInitializedAsync()
218 {
219 if (!await LoadRepoAsync())
220 {
221 return;
222 }
223
224 var repo = Repository!;
225 var refs = await Git.ListRefsAsync(RepoPath);
226 _choices = refs.Where(r => r.Kind == RefKind.Branch).Select(r => r.Name).ToList();
227
228 if (string.IsNullOrEmpty(Range))
229 {
230 if (!string.IsNullOrEmpty(BaseQuery) && !string.IsNullOrEmpty(HeadQuery))
231 {
232 Redirect(Urls.Compare(repo, BaseQuery, HeadQuery));
233 }
234
235 return; // Nothing chosen yet: the markup shows only the picker.
236 }
237
238 // Ref names cannot contain "..", so the first occurrence is the separator.
239 var split = Range.IndexOf("..", StringComparison.Ordinal);
240 if (split > 0)
241 {
242 _direct = !Range.AsSpan(split).StartsWith("...");
243 _base = await Resolver.ResolveExactAsync(RepoPath, Range[..split], refs);
244 _head = await Resolver.ResolveExactAsync(RepoPath, Range[(split + (_direct ? 2 : 3))..], refs);
245 }
246
247 if (_base is null || _head is null)
248 {
249 NotFound();
250 return;
251 }
252
253 if (_base.CommitSha == _head.CommitSha)
254 {
255 return;
256 }
257
258 _mergeBase = await Git.MergeBaseAsync(RepoPath, _base.CommitSha, _head.CommitSha);
259 _commits = await Git.LogRangeAsync(RepoPath, _base.CommitSha, _head.CommitSha, MaxCommits);
260 var from = _direct ? _base.CommitSha : _mergeBase ?? _base.CommitSha;
261 _diff = await Git.GetRangeDiffAsync(RepoPath, from, _head.CommitSha, IgnoreWhitespace);
262
263 // Merging is offered to the owner, and only between two branches.
264 if (IsOwner && _base.Kind == ResolvedKind.Branch && _head.Kind == ResolvedKind.Branch)
265 {
266 _check = await Refs.CheckMergeAsync(RepoPath, _base.CommitSha, _head.CommitSha);
267 _openPull = await Db.PullRequests.FirstOrDefaultAsync(p =>
268 p.RepoId == repo.Id
269 && p.Status == PullRequestStatus.Open
270 && p.BaseBranch == _base.Name
271 && p.HeadBranch == _head.Name);
272 _defaultTitle = _commits.Count == 1 ? _commits[0].Subject : _head.Name;
273 }
274 }
275
276 private async Task OpenPullAsync()
277 {
278 // _check is only set for the owner and two branches, so this also guards the handler.
279 if (Repository is null || _base is null || _head is null || _check is null)
280 {
281 return;
282 }
283
284 var (pull, error) = await Pulls.CreateAsync(Repository, Me.UserId!.Value, Title, Description, _base.Name, _head.Name);
285 if (pull is null)
286 {
287 _error = T[error!];
288 return;
289 }
290
291 Redirect(Urls.Pull(Repository, pull.Number));
292 }
293
294 private async Task MergeAsync()
295 {
296 if (Repository is null || _base is null || _head is null || _check is null)
297 {
298 return;
299 }
300
301 var user = await Db.Users.FindAsync(Me.UserId);
302 if (user is null)
303 {
304 return;
305 }
306
307 var result = await Refs.MergeAsync(
308 Repository, Refs.IdentityFor(user), _base.Name, _head.Name, MergeFields.Parse(Method), Message);
309 if (!result.Ok)
310 {
311 _error = T[result.Error!];
312 _errorConflicts = result.Conflicts ?? [];
313 return;
314 }
315
316 // A pull request for the same branches is done as well.
317 await Pulls.MarkMergedAsync(Repository, _base.Name, _head.Name, _mergeBase, _head.CommitSha, result.Sha);
318 if (DeleteBranch)
319 {
320 // Refused for the default or a protected branch; a failure here does not undo the merge.
321 await Refs.DeleteBranchAsync(Repository, _head.Name);
322 }
323
324 Redirect(Urls.Tree(Repository, _base.Name));
325 }
326 }
added forge/Features/History/Conflicts.razor +175 −0View file
@@ -0,0 +1,175 @@
1 @page "/{Owner}/{Repo}/conflicts/{*Range}"
2 @inherits RepoPageBase
3 @inject RefService Refs
4 @inject PullRequestService Pulls
5 @inject ForgeDb Db
6 @inject IHttpContextAccessor Http
7
8 @if (Repository is not null && _base is not null && _head is not null)
9 {
10 <PageTitle>@T["Resolve conflicts"] · @Repository.Owner.Username/@Repository.Name</PageTitle>
11
12 <RepoHeader Repository="Repository" Active="branches" IsOwner="IsOwner"/>
13
14 <h2>@T["Resolve conflicts: {0} into {1}", _head.Name, _base.Name]</h2>
15
16 @if (_error is not null)
17 {
18 <p class="alert error">@_error</p>
19 }
20
21 @if (_files.Count == 0)
22 {
23 <div class="card empty">
24 <p>@T["These branches have no conflicts."]</p>
25 <p><a href="@Urls.Compare(Repository, _base.Name, _head.Name)">@T["Back to the comparison"]</a></p>
26 </div>
27 }
28 else
29 {
30 <p class="muted">@T["Choose a version for every file, or edit the text and remove the conflict markers. Saving creates the merge commit."]</p>
31
32 <form method="post" @formname="resolve" @onsubmit="ResolveAsync" class="form">
33 <AntiforgeryToken/>
34 @* The SHAs the choices were made against; if a branch moves in the meantime, nothing is merged. *@
35 <input type="hidden" name="base_sha" value="@_base.CommitSha"/>
36 <input type="hidden" name="head_sha" value="@_head.CommitSha"/>
37
38 @for (var i = 0; i < _files.Count; i++)
39 {
40 var file = _files[i];
41 var editable = file.MarkerText is not null;
42 <fieldset class="conflict">
43 <legend><code>@file.Path</code></legend>
44 <label class="choice">
45 <input type="radio" name="@($"choice_{i}")" value="ours" required/>
46 @(file.OnBase ? T["Keep the version from {0}", _base.Name] : T["Delete the file (as on {0})", _base.Name])
47 </label>
48 <label class="choice">
49 <input type="radio" name="@($"choice_{i}")" value="theirs"/>
50 @(file.OnHead ? T["Take the version from {0}", _head.Name] : T["Delete the file (as on {0})", _head.Name])
51 </label>
52 @if (editable)
53 {
54 <label class="choice">
55 <input type="radio" name="@($"choice_{i}")" value="edit" checked/>
56 @T["Use the text below"]
57 </label>
58 <textarea name="@($"text_{i}")" rows="@Rows(file.MarkerText!)" class="code-input" spellcheck="false">@file.MarkerText</textarea>
59 }
60 else
61 {
62 <p class="muted small">@T["This file is binary or too large to edit here."]</p>
63 }
64 </fieldset>
65 }
66
67 <label>
68 <span>@T["Commit message"] <span class="muted">@T["(optional, a default is used if empty)"]</span></span>
69 <input name="message" maxlength="2000"/>
70 </label>
71 <button type="submit" class="button primary">@T["Resolve and merge"]</button>
72 </form>
73 }
74 }
75
76 @code {
77 /// <summary>"&lt;base&gt;...&lt;head&gt;", two branch names.</summary>
78 [Parameter]
79 public string? Range { get; set; }
80
81 private ResolvedRef? _base;
82 private ResolvedRef? _head;
83 private IReadOnlyList<ConflictFile> _files = [];
84 private string? _error;
85
86 private static int Rows(string text) => Math.Clamp(text.AsSpan().Count('\n') + 2, 6, 30);
87
88 protected override async Task OnInitializedAsync()
89 {
90 // Resolving a conflict writes a commit, so the whole page is for the owner only.
91 if (!await LoadRepoAsync(requireAdmin: true))
92 {
93 return;
94 }
95
96 var refs = await Git.ListRefsAsync(RepoPath);
97 var split = Range?.IndexOf("...", StringComparison.Ordinal) ?? -1;
98 if (split > 0)
99 {
100 _base = await Resolver.ResolveExactAsync(RepoPath, Range![..split], refs);
101 _head = await Resolver.ResolveExactAsync(RepoPath, Range[(split + 3)..], refs);
102 }
103
104 if (_base is not { Kind: ResolvedKind.Branch } || _head is not { Kind: ResolvedKind.Branch })
105 {
106 _base = null;
107 NotFound();
108 return;
109 }
110
111 _files = await Refs.GetConflictsAsync(RepoPath, _base.CommitSha, _head.CommitSha);
112 }
113
114 private async Task ResolveAsync()
115 {
116 var form = Http.HttpContext?.Request.Form;
117 if (Repository is null || _base is null || _head is null || form is null)
118 {
119 return;
120 }
121
122 var user = await Db.Users.FindAsync(Me.UserId);
123 if (user is null)
124 {
125 return;
126 }
127
128 // The form has one group of fields per file, numbered in the order the files are listed.
129 var resolutions = new Dictionary<string, Resolution>(StringComparer.Ordinal);
130 for (var i = 0; i < _files.Count; i++)
131 {
132 var file = _files[i];
133 switch (form[$"choice_{i}"].ToString())
134 {
135 case "ours":
136 resolutions[file.Path] = new Resolution(ResolutionKind.Ours);
137 break;
138 case "theirs":
139 resolutions[file.Path] = new Resolution(ResolutionKind.Theirs);
140 break;
141 case "edit" when file.MarkerText is not null:
142 // Browsers submit textarea line breaks as CRLF; keep the line endings the file had.
143 var text = form[$"text_{i}"].ToString().Replace("\r\n", "\n");
144 if (file.MarkerText.Contains("\r\n", StringComparison.Ordinal))
145 {
146 text = text.Replace("\n", "\r\n");
147 }
148
149 resolutions[file.Path] = new Resolution(ResolutionKind.Edited, text);
150 break;
151 }
152 }
153
154 var mergeBase = await Git.MergeBaseAsync(RepoPath, _base.CommitSha, _head.CommitSha);
155 var result = await Refs.ResolveAndMergeAsync(
156 Repository,
157 Refs.IdentityFor(user),
158 _base.Name,
159 _head.Name,
160 form["base_sha"].ToString(),
161 form["head_sha"].ToString(),
162 resolutions,
163 form["message"].ToString());
164 if (!result.Ok)
165 {
166 _error = result.Conflicts is { Count: > 0 }
167 ? $"{T[result.Error!]} ({string.Join(", ", result.Conflicts)})"
168 : T[result.Error!];
169 return;
170 }
171
172 await Pulls.MarkMergedAsync(Repository, _base.Name, _head.Name, mergeBase, _head.CommitSha, result.Sha);
173 Redirect(Urls.Commit(Repository, result.Sha!));
174 }
175 }
added forge/Features/History/DiffOptions.razor +34 −0View file
@@ -0,0 +1,34 @@
1 @* Switches for a diff: unified or side by side, and whether whitespace-only changes count. Plain links, no script. *@
2 <nav class="diff-options">
3 <span class="segmented">
4 <a class="@(Split ? "" : "active")" href="@(Path + Query(false, IgnoreWhitespace))">@T["Unified"]</a>
5 <a class="@(Split ? "active" : "")" href="@(Path + Query(true, IgnoreWhitespace))">@T["Side by side"]</a>
6 </span>
7 <a href="@(Path + Query(Split, !IgnoreWhitespace))">@(IgnoreWhitespace ? T["Show whitespace changes"] : T["Hide whitespace changes"])</a>
8 @ChildContent
9 </nav>
10
11 @code {
12 /// <summary>Address of the page without its query string.</summary>
13 [Parameter, EditorRequired]
14 public string Path { get; set; } = "";
15
16 [Parameter]
17 public bool Split { get; set; }
18
19 [Parameter]
20 public bool IgnoreWhitespace { get; set; }
21
22 /// <summary>Extra links shown after the standard ones.</summary>
23 [Parameter]
24 public RenderFragment? ChildContent { get; set; }
25
26 /// <summary>The query string that selects these options; empty for the defaults.</summary>
27 public static string Query(bool split, bool ignoreWhitespace) => (split, ignoreWhitespace) switch
28 {
29 (true, true) => "?view=split&w=1",
30 (true, false) => "?view=split",
31 (false, true) => "?w=1",
32 _ => "",
33 };
34 }
added forge/Features/History/DiffRows.cs +156 −0View file
@@ -0,0 +1,156 @@
1 using Forge.Git;
2
3 namespace Forge.Features.History;
4
5 /// <summary>The part of a line that differs from its counterpart, as character offsets [Start, End).</summary>
6 public readonly record struct ChangeRange(int Start, int End);
7
8 public sealed record DiffCell(DiffLine Line, ChangeRange? Change);
9
10 /// <summary>One row of a side-by-side diff. A side is null where the other side has a line with no counterpart.</summary>
11 public sealed record DiffRow(DiffCell? Left, DiffCell? Right);
12
13 /// <summary>
14 /// Pairs removed lines with the added lines that replaced them. The pairing gives the side-by-side
15 /// layout its rows, and gives both layouts the within-line highlight of what actually changed.
16 /// </summary>
17 public static class DiffRows
18 {
19 /// <summary>Rows for the side-by-side layout.</summary>
20 public static List<DiffRow> Pair(DiffHunk hunk)
21 {
22 var rows = new List<DiffRow>();
23 foreach (var (removed, added, context) in Blocks(hunk))
24 {
25 if (context is not null)
26 {
27 var cell = new DiffCell(context, null);
28 rows.Add(new DiffRow(cell, cell));
29 continue;
30 }
31
32 for (var i = 0; i < Math.Max(removed.Count, added.Count); i++)
33 {
34 var left = i < removed.Count ? removed[i] : null;
35 var right = i < added.Count ? added[i] : null;
36 var (leftChange, rightChange) = left is not null && right is not null
37 ? Compare(left.Text, right.Text)
38 : (null, null);
39 rows.Add(new DiffRow(
40 left is null ? null : new DiffCell(left, leftChange),
41 right is null ? null : new DiffCell(right, rightChange)));
42 }
43 }
44
45 return rows;
46 }
47
48 /// <summary>Within-line changes for the unified layout, keyed by line.</summary>
49 public static Dictionary<DiffLine, ChangeRange?> Changes(DiffHunk hunk)
50 {
51 var changes = new Dictionary<DiffLine, ChangeRange?>();
52 foreach (var (removed, added, _) in Blocks(hunk))
53 {
54 for (var i = 0; i < Math.Min(removed.Count, added.Count); i++)
55 {
56 var (left, right) = Compare(removed[i].Text, added[i].Text);
57 changes[removed[i]] = left;
58 changes[added[i]] = right;
59 }
60 }
61
62 return changes;
63 }
64
65 /// <summary>
66 /// What differs between two versions of a line: everything between their common start and common end.
67 /// Returns nothing when the lines have no meaningful part in common, since then the whole line changed.
68 /// </summary>
69 public static (ChangeRange? Old, ChangeRange? New) Compare(string oldText, string newText)
70 {
71 if (oldText == newText)
72 {
73 return (null, null);
74 }
75
76 var limit = Math.Min(oldText.Length, newText.Length);
77 var prefix = 0;
78 while (prefix < limit && oldText[prefix] == newText[prefix])
79 {
80 prefix++;
81 }
82
83 // Never cut a surrogate pair in half.
84 if (prefix > 0 && char.IsHighSurrogate(oldText[prefix - 1]))
85 {
86 prefix--;
87 }
88
89 var suffix = 0;
90 while (suffix < limit - prefix && oldText[^(suffix + 1)] == newText[^(suffix + 1)])
91 {
92 suffix++;
93 }
94
95 if (suffix > 0 && char.IsLowSurrogate(oldText[^suffix]))
96 {
97 suffix--;
98 }
99
100 // Shared indentation alone says nothing about what changed.
101 var shared = oldText.AsSpan(0, prefix).Trim().Length + oldText.AsSpan(oldText.Length - suffix).Trim().Length;
102 if (shared == 0)
103 {
104 return (null, null);
105 }
106
107 return (
108 new ChangeRange(prefix, oldText.Length - suffix),
109 new ChangeRange(prefix, newText.Length - suffix));
110 }
111
112 /// <summary>Splits a hunk into context lines and blocks of removed lines followed by added lines.</summary>
113 private static IEnumerable<(List<DiffLine> Removed, List<DiffLine> Added, DiffLine? Context)> Blocks(DiffHunk hunk)
114 {
115 var removed = new List<DiffLine>();
116 var added = new List<DiffLine>();
117 foreach (var line in hunk.Lines)
118 {
119 switch (line.Kind)
120 {
121 case DiffLineKind.Deleted:
122 if (added.Count > 0)
123 {
124 yield return (removed, added, null);
125 removed = [];
126 added = [];
127 }
128
129 removed.Add(line);
130 break;
131
132 case DiffLineKind.Added:
133 added.Add(line);
134 break;
135
136 case DiffLineKind.Context:
137 if (removed.Count > 0 || added.Count > 0)
138 {
139 yield return (removed, added, null);
140 removed = [];
141 added = [];
142 }
143
144 yield return ([], [], line);
145 break;
146
147 // "\ No newline at end of file" belongs to the line before it and is not a row of its own.
148 }
149 }
150
151 if (removed.Count > 0 || added.Count > 0)
152 {
153 yield return (removed, added, null);
154 }
155 }
156 }
added forge/Features/History/DiffView.razor +208 −0View file
@@ -0,0 +1,208 @@
1 @* Renders a parsed diff: a file list to jump from, then one collapsible table per file, unified or side by side. *@
2 @if (Diff.Truncated)
3 {
4 <p class="alert warning">@T["The diff is too large; only part of it is shown."]</p>
5 }
6
7 @if (Diff.Files.Count > 1)
8 {
9 <ul class="diff-index">
10 @for (var i = 0; i < Diff.Files.Count; i++)
11 {
12 var file = Diff.Files[i];
13 <li>
14 <span class="stat-counts">
15 @if (file.IsBinary)
16 {
17 <span class="muted">@T["bin"]</span>
18 }
19 else
20 {
21 <span class="added">+@file.Added</span>
22 <span class="deleted">−@file.Deleted</span>
23 }
24 </span>
25 <a href="#diff-@i">@file.DisplayPath</a>
26 </li>
27 }
28 </ul>
29 }
30
31 @for (var i = 0; i < Diff.Files.Count; i++)
32 {
33 var file = Diff.Files[i];
34 var language = FileTypes.Language(System.IO.Path.GetFileName(file.DisplayPath));
35 <details class="diff-file" id="diff-@i" open>
36 <summary class="diff-file-head">
37 <span class="badge @ChangeClass(file.Change)">@ChangeLabel(file.Change)</span>
38 <span class="diff-path">
39 @if (file.Change is FileChange.Renamed or FileChange.Copied)
40 {
41 <span>@file.OldPath → </span>
42 }
43 @file.DisplayPath
44 </span>
45 <span class="diff-counts">
46 <span class="added">+@file.Added</span>
47 <span class="deleted">−@file.Deleted</span>
48 </span>
49 @if (Repository is not null && HeadSha is not null && file.Change != FileChange.Deleted)
50 {
51 <a class="small" href="@Urls.Blob(Repository, HeadSha, file.NewPath)">@T["View file"]</a>
52 }
53 </summary>
54
55 @if (file.IsBinary)
56 {
57 <p class="diff-note muted">@T["Binary file, diff not shown."]</p>
58 }
59 else if (file.TooLarge)
60 {
61 <p class="diff-note muted">@T["The diff is too large (more than {0} lines).", GitParsers.MaxDiffLinesPerFile]</p>
62 }
63 else if (file.Hunks.Count == 0)
64 {
65 <p class="diff-note muted">@(file.Change is FileChange.Renamed or FileChange.Copied ? T["No content changes."] : T["No content changes (empty file or mode change)."])</p>
66 }
67 else if (Split)
68 {
69 <table class="diff split">
70 <tbody>
71 @foreach (var hunk in file.Hunks)
72 {
73 <tr class="hunk">
74 <td class="ln"></td>
75 <td class="diff-code" colspan="3">@hunk.Header</td>
76 </tr>
77 @foreach (var row in DiffRows.Pair(hunk))
78 {
79 <tr>
80 @if (row.Left is { } left)
81 {
82 <td class="ln @SideClass(left.Line.Kind)">@left.Line.OldNumber</td>
83 <td class="diff-code @SideClass(left.Line.Kind)">@Code(left, language)</td>
84 }
85 else
86 {
87 <td class="ln blank"></td>
88 <td class="diff-code blank"></td>
89 }
90 @if (row.Right is { } right)
91 {
92 <td class="ln @SideClass(right.Line.Kind)">@right.Line.NewNumber</td>
93 <td class="diff-code @SideClass(right.Line.Kind)">@Code(right, language)</td>
94 }
95 else
96 {
97 <td class="ln blank"></td>
98 <td class="diff-code blank"></td>
99 }
100 </tr>
101 }
102 }
103 </tbody>
104 </table>
105 }
106 else
107 {
108 <table class="diff">
109 <tbody>
110 @foreach (var hunk in file.Hunks)
111 {
112 var changes = DiffRows.Changes(hunk);
113 <tr class="hunk">
114 <td class="ln"></td>
115 <td class="ln"></td>
116 <td class="diff-code">@hunk.Header</td>
117 </tr>
118 @foreach (var line in hunk.Lines)
119 {
120 <tr class="@LineClass(line.Kind)">
121 <td class="ln">@line.OldNumber</td>
122 <td class="ln">@line.NewNumber</td>
123 @* One line on purpose: the cell preserves whitespace, so any stray space would show. *@
124 <td class="diff-code"><span class="marker">@Marker(line.Kind)</span>@(line.Kind == DiffLineKind.NoNewline ? Note(T["No newline at end of file"]) : Code(new DiffCell(line, changes.GetValueOrDefault(line)), language))</td>
125 </tr>
126 }
127 }
128 </tbody>
129 </table>
130 }
131 </details>
132 }
133
134 @code {
135 [Parameter, EditorRequired]
136 public ParsedDiff Diff { get; set; } = null!;
137
138 /// <summary>Two columns, old on the left and new on the right, instead of one interleaved column.</summary>
139 [Parameter]
140 public bool Split { get; set; }
141
142 /// <summary>With <see cref="HeadSha"/>, each file gets a link to its full content at that commit.</summary>
143 [Parameter]
144 public Repository? Repository { get; set; }
145
146 [Parameter]
147 public string? HeadSha { get; set; }
148
149 /// <summary>
150 /// One line of code. The part that differs from its counterpart is wrapped in a span, and the same
151 /// range is repeated in data attributes: the script that adds syntax colours rebuilds the line and re-applies it.
152 /// </summary>
153 private static RenderFragment Code(DiffCell cell, string? language) => __builder =>
154 {
155 var text = cell.Line.Text;
156 if (cell.Change is { } c)
157 {
158 <span class="line" data-lang="@language" data-cs="@c.Start" data-ce="@c.End">@(text[..c.Start])<span class="chg">@(text[c.Start..c.End])</span>@(text[c.End..])</span>
159 }
160 else
161 {
162 <span class="line" data-lang="@language">@text</span>
163 }
164 };
165
166 private static RenderFragment Note(string text) => __builder =>
167 {
168 <span>@text</span>
169 };
170
171 private string ChangeLabel(FileChange change) => change switch
172 {
173 FileChange.Added => T["added"],
174 FileChange.Deleted => T["deleted"],
175 FileChange.Renamed => T["renamed"],
176 FileChange.Copied => T["copied"],
177 _ => T["modified"],
178 };
179
180 private static string ChangeClass(FileChange change) => change switch
181 {
182 FileChange.Added => "badge-added",
183 FileChange.Deleted => "badge-deleted",
184 _ => "",
185 };
186
187 private static string LineClass(DiffLineKind kind) => kind switch
188 {
189 DiffLineKind.Added => "add",
190 DiffLineKind.Deleted => "del",
191 DiffLineKind.NoNewline => "meta",
192 _ => "ctx",
193 };
194
195 private static string SideClass(DiffLineKind kind) => kind switch
196 {
197 DiffLineKind.Added => "add",
198 DiffLineKind.Deleted => "del",
199 _ => "",
200 };
201
202 private static string Marker(DiffLineKind kind) => kind switch
203 {
204 DiffLineKind.Added => "+",
205 DiffLineKind.Deleted => "-",
206 _ => " ",
207 };
208 }
added forge/Features/History/MergeFields.razor +47 −0View file
@@ -0,0 +1,47 @@
1 @* The inputs of a merge form. The page supplies the <form> around them and the handler. *@
2 <label>
3 @T["Method"]
4 <select name="Method">
5 <option value="merge">@T["Merge commit"]</option>
6 <option value="squash">@T["Squash into one commit"]</option>
7 <option value="rebase">@T["Rebase onto the base branch"]</option>
8 @if (CanFastForward)
9 {
10 <option value="ff">@T["Fast-forward"]</option>
11 }
12 </select>
13 </label>
14 <label>
15 <span>@T["Commit message"] <span class="muted">@T["(optional, a default is used if empty)"]</span></span>
16 <input name="Message" value="@Message" maxlength="2000"/>
17 </label>
18 @if (AllowDelete)
19 {
20 <label class="choice">
21 <input type="checkbox" name="DeleteBranch" value="true"/>
22 @T["Delete branch {0} after merging", HeadName]
23 </label>
24 }
25
26 @code {
27 [Parameter]
28 public bool CanFastForward { get; set; }
29
30 [Parameter]
31 public bool AllowDelete { get; set; }
32
33 [Parameter]
34 public string HeadName { get; set; } = "";
35
36 [Parameter]
37 public string? Message { get; set; }
38
39 /// <summary>Reads the value of the method select.</summary>
40 public static MergeMethod Parse(string? value) => value switch
41 {
42 "squash" => MergeMethod.Squash,
43 "rebase" => MergeMethod.Rebase,
44 "ff" => MergeMethod.FastForward,
45 _ => MergeMethod.MergeCommit,
46 };
47 }
added forge/Features/History/RefService.cs +570 −0View file
@@ -0,0 +1,570 @@
1 using System.Text;
2 using Forge.Data;
3 using Forge.Features.SmartHttp;
4 using Forge.Git;
5 using Forge.Localization;
6 using Microsoft.EntityFrameworkCore;
7 using Microsoft.Extensions.Options;
8
9 namespace Forge.Features.History;
10
11 public enum MergeMethod
12 {
13 /// <summary>A commit with two parents.</summary>
14 MergeCommit,
15
16 /// <summary>One new commit on the base branch carrying all changes; the other branch's history is not linked.</summary>
17 Squash,
18
19 /// <summary>The head's commits are re-created one by one on top of the base branch, giving a linear history.</summary>
20 Rebase,
21
22 /// <summary>No new commit: the base branch simply moves forward. Only possible when it has not diverged.</summary>
23 FastForward,
24 }
25
26 /// <summary>What merging two commits would involve, computed without changing anything.</summary>
27 /// <param name="NothingToMerge">The head is already contained in the base.</param>
28 /// <param name="CanFastForward">The base has no commits the head lacks.</param>
29 /// <param name="Conflicts">Files that need a manual merge; empty when the merge is clean.</param>
30 /// <param name="Unrelated">The two histories share no commit.</param>
31 public sealed record MergeCheck(bool NothingToMerge, bool CanFastForward, IReadOnlyList<string> Conflicts, bool Unrelated)
32 {
33 public bool CanMerge => !NothingToMerge && !Unrelated && Conflicts.Count == 0;
34 }
35
36 /// <param name="Error">An English message (a translation key), or null on success.</param>
37 /// <param name="Sha">On success, the commit the ref points at now (or pointed at, for a deletion).</param>
38 /// <param name="Conflicts">For a refused merge, the conflicting files.</param>
39 public sealed record RefResult(string? Error, string? Sha = null, IReadOnlyList<string>? Conflicts = null)
40 {
41 public bool Ok => Error is null;
42 }
43
44 public enum ResolutionKind
45 {
46 /// <summary>Take the file as it is on the base branch.</summary>
47 Ours,
48
49 /// <summary>Take the file as it is on the head branch.</summary>
50 Theirs,
51
52 /// <summary>Use text the user edited by hand.</summary>
53 Edited,
54 }
55
56 public sealed record Resolution(ResolutionKind Kind, string? Text = null);
57
58 /// <summary>One conflicted file, as offered for resolution.</summary>
59 /// <param name="MarkerText">The file with conflict markers, or null when it is binary or too large to edit.</param>
60 public sealed record ConflictFile(string Path, bool OnBase, bool OnHead, string? MarkerText);
61
62 /// <summary>
63 /// Changes refs from the web UI: merging, replaying commits, and creating or deleting branches and tags.
64 /// Every change takes the repository's push lock and is recorded exactly like a push,
65 /// so webhooks fire and "pushed at" moves whether a change came from git or from the browser.
66 /// </summary>
67 public sealed class RefService(
68 ForgeDb db,
69 GitRepo git,
70 RefResolver resolver,
71 RepoPaths paths,
72 PushLocks locks,
73 PushRecorder recorder,
74 IOptions<ForgeOptions> options)
75 {
76 public const int MaxReplayedCommits = 200;
77 public const int MaxEditableConflictBytes = 256 * 1024;
78
79 private const string Heads = "refs/heads/";
80 private const string TagsPrefix = "refs/tags/";
81
82 private static readonly string ConflictError =
83 Localizer.Key("The branches have conflicts and cannot be merged automatically.");
84
85 private static readonly string MovedError =
86 Localizer.Key("The branch changed in the meantime. Reload the page and try again.");
87
88 /// <summary>The author of commits Forge creates for a user. Accounts have no e-mail, so one is derived from the site's host.</summary>
89 public GitIdentity IdentityFor(User user)
90 {
91 var host = Uri.TryCreate(options.Value.BaseUrl, UriKind.Absolute, out var uri) ? uri.Host : "forge.invalid";
92 return new GitIdentity(user.DisplayName, $"{user.Username}@{host}");
93 }
94
95 public async Task<MergeCheck> CheckMergeAsync(string repoPath, string baseSha, string headSha, CancellationToken ct = default)
96 {
97 var mergeBase = await git.MergeBaseAsync(repoPath, baseSha, headSha, ct);
98 if (mergeBase is null)
99 {
100 return new MergeCheck(false, false, [], Unrelated: true);
101 }
102
103 if (mergeBase == headSha)
104 {
105 return new MergeCheck(NothingToMerge: true, false, [], false);
106 }
107
108 if (mergeBase == baseSha)
109 {
110 return new MergeCheck(false, CanFastForward: true, [], false);
111 }
112
113 var merged = await git.MergeTreeAsync(repoPath, baseSha, headSha, ct);
114 return new MergeCheck(false, false, merged.Conflicts, Unrelated: merged is { IsClean: false, Conflicts.Count: 0 });
115 }
116
117 /// <summary>Merges branch <paramref name="headBranch"/> into branch <paramref name="baseBranch"/>.</summary>
118 public Task<RefResult> MergeAsync(
119 Repository repo,
120 GitIdentity who,
121 string baseBranch,
122 string headBranch,
123 MergeMethod method,
124 string? message,
125 CancellationToken ct = default) =>
126 MutateAsync(repo, async path =>
127 {
128 var (target, source, error) = await FindBranchesAsync(path, baseBranch, headBranch, ct);
129 if (error is not null)
130 {
131 return new RefResult(error);
132 }
133
134 var check = await CheckMergeAsync(path, target!.Sha, source!.Sha, ct);
135 if (check.NothingToMerge)
136 {
137 return new RefResult(Localizer.Key("There is nothing to merge."));
138 }
139
140 if (check.Unrelated)
141 {
142 return new RefResult(Localizer.Key("The branches have no common history and cannot be merged here."));
143 }
144
145 string newSha;
146 switch (method)
147 {
148 case MergeMethod.FastForward:
149 if (!check.CanFastForward)
150 {
151 return new RefResult(Localizer.Key("Fast-forward is not possible because the branches have diverged."));
152 }
153
154 newSha = source.Sha;
155 break;
156
157 case MergeMethod.Rebase:
158 var rebased = await RebaseAsync(path, target, source, who, ct);
159 if (!rebased.Ok)
160 {
161 return rebased;
162 }
163
164 newSha = rebased.Sha!;
165 break;
166
167 default:
168 var merged = await git.MergeTreeAsync(path, target.Sha, source.Sha, ct);
169 if (!merged.IsClean)
170 {
171 return new RefResult(ConflictError, Conflicts: merged.Conflicts);
172 }
173
174 var squash = method == MergeMethod.Squash;
175 var text = string.IsNullOrWhiteSpace(message)
176 ? await DefaultMessageAsync(path, target, source, squash, ct)
177 : message.Trim();
178 string[] parents = squash ? [target.Sha] : [target.Sha, source.Sha];
179 newSha = await git.CommitTreeAsync(path, merged.TreeSha!, parents, text, who, ct);
180 break;
181 }
182
183 // Compare-and-swap: if someone pushed to the base branch since it was read, nothing is overwritten.
184 return await git.UpdateRefAsync(path, target.FullName, newSha, target.Sha, ct)
185 ? new RefResult(null, newSha)
186 : new RefResult(MovedError);
187 });
188
189 /// <summary>The conflicted files of a merge, with the content needed to resolve them in the browser.</summary>
190 public async Task<IReadOnlyList<ConflictFile>> GetConflictsAsync(string repoPath, string baseSha, string headSha, CancellationToken ct = default)
191 {
192 var merged = await git.MergeTreeAsync(repoPath, baseSha, headSha, ct);
193 if (merged.ConflictTreeSha is null)
194 {
195 return [];
196 }
197
198 var files = new List<ConflictFile>();
199 foreach (var path in merged.Conflicts)
200 {
201 var ours = await git.GetEntryAsync(repoPath, baseSha, path, ct);
202 var theirs = await git.GetEntryAsync(repoPath, headSha, path, ct);
203 var marked = await git.GetEntryAsync(repoPath, merged.ConflictTreeSha, path, ct);
204
205 string? text = null;
206 if (marked is { IsBlob: true, Size: <= MaxEditableConflictBytes })
207 {
208 var blob = await git.ReadBlobAsync(repoPath, marked.Sha, MaxEditableConflictBytes, ct);
209 text = blob.IsBinary ? null : blob.Text;
210 }
211
212 files.Add(new ConflictFile(path, ours is { IsBlob: true }, theirs is { IsBlob: true }, text));
213 }
214
215 return files;
216 }
217
218 /// <summary>
219 /// Merges two conflicting branches using the user's choice for every conflicted file.
220 /// The expected SHAs are the ones the user was looking at; if either branch moved, nothing happens.
221 /// </summary>
222 public Task<RefResult> ResolveAndMergeAsync(
223 Repository repo,
224 GitIdentity who,
225 string baseBranch,
226 string headBranch,
227 string expectedBaseSha,
228 string expectedHeadSha,
229 IReadOnlyDictionary<string, Resolution> resolutions,
230 string? message,
231 CancellationToken ct = default) =>
232 MutateAsync(repo, async path =>
233 {
234 var (target, source, error) = await FindBranchesAsync(path, baseBranch, headBranch, ct);
235 if (error is not null)
236 {
237 return new RefResult(error);
238 }
239
240 if (target!.Sha != expectedBaseSha || source!.Sha != expectedHeadSha)
241 {
242 return new RefResult(MovedError);
243 }
244
245 var merged = await git.MergeTreeAsync(path, target.Sha, source.Sha, ct);
246 var tree = merged.TreeSha;
247 if (tree is null)
248 {
249 if (merged.ConflictTreeSha is null)
250 {
251 return new RefResult(Localizer.Key("The branches have no common history and cannot be merged here."));
252 }
253
254 var changes = new Dictionary<string, (string Mode, string BlobSha)?>(StringComparer.Ordinal);
255 foreach (var file in merged.Conflicts)
256 {
257 if (!resolutions.TryGetValue(file, out var resolution))
258 {
259 return new RefResult(Localizer.Key("Choose a resolution for every conflicting file."), Conflicts: merged.Conflicts);
260 }
261
262 var ours = await git.GetEntryAsync(path, target.Sha, file, ct);
263 var theirs = await git.GetEntryAsync(path, source.Sha, file, ct);
264 switch (resolution.Kind)
265 {
266 // A side that does not have the file resolves to "the file is deleted".
267 case ResolutionKind.Ours:
268 changes[file] = ours is { IsBlob: true } ? (ours.Mode, ours.Sha) : null;
269 break;
270 case ResolutionKind.Theirs:
271 changes[file] = theirs is { IsBlob: true } ? (theirs.Mode, theirs.Sha) : null;
272 break;
273 default:
274 var text = resolution.Text ?? "";
275 if (HasConflictMarkers(text))
276 {
277 return new RefResult(Localizer.Key("The edited text still contains conflict markers."), Conflicts: [file]);
278 }
279
280 var blob = await git.WriteBlobAsync(path, Encoding.UTF8.GetBytes(text), ct);
281 changes[file] = (ours?.Mode ?? theirs?.Mode ?? "100644", blob);
282 break;
283 }
284 }
285
286 tree = await git.BuildTreeAsync(path, merged.ConflictTreeSha, changes, ct);
287 }
288
289 var commitMessage = string.IsNullOrWhiteSpace(message)
290 ? await DefaultMessageAsync(path, target, source, squash: false, ct)
291 : message.Trim();
292 var commit = await git.CommitTreeAsync(path, tree, [target.Sha, source.Sha], commitMessage, who, ct);
293 return await git.UpdateRefAsync(path, target.FullName, commit, target.Sha, ct)
294 ? new RefResult(null, commit)
295 : new RefResult(MovedError);
296 });
297
298 /// <summary>Applies one commit's change to a branch (cherry-pick), or its inverse (revert), as a new commit.</summary>
299 public Task<RefResult> ApplyCommitAsync(
300 Repository repo,
301 GitIdentity who,
302 string branchName,
303 string commitSha,
304 bool revert,
305 CancellationToken ct = default) =>
306 MutateAsync(repo, async path =>
307 {
308 var refs = await git.ListRefsAsync(path, ct);
309 var branch = refs.FirstOrDefault(r => r.Kind == RefKind.Branch && r.Name == branchName);
310 if (branch is null)
311 {
312 return new RefResult(Localizer.Key("There is no such branch in the repository."));
313 }
314
315 var commit = await git.GetCommitAsync(path, commitSha, ct);
316 if (commit is not { Parents.Count: 1 })
317 {
318 return new RefResult(Localizer.Key("Merge commits and the first commit cannot be reverted or cherry-picked here."));
319 }
320
321 // A three-way merge with a chosen ancestor: picking replays parent→commit, reverting replays commit→parent.
322 var parent = commit.Parents[0];
323 var merged = revert
324 ? await git.MergeTreeAsync(path, branch.Sha, parent, ct, mergeBaseSha: commit.Sha)
325 : await git.MergeTreeAsync(path, branch.Sha, commit.Sha, ct, mergeBaseSha: parent);
326 if (!merged.IsClean)
327 {
328 return new RefResult(
329 Localizer.Key("The change conflicts with the branch and cannot be applied automatically."),
330 Conflicts: merged.Conflicts);
331 }
332
333 if (merged.TreeSha == await git.GetRootTreeShaAsync(path, branch.Sha, ct))
334 {
335 return new RefResult(Localizer.Key("The branch already contains this change. There is nothing to do."));
336 }
337
338 var original = FullMessage(commit);
339 var newSha = revert
340 ? await git.CommitTreeAsync(
341 path, merged.TreeSha!, [branch.Sha],
342 $"Revert \"{commit.Subject}\"\n\nThis reverts commit {commit.Sha}.", who, ct)
343 : await git.CommitTreeAsync(
344 path, merged.TreeSha!, [branch.Sha],
345 $"{original}\n\n(cherry picked from commit {commit.Sha})", who, ct,
346 new GitIdentity(commit.AuthorName, commit.AuthorEmail), commit.AuthorDateRaw);
347
348 return await git.UpdateRefAsync(path, branch.FullName, newSha, branch.Sha, ct)
349 ? new RefResult(null, newSha)
350 : new RefResult(MovedError);
351 });
352
353 public Task<RefResult> CreateBranchAsync(Repository repo, string? name, string? from, CancellationToken ct = default) =>
354 CreateAsync(
355 repo, Heads, RefKind.Branch, name, from,
356 Localizer.Key("This is not a valid branch name."),
357 Localizer.Key("A branch with this name already exists."),
358 ct);
359
360 public Task<RefResult> CreateTagAsync(Repository repo, string? name, string? from, CancellationToken ct = default) =>
361 CreateAsync(
362 repo, TagsPrefix, RefKind.Tag, name, from,
363 Localizer.Key("This is not a valid tag name."),
364 Localizer.Key("A tag with this name already exists."),
365 ct);
366
367 public Task<RefResult> DeleteBranchAsync(Repository repo, string? name, CancellationToken ct = default) =>
368 MutateAsync(repo, async path =>
369 {
370 var refs = await git.ListRefsAsync(path, ct);
371 var branch = refs.FirstOrDefault(r => r.Kind == RefKind.Branch && r.Name == name);
372 if (branch is null)
373 {
374 return new RefResult(Localizer.Key("There is no such branch in the repository."));
375 }
376
377 // HEAD must keep pointing at something, and clones check this branch out.
378 if (branch.Name == repo.DefaultBranch || branch.Name == await git.GetHeadBranchAsync(path, ct))
379 {
380 return new RefResult(Localizer.Key("The default branch cannot be deleted. Choose another default branch first."));
381 }
382
383 var rules = await db.BranchProtections.Where(r => r.RepoId == repo.Id).ToListAsync(ct);
384 if (BranchRules.Find(rules, branch.Name) is not null)
385 {
386 return new RefResult(Localizer.Key("This branch is protected and cannot be deleted."));
387 }
388
389 return await git.UpdateRefAsync(path, branch.FullName, null, branch.Sha, ct)
390 ? new RefResult(null, branch.Sha)
391 : new RefResult(MovedError);
392 });
393
394 public Task<RefResult> DeleteTagAsync(Repository repo, string? name, CancellationToken ct = default) =>
395 MutateAsync(repo, async path =>
396 {
397 var refs = await git.ListRefsAsync(path, ct);
398 var tag = refs.FirstOrDefault(r => r.Kind == RefKind.Tag && r.Name == name);
399 if (tag is null)
400 {
401 return new RefResult(Localizer.Key("There is no such tag in the repository."));
402 }
403
404 return await git.UpdateRefAsync(path, tag.FullName, null, tag.Sha, ct)
405 ? new RefResult(null, tag.TargetSha)
406 : new RefResult(MovedError);
407 });
408
409 /// <summary>True when the name could be a branch: git's own rules, plus a few that keep it usable in URLs and commands.</summary>
410 public async Task<bool> IsValidBranchNameAsync(string name, CancellationToken ct = default) =>
411 name.Length is > 0 and <= 200
412 && !name.StartsWith('-')
413 && name is not "HEAD"
414 && await git.IsValidRefNameAsync(Heads + name, ct);
415
416 private async Task<(GitRef? Target, GitRef? Source, string? Error)> FindBranchesAsync(
417 string path,
418 string baseBranch,
419 string headBranch,
420 CancellationToken ct)
421 {
422 // Both names are looked up in the repository's own ref list; only their SHAs go to git.
423 var refs = await git.ListRefsAsync(path, ct);
424 var target = refs.FirstOrDefault(r => r.Kind == RefKind.Branch && r.Name == baseBranch);
425 var source = refs.FirstOrDefault(r => r.Kind == RefKind.Branch && r.Name == headBranch);
426 if (target is null || source is null)
427 {
428 return (null, null, Localizer.Key("There is no such branch in the repository."));
429 }
430
431 return target.Name == source.Name
432 ? (null, null, Localizer.Key("Choose two different branches."))
433 : (target, source, null);
434 }
435
436 /// <summary>Re-creates the head's commits on top of the base, one three-way merge per commit.</summary>
437 private async Task<RefResult> RebaseAsync(string path, GitRef target, GitRef source, GitIdentity who, CancellationToken ct)
438 {
439 var commits = await git.LogRangeAsync(path, target.Sha, source.Sha, MaxReplayedCommits + 1, ct);
440 if (commits.Count > MaxReplayedCommits)
441 {
442 return new RefResult(Localizer.Key("The branch has too many commits to rebase here."));
443 }
444
445 if (commits.Any(c => c.Parents.Count != 1))
446 {
447 return new RefResult(Localizer.Key("The branch contains merge commits and cannot be rebased here."));
448 }
449
450 var tip = target.Sha;
451 var tipTree = await git.GetRootTreeShaAsync(path, tip, ct);
452 foreach (var commit in commits.Reverse())
453 {
454 var merged = await git.MergeTreeAsync(path, tip, commit.Sha, ct, mergeBaseSha: commit.Parents[0]);
455 if (!merged.IsClean)
456 {
457 return new RefResult(ConflictError, Conflicts: merged.Conflicts);
458 }
459
460 // A commit whose change is already on the base would be empty; it is left out.
461 if (merged.TreeSha == tipTree)
462 {
463 continue;
464 }
465
466 tip = await git.CommitTreeAsync(
467 path, merged.TreeSha!, [tip], FullMessage(commit), who, ct,
468 new GitIdentity(commit.AuthorName, commit.AuthorEmail), commit.AuthorDateRaw);
469 tipTree = merged.TreeSha;
470 }
471
472 return tip == target.Sha
473 ? new RefResult(Localizer.Key("There is nothing to merge."))
474 : new RefResult(null, tip);
475 }
476
477 private Task<RefResult> CreateAsync(
478 Repository repo,
479 string prefix,
480 RefKind kind,
481 string? name,
482 string? from,
483 string invalidName,
484 string exists,
485 CancellationToken ct) =>
486 MutateAsync(repo, async path =>
487 {
488 name = name?.Trim() ?? "";
489 // git's own rules decide what a valid name is; the extra checks keep names usable in URLs and commands.
490 if (name.Length is 0 or > 200
491 || name.StartsWith('-')
492 || name is "HEAD"
493 || !await git.IsValidRefNameAsync(prefix + name, ct))
494 {
495 return new RefResult(invalidName);
496 }
497
498 var refs = await git.ListRefsAsync(path, ct);
499 if (refs.Any(r => r.Kind == kind && r.Name == name))
500 {
501 return new RefResult(exists);
502 }
503
504 var start = await resolver.ResolveExactAsync(path, from?.Trim(), refs, ct);
505 if (start is null)
506 {
507 return new RefResult(Localizer.Key("The starting point does not exist."));
508 }
509
510 // "Expected old value: none" makes a simultaneous creation fail instead of being overwritten.
511 return await git.UpdateRefAsync(path, prefix + name, start.CommitSha, GitParsers.ZeroSha, ct)
512 ? new RefResult(null, start.CommitSha)
513 : new RefResult(exists);
514 });
515
516 private async Task<string> DefaultMessageAsync(string path, GitRef target, GitRef source, bool squash, CancellationToken ct)
517 {
518 if (!squash)
519 {
520 return $"Merge branch '{source.Name}' into {target.Name}";
521 }
522
523 // A squash drops the individual commits, so their subjects are kept in the message.
524 var commits = await git.LogRangeAsync(path, target.Sha, source.Sha, 100, ct);
525 var text = new StringBuilder($"Squash branch '{source.Name}' into {target.Name}\n");
526 foreach (var commit in commits.Reverse())
527 {
528 text.Append("\n* ").Append(commit.Subject);
529 }
530
531 return text.ToString();
532 }
533
534 private static string FullMessage(CommitInfo commit) =>
535 commit.Body.Length == 0 ? commit.Subject : commit.Subject + "\n\n" + commit.Body;
536
537 /// <summary>
538 /// The opening and closing lines git writes around a conflict. The "=======" separator is not
539 /// checked: on its own it is ordinary text (a Markdown heading underline, for one).
540 /// </summary>
541 private static bool HasConflictMarkers(string text)
542 {
543 foreach (var line in text.Split('\n'))
544 {
545 if (line.StartsWith("<<<<<<< ", StringComparison.Ordinal)
546 || line.StartsWith(">>>>>>> ", StringComparison.Ordinal))
547 {
548 return true;
549 }
550 }
551
552 return false;
553 }
554
555 private async Task<RefResult> MutateAsync(Repository repo, Func<string, Task<RefResult>> change)
556 {
557 using var pushLock = await locks.AcquireAsync(repo.Id, CancellationToken.None);
558 var path = paths.For(repo.Id);
559 var before = await git.SnapshotRefsAsync(path);
560 try
561 {
562 return await change(path);
563 }
564 finally
565 {
566 var after = await git.SnapshotRefsAsync(path);
567 await recorder.RecordAsync(repo.Id, before, after);
568 }
569 }
570 }
added forge/Features/History/Tags.razor +165 −0View file
@@ -0,0 +1,165 @@
1 @page "/{Owner}/{Repo}/tags"
2 @inherits RepoPageBase
3 @inject RefService Refs
4
5 @if (Repository is not null)
6 {
7 <PageTitle>@T["Tags"] · @Repository.Owner.Username/@Repository.Name</PageTitle>
8
9 <RepoHeader Repository="Repository" Active="tags" IsOwner="IsOwner"/>
10
11 @if (_message is not null)
12 {
13 <p class="alert success">@_message</p>
14 }
15 @if (_error is not null)
16 {
17 <p class="alert error">@_error</p>
18 }
19
20 @if (_tags.Count == 0)
21 {
22 <div class="empty-state">
23 <Icon Name="tag" Size="32"/>
24 <h2>@T["This repository has no tags yet."]</h2>
25 </div>
26 }
27 else
28 {
29 <form method="post" @formname="delete-tag" @onsubmit="DeleteAsync">
30 <AntiforgeryToken/>
31 <table class="table">
32 <thead>
33 <tr>
34 <th>@T["Tag"]</th>
35 <th>@T["Message"]</th>
36 <th>@T["Commit"]</th>
37 <th class="right">@T["Created"]</th>
38 <th></th>
39 </tr>
40 </thead>
41 <tbody>
42 @foreach (var tag in _tags)
43 {
44 <tr>
45 <td>
46 <Icon Name="tag" Class="cell-icon"/>
47 <a href="@Urls.Tree(Repository, tag.Name)"><strong>@tag.Name</strong></a>
48 </td>
49 <td>@tag.Subject</td>
50 <td><a class="sha" href="@Urls.Commit(Repository, tag.TargetSha)">@tag.TargetSha[..8]</a></td>
51 <td class="right small">
52 @if (tag.Date is { } date)
53 {
54 <TimeAgo Value="date"/>
55 }
56 </td>
57 <td class="right actions">
58 @if (IsOwner)
59 {
60 <button type="submit" name="DeleteName" value="@tag.Name" class="button danger small">@T["Delete"]</button>
61 }
62 </td>
63 </tr>
64 }
65 </tbody>
66 </table>
67 </form>
68 }
69
70 @if (IsOwner && _hasCommits)
71 {
72 <section class="card">
73 <h2>@T["New tag"]</h2>
74 <form method="post" @formname="create-tag" @onsubmit="CreateAsync" class="form">
75 <AntiforgeryToken/>
76 <label>
77 @T["Name"]
78 <input name="NewName" value="@NewName" required maxlength="200" placeholder="v1.0"/>
79 </label>
80 <label>
81 <span>@T["From"] <span class="muted">@T["(branch, tag or commit SHA)"]</span></span>
82 <input name="From" value="@(From ?? Repository.DefaultBranch)" required maxlength="250"/>
83 </label>
84 <button type="submit" class="button primary">@T["Create tag"]</button>
85 </form>
86 </section>
87 }
88 }
89
90 @code {
91 [SupplyParameterFromForm(FormName = "delete-tag")]
92 private string? DeleteName { get; set; }
93
94 [SupplyParameterFromForm(FormName = "create-tag")]
95 private string? NewName { get; set; }
96
97 [SupplyParameterFromForm(FormName = "create-tag")]
98 private string? From { get; set; }
99
100 private IReadOnlyList<GitRef> _tags = [];
101 private bool _hasCommits;
102 private string? _message;
103 private string? _error;
104
105 protected override async Task OnInitializedAsync()
106 {
107 if (await LoadRepoAsync())
108 {
109 await LoadAsync();
110 }
111 }
112
113 private async Task LoadAsync()
114 {
115 // Tags of commits only; a tag pointing at a blob or tree has nothing to browse.
116 _tags = (await Git.ListTagsByDateAsync(RepoPath))
117 .Where(t => t.ObjectType == "commit" || t.PeeledSha is not null)
118 .ToList();
119 _hasCommits = _tags.Count > 0 || (await Git.ListRefsAsync(RepoPath)).Any(r => r.Kind == RefKind.Branch);
120 }
121
122 private async Task CreateAsync()
123 {
124 if (Repository is null || !IsOwner)
125 {
126 return;
127 }
128
129 var name = NewName?.Trim() ?? "";
130 var result = await Refs.CreateTagAsync(Repository, name, From);
131 if (result.Ok)
132 {
133 _message = T["Tag {0} was created.", name];
134 NewName = null;
135 From = null;
136 }
137 else
138 {
139 _error = T[result.Error!];
140 }
141
142 await LoadAsync();
143 }
144
145 private async Task DeleteAsync()
146 {
147 if (Repository is null || !IsOwner)
148 {
149 return;
150 }
151
152 var result = await Refs.DeleteTagAsync(Repository, DeleteName);
153 if (result.Ok)
154 {
155 // The SHA is shown so that a tag deleted by mistake can be created again from it.
156 _message = T["Tag {0} was deleted (it pointed at {1}).", DeleteName, result.Sha];
157 }
158 else
159 {
160 _error = T[result.Error!];
161 }
162
163 await LoadAsync();
164 }
165 }
added forge/Features/Pulls/PullDetail.razor +353 −0View file
@@ -0,0 +1,353 @@
1 @page "/{Owner}/{Repo}/pull/{Number:int}"
2 @inherits RepoPageBase
3 @inject PullRequestService Pulls
4 @inject RefService Refs
5 @inject MarkdownRenderer Markdown
6 @inject ForgeDb Db
7
8 @if (Repository is not null && _pull is not null && _state is not null)
9 {
10 <PageTitle>@_pull.Title · #@_pull.Number</PageTitle>
11 <HighlightAssets/>
12
13 <RepoHeader Repository="Repository" Active="pulls" IsOwner="IsOwner"/>
14
15 <h2 class="commit-title pull-title">@_pull.Title <span class="muted">#@_pull.Number</span></h2>
16 <p class="pull-summary">
17 <PullStatusBadge Status="_pull.Status"/>
18 <span class="muted commit-byline">
19 <Avatar Name="@_pull.Author.Username"/>
20 <span>@_pull.Author.Username</span>
21 <span class="sep">·</span>
22 <span><code>@_pull.HeadBranch</code> → <code>@_pull.BaseBranch</code></span>
23 <span class="sep">·</span>
24 <TimeAgo Value="Format.Utc(_pull.CreatedAt)"/>
25 </span>
26 </p>
27
28 @if (_error is not null)
29 {
30 <div class="alert error">
31 <p>@_error</p>
32 @if (_errorConflicts.Count > 0)
33 {
34 <ul>
35 @foreach (var file in _errorConflicts)
36 {
37 <li><code>@file</code></li>
38 }
39 </ul>
40 }
41 </div>
42 }
43
44 @if (_pull.Description.Length > 0)
45 {
46 <article class="card markdown">@((MarkupString)Render(_pull.Description))</article>
47 }
48
49 @if (IsOwner)
50 {
51 <details class="card">
52 <summary>@T["Edit title and description"]</summary>
53 <form method="post" @formname="edit-pull" @onsubmit="EditAsync" class="form">
54 <AntiforgeryToken/>
55 <label>
56 @T["Title"]
57 <input name="Title" value="@(Title ?? _pull.Title)" required maxlength="@PullRequestService.MaxTitleLength"/>
58 </label>
59 <label>
60 <span>@T["Description"] <span class="muted">@T["(optional, Markdown)"]</span></span>
61 <textarea name="Description" rows="5">@(Description ?? _pull.Description)</textarea>
62 </label>
63 <button type="submit" class="button">@T["Save"]</button>
64 </form>
65 </details>
66 }
67
68 @if (_pull.Status == PullRequestStatus.Merged && _pull.MergeCommitSha is not null)
69 {
70 <p class="alert success">
71 @T["Merged into {0}.", _pull.BaseBranch]
72 <a class="sha" href="@Urls.Commit(Repository, _pull.MergeCommitSha)">@(_pull.MergeCommitSha[..8])</a>
73 </p>
74 }
75
76 @if (_pull.Status == PullRequestStatus.Open)
77 {
78 <section class="card">
79 @if (_state.Base is null || _state.Head is null)
80 {
81 <p class="alert warning">@T["A branch of this pull request no longer exists."]</p>
82 }
83 else if (_state.Check is { } check)
84 {
85 @if (check.Unrelated)
86 {
87 <p class="alert warning">@T["The branches have no common history and cannot be merged here."]</p>
88 }
89 else if (check.Conflicts.Count > 0)
90 {
91 <p class="alert warning">@T["These branches have conflicts."]</p>
92 <p>@T["Conflicting files:"]</p>
93 <ul>
94 @foreach (var file in check.Conflicts)
95 {
96 <li><code>@file</code></li>
97 }
98 </ul>
99 @if (IsOwner)
100 {
101 <a class="button primary" href="@Urls.Conflicts(Repository, _pull.BaseBranch, _pull.HeadBranch)">@T["Resolve conflicts"]</a>
102 }
103 }
104 else
105 {
106 <p class="alert success">@T["These branches can be merged automatically."]</p>
107 @if (IsOwner)
108 {
109 <form method="post" @formname="merge" @onsubmit="MergeAsync" class="form">
110 <AntiforgeryToken/>
111 <MergeFields CanFastForward="check.CanFastForward" AllowDelete="@(_pull.HeadBranch != Repository.DefaultBranch)"
112 HeadName="@_pull.HeadBranch" Message="@Message"/>
113 <button type="submit" class="button primary">@T["Merge"]</button>
114 </form>
115 }
116 }
117 }
118 </section>
119 }
120
121 @if (IsOwner && _pull.Status != PullRequestStatus.Merged)
122 {
123 <form method="post" @formname="pull-state" @onsubmit="ChangeStateAsync" class="button-row">
124 <AntiforgeryToken/>
125 @if (_pull.Status == PullRequestStatus.Open)
126 {
127 <button type="submit" name="Action" value="close" class="button">@T["Close pull request"]</button>
128 }
129 else
130 {
131 <button type="submit" name="Action" value="reopen" class="button">@T["Reopen pull request"]</button>
132 }
133 </form>
134 }
135
136 <h3>@T.Plural(_commits.Count, "{0} commit", "{0} commits")</h3>
137 @if (_commits.Count > 0)
138 {
139 <CommitList Repository="Repository" Commits="_commits"/>
140 }
141
142 <h3>@T.Plural(_comments.Count, "{0} comment", "{0} comments")</h3>
143 @foreach (var comment in _comments)
144 {
145 <article class="card comment" id="comment-@comment.Id">
146 <p class="muted small commit-byline comment-head">
147 <Avatar Name="@comment.Author.Username"/>
148 <strong>@comment.Author.Username</strong>
149 <span class="sep">·</span>
150 <TimeAgo Value="Format.Utc(comment.CreatedAt)"/>
151 </p>
152 <div class="markdown">@((MarkupString)Render(comment.Body))</div>
153 </article>
154 }
155 @if (IsOwner)
156 {
157 <form method="post" @formname="comment" @onsubmit="CommentAsync" class="form">
158 <AntiforgeryToken/>
159 <label>
160 <span>@T["Add a comment"] <span class="muted">@T["(Markdown)"]</span></span>
161 <textarea name="Body" rows="4" required>@Body</textarea>
162 </label>
163 <button type="submit" class="button">@T["Comment"]</button>
164 </form>
165 }
166
167 @if (_diff is not null)
168 {
169 <h3>
170 @T.Plural(_diff.Stats.Count, "{0} changed file", "{0} changed files"):
171 <span class="added">+@_diff.Stats.Sum(s => s.Added ?? 0)</span>
172 <span class="deleted">−@_diff.Stats.Sum(s => s.Deleted ?? 0)</span>
173 </h3>
174 <DiffOptions Path="@Urls.Pull(Repository, _pull.Number)" Split="Split" IgnoreWhitespace="IgnoreWhitespace"/>
175 <DiffView Diff="_diff.Patch" Split="Split" Repository="Repository" HeadSha="@_state.ToSha"/>
176 }
177 }
178
179 @code {
180 private const int MaxCommits = 250;
181
182 [Parameter]
183 public int Number { get; set; }
184
185 [SupplyParameterFromQuery(Name = "view")]
186 private string? View { get; set; }
187
188 [SupplyParameterFromQuery(Name = "w")]
189 private string? Whitespace { get; set; }
190
191 [SupplyParameterFromForm(FormName = "merge")]
192 private string? Method { get; set; }
193
194 [SupplyParameterFromForm(FormName = "merge")]
195 private string? Message { get; set; }
196
197 [SupplyParameterFromForm(FormName = "merge")]
198 private bool DeleteBranch { get; set; }
199
200 [SupplyParameterFromForm(FormName = "pull-state")]
201 private string? Action { get; set; }
202
203 [SupplyParameterFromForm(FormName = "comment")]
204 private string? Body { get; set; }
205
206 [SupplyParameterFromForm(FormName = "edit-pull")]
207 private string? Title { get; set; }
208
209 [SupplyParameterFromForm(FormName = "edit-pull")]
210 private string? Description { get; set; }
211
212 private PullRequest? _pull;
213 private PullRequestState? _state;
214 private IReadOnlyList<CommitInfo> _commits = [];
215 private CommitDiff? _diff;
216 private List<PullRequestComment> _comments = [];
217 private string? _error;
218 private IReadOnlyList<string> _errorConflicts = [];
219
220 private bool Split => View == "split";
221 private bool IgnoreWhitespace => Whitespace == "1";
222
223 /// <summary>Descriptions and comments are Markdown, sanitized like a README; relative links point at the default branch.</summary>
224 private string Render(string markdown) =>
225 Markdown.Render(markdown, new LinkContext(
226 Urls.Raw(Repository!, Repository!.DefaultBranch, ""),
227 Urls.Blob(Repository, Repository.DefaultBranch, ""),
228 ""));
229
230 protected override async Task OnInitializedAsync()
231 {
232 if (!await LoadRepoAsync())
233 {
234 return;
235 }
236
237 _pull = await Pulls.FindAsync(Repository!.Id, Number);
238 if (_pull is null)
239 {
240 NotFound();
241 return;
242 }
243
244 await LoadAsync();
245 }
246
247 private async Task LoadAsync()
248 {
249 var repo = Repository!;
250 var pull = _pull!;
251 _state = await Pulls.LoadStateAsync(repo, pull);
252
253 _commits = [];
254 _diff = null;
255 if (_state.ToSha is { } to)
256 {
257 if (_state.FromSha is { } from)
258 {
259 _commits = await Git.LogRangeAsync(RepoPath, from, to, MaxCommits);
260 _diff = await Git.GetRangeDiffAsync(RepoPath, from, to, IgnoreWhitespace);
261 }
262 }
263
264 _comments = await Db.PullRequestComments
265 .AsNoTracking()
266 .Include(c => c.Author)
267 .Where(c => c.PullRequestId == pull.Id)
268 .OrderBy(c => c.Id)
269 .ToListAsync();
270 }
271
272 private async Task MergeAsync()
273 {
274 if (Repository is null || _pull is null || !IsOwner)
275 {
276 return;
277 }
278
279 var user = await Db.Users.FindAsync(Me.UserId);
280 if (user is null)
281 {
282 return;
283 }
284
285 var result = await Pulls.MergeAsync(
286 Repository, _pull, Refs.IdentityFor(user), MergeFields.Parse(Method), Message, DeleteBranch);
287 if (!result.Ok)
288 {
289 _error = T[result.Error!];
290 _errorConflicts = result.Conflicts ?? [];
291 }
292
293 await LoadAsync();
294 }
295
296 private async Task ChangeStateAsync()
297 {
298 if (Repository is null || _pull is null || !IsOwner)
299 {
300 return;
301 }
302
303 if (Action == "close")
304 {
305 await Pulls.CloseAsync(Repository, _pull);
306 }
307 else if (Action == "reopen" && await Pulls.ReopenAsync(Repository, _pull) is { } error)
308 {
309 _error = T[error];
310 }
311
312 await LoadAsync();
313 }
314
315 private async Task EditAsync()
316 {
317 if (Repository is null || _pull is null || !IsOwner)
318 {
319 return;
320 }
321
322 if (await Pulls.UpdateAsync(_pull, Title, Description) is { } error)
323 {
324 _error = T[error];
325 }
326 else
327 {
328 Title = null;
329 Description = null;
330 }
331
332 await LoadAsync();
333 }
334
335 private async Task CommentAsync()
336 {
337 if (Repository is null || _pull is null || !IsOwner)
338 {
339 return;
340 }
341
342 if (await Pulls.AddCommentAsync(_pull, Me.UserId!.Value, Body) is { } error)
343 {
344 _error = T[error];
345 }
346 else
347 {
348 Body = null;
349 }
350
351 await LoadAsync();
352 }
353 }
added forge/Features/Pulls/PullList.razor +103 −0View file
@@ -0,0 +1,103 @@
1 @page "/{Owner}/{Repo}/pulls"
2 @inherits RepoPageBase
3 @inject ForgeDb Db
4
5 @if (Repository is not null)
6 {
7 <PageTitle>@T["Pull requests"] · @Repository.Owner.Username/@Repository.Name</PageTitle>
8
9 <RepoHeader Repository="Repository" Active="pulls" IsOwner="IsOwner"/>
10
11 <div class="toolbar">
12 <nav class="segmented">
13 <a class="@(ShowClosed ? "" : "active")" href="@Urls.Pulls(Repository)">@T["Open ({0})", _openCount]</a>
14 <a class="@(ShowClosed ? "active" : "")" href="@Urls.Pulls(Repository)?state=closed">@T["Closed ({0})", _closedCount]</a>
15 </nav>
16 @if (IsOwner)
17 {
18 <a class="button primary toolbar-end" href="@Urls.Compare(Repository)"><Icon Name="plus"/> @T["New pull request"]</a>
19 }
20 </div>
21
22 @if (_pulls.Count == 0)
23 {
24 <div class="empty-state">
25 <Icon Name="pull" Size="32"/>
26 <h2>@(ShowClosed ? T["There are no closed pull requests."] : T["There are no open pull requests."])</h2>
27 </div>
28 }
29 else
30 {
31 <ul class="commit-list">
32 @foreach (var pull in _pulls)
33 {
34 <li class="commit-row">
35 <span class="pull-icon pull-@pull.Status.ToString().ToLowerInvariant()">
36 <Icon Name="@(pull.Status == PullRequestStatus.Merged ? "merge" : "pull")" Size="18"/>
37 </span>
38 <div class="commit-main pull-main">
39 <a class="commit-subject" href="@Urls.Pull(Repository, pull.Number)">@pull.Title</a>
40 <div class="muted small commit-byline">
41 <span>#@pull.Number</span>
42 <span class="sep">·</span>
43 <Avatar Name="@pull.Author.Username"/>
44 <span>@pull.Author.Username</span>
45 <span class="sep">·</span>
46 <span><code>@pull.HeadBranch</code> → <code>@pull.BaseBranch</code></span>
47 <span class="sep">·</span>
48 <TimeAgo Value="Format.Utc(pull.UpdatedAt)"/>
49 </div>
50 </div>
51 @if (_commentCounts.GetValueOrDefault(pull.Id) is > 0 and var comments)
52 {
53 <a class="meta-item muted small" href="@Urls.Pull(Repository, pull.Number)"
54 title="@T.Plural(comments, "{0} comment", "{0} comments")">
55 <Icon Name="comment" Size="14"/> @comments
56 </a>
57 }
58 <PullStatusBadge Status="pull.Status"/>
59 </li>
60 }
61 </ul>
62 }
63 }
64
65 @code {
66 [SupplyParameterFromQuery(Name = "state")]
67 private string? State { get; set; }
68
69 private List<PullRequest> _pulls = [];
70 private Dictionary<long, int> _commentCounts = [];
71 private int _openCount;
72 private int _closedCount;
73
74 private bool ShowClosed => State == "closed";
75
76 protected override async Task OnInitializedAsync()
77 {
78 if (!await LoadRepoAsync())
79 {
80 return;
81 }
82
83 var repoId = Repository!.Id;
84 var all = Db.PullRequests.Where(p => p.RepoId == repoId);
85 _openCount = await all.CountAsync(p => p.Status == PullRequestStatus.Open);
86 _closedCount = await all.CountAsync(p => p.Status != PullRequestStatus.Open);
87
88 var showClosed = ShowClosed;
89 _pulls = await all
90 .Include(p => p.Author)
91 .Where(p => (p.Status != PullRequestStatus.Open) == showClosed)
92 .OrderByDescending(p => p.Number)
93 .Take(200)
94 .ToListAsync();
95
96 var ids = _pulls.Select(p => p.Id).ToList();
97 _commentCounts = await Db.PullRequestComments
98 .Where(c => ids.Contains(c.PullRequestId))
99 .GroupBy(c => c.PullRequestId)
100 .Select(g => new { g.Key, Count = g.Count() })
101 .ToDictionaryAsync(g => g.Key, g => g.Count);
102 }
103 }
added forge/Features/Pulls/PullRequestService.cs +289 −0View file
@@ -0,0 +1,289 @@
1 using Forge.Data;
2 using Forge.Features.History;
3 using Forge.Git;
4 using Forge.Localization;
5 using Microsoft.EntityFrameworkCore;
6
7 namespace Forge.Features.Pulls;
8
9 /// <summary>What a pull request looks like right now.</summary>
10 /// <param name="Base">The base branch, or null when it no longer exists (or the pull request is not open).</param>
11 /// <param name="Head">The head branch, likewise.</param>
12 /// <param name="FromSha">Start of the diff: where the branches diverged. Null when unknown.</param>
13 /// <param name="ToSha">End of the diff: the head's tip.</param>
14 /// <param name="Check">For an open pull request with both branches present, whether it can be merged.</param>
15 public sealed record PullRequestState(GitRef? Base, GitRef? Head, string? FromSha, string? ToSha, MergeCheck? Check);
16
17 public sealed class PullRequestService(ForgeDb db, RefService refs, GitRepo git, RepoPaths paths)
18 {
19 public const int MaxTitleLength = 200;
20 public const int MaxTextLength = 20_000;
21
22 public Task<PullRequest?> FindAsync(long repoId, int number, CancellationToken ct = default) =>
23 db.PullRequests.Include(p => p.Author).FirstOrDefaultAsync(p => p.RepoId == repoId && p.Number == number, ct);
24
25 public async Task<(PullRequest? PullRequest, string? Error)> CreateAsync(
26 Repository repo,
27 long authorId,
28 string? title,
29 string? description,
30 string? baseBranch,
31 string? headBranch,
32 CancellationToken ct = default)
33 {
34 title = title?.Trim() ?? "";
35 description = description?.Trim() ?? "";
36 if (title.Length is 0 or > MaxTitleLength)
37 {
38 return (null, Localizer.Key("Enter a title (at most 200 characters)."));
39 }
40
41 if (description.Length > MaxTextLength)
42 {
43 return (null, Localizer.Key("The text is too long."));
44 }
45
46 var path = paths.For(repo.Id);
47 var branches = (await git.ListRefsAsync(path, ct)).Where(r => r.Kind == RefKind.Branch).ToList();
48 var target = branches.FirstOrDefault(b => b.Name == baseBranch);
49 var source = branches.FirstOrDefault(b => b.Name == headBranch);
50 if (target is null || source is null)
51 {
52 return (null, Localizer.Key("There is no such branch in the repository."));
53 }
54
55 if (target.Name == source.Name)
56 {
57 return (null, Localizer.Key("Choose two different branches."));
58 }
59
60 if (await git.MergeBaseAsync(path, target.Sha, source.Sha, ct) == source.Sha)
61 {
62 return (null, Localizer.Key("There is nothing to merge."));
63 }
64
65 if (await db.PullRequests.AnyAsync(
66 p => p.RepoId == repo.Id
67 && p.Status == PullRequestStatus.Open
68 && p.BaseBranch == target.Name
69 && p.HeadBranch == source.Name,
70 ct))
71 {
72 return (null, Localizer.Key("An open pull request for these branches already exists."));
73 }
74
75 var now = DateTime.UtcNow;
76 var pull = new PullRequest
77 {
78 RepoId = repo.Id,
79 Number = (await db.PullRequests.Where(p => p.RepoId == repo.Id).MaxAsync(p => (int?)p.Number, ct) ?? 0) + 1,
80 Title = title,
81 Description = description,
82 BaseBranch = target.Name,
83 HeadBranch = source.Name,
84 Status = PullRequestStatus.Open,
85 AuthorId = authorId,
86 CreatedAt = now,
87 UpdatedAt = now,
88 };
89 db.PullRequests.Add(pull);
90 await db.SaveChangesAsync(ct);
91 return (pull, null);
92 }
93
94 /// <summary>
95 /// Works out what to show. As a side effect, an open pull request whose head has meanwhile been
96 /// merged some other way (a push, the compare page) is marked as merged.
97 /// </summary>
98 public async Task<PullRequestState> LoadStateAsync(Repository repo, PullRequest pull, CancellationToken ct = default)
99 {
100 if (pull.Status != PullRequestStatus.Open)
101 {
102 return new PullRequestState(null, null, pull.BaseSha, pull.HeadSha, null);
103 }
104
105 var path = paths.For(repo.Id);
106 var branches = (await git.ListRefsAsync(path, ct)).Where(r => r.Kind == RefKind.Branch).ToList();
107 var target = branches.FirstOrDefault(b => b.Name == pull.BaseBranch);
108 var source = branches.FirstOrDefault(b => b.Name == pull.HeadBranch);
109 if (target is null || source is null)
110 {
111 return new PullRequestState(target, source, null, null, null);
112 }
113
114 var mergeBase = await git.MergeBaseAsync(path, target.Sha, source.Sha, ct);
115 if (mergeBase == source.Sha)
116 {
117 // Where the branches had diverged is no longer known, so only the head is recorded.
118 await MarkMergedAsync(pull, null, source.Sha, target.Sha, ct);
119 return new PullRequestState(null, null, null, source.Sha, null);
120 }
121
122 var check = await refs.CheckMergeAsync(path, target.Sha, source.Sha, ct);
123 return new PullRequestState(target, source, mergeBase ?? target.Sha, source.Sha, check);
124 }
125
126 public async Task<RefResult> MergeAsync(
127 Repository repo,
128 PullRequest pull,
129 GitIdentity who,
130 MergeMethod method,
131 string? message,
132 bool deleteBranch,
133 CancellationToken ct = default)
134 {
135 var state = await LoadStateAsync(repo, pull, ct);
136 if (pull.Status != PullRequestStatus.Open || state.Base is null || state.Head is null)
137 {
138 return new RefResult(Localizer.Key("This pull request can no longer be merged."));
139 }
140
141 var result = await refs.MergeAsync(repo, who, pull.BaseBranch, pull.HeadBranch, method, message, ct);
142 if (!result.Ok)
143 {
144 return result;
145 }
146
147 await MarkMergedAsync(pull, state.FromSha, state.Head.Sha, result.Sha, ct);
148 if (deleteBranch)
149 {
150 // Refused for the default or a protected branch; that does not undo the merge.
151 await refs.DeleteBranchAsync(repo, pull.HeadBranch, ct);
152 }
153
154 return result;
155 }
156
157 public async Task MarkMergedAsync(PullRequest pull, string? fromSha, string headSha, string? mergeCommitSha, CancellationToken ct = default)
158 {
159 var now = DateTime.UtcNow;
160 pull.Status = PullRequestStatus.Merged;
161 pull.BaseSha = fromSha;
162 pull.HeadSha = headSha;
163 pull.MergeCommitSha = mergeCommitSha;
164 pull.ClosedAt = now;
165 pull.UpdatedAt = now;
166 await db.SaveChangesAsync(ct);
167 }
168
169 /// <summary>Marks the open pull request for a pair of branches as merged, if there is one.</summary>
170 public async Task MarkMergedAsync(
171 Repository repo,
172 string baseBranch,
173 string headBranch,
174 string? fromSha,
175 string headSha,
176 string? mergeCommitSha,
177 CancellationToken ct = default)
178 {
179 var pull = await db.PullRequests.FirstOrDefaultAsync(
180 p => p.RepoId == repo.Id
181 && p.Status == PullRequestStatus.Open
182 && p.BaseBranch == baseBranch
183 && p.HeadBranch == headBranch,
184 ct);
185 if (pull is not null)
186 {
187 await MarkMergedAsync(pull, fromSha, headSha, mergeCommitSha, ct);
188 }
189 }
190
191 public async Task CloseAsync(Repository repo, PullRequest pull, CancellationToken ct = default)
192 {
193 var state = await LoadStateAsync(repo, pull, ct);
194 if (pull.Status != PullRequestStatus.Open)
195 {
196 return;
197 }
198
199 var now = DateTime.UtcNow;
200 pull.Status = PullRequestStatus.Closed;
201 pull.BaseSha = state.FromSha;
202 pull.HeadSha = state.ToSha;
203 pull.ClosedAt = now;
204 pull.UpdatedAt = now;
205 await db.SaveChangesAsync(ct);
206 }
207
208 public async Task<string?> ReopenAsync(Repository repo, PullRequest pull, CancellationToken ct = default)
209 {
210 if (pull.Status != PullRequestStatus.Closed)
211 {
212 return null;
213 }
214
215 var path = paths.For(repo.Id);
216 var branches = (await git.ListRefsAsync(path, ct)).Where(r => r.Kind == RefKind.Branch).Select(r => r.Name).ToList();
217 if (!branches.Contains(pull.BaseBranch) || !branches.Contains(pull.HeadBranch))
218 {
219 return Localizer.Key("A branch of this pull request no longer exists, so it cannot be reopened.");
220 }
221
222 if (await db.PullRequests.AnyAsync(
223 p => p.RepoId == repo.Id
224 && p.Id != pull.Id
225 && p.Status == PullRequestStatus.Open
226 && p.BaseBranch == pull.BaseBranch
227 && p.HeadBranch == pull.HeadBranch,
228 ct))
229 {
230 return Localizer.Key("An open pull request for these branches already exists.");
231 }
232
233 pull.Status = PullRequestStatus.Open;
234 pull.BaseSha = null;
235 pull.HeadSha = null;
236 pull.ClosedAt = null;
237 pull.UpdatedAt = DateTime.UtcNow;
238 await db.SaveChangesAsync(ct);
239 return null;
240 }
241
242 /// <summary>Changes the title and description. Allowed in every state: a merged pull request is still a record worth correcting.</summary>
243 public async Task<string?> UpdateAsync(PullRequest pull, string? title, string? description, CancellationToken ct = default)
244 {
245 title = title?.Trim() ?? "";
246 description = description?.Trim() ?? "";
247 if (title.Length is 0 or > MaxTitleLength)
248 {
249 return Localizer.Key("Enter a title (at most 200 characters).");
250 }
251
252 if (description.Length > MaxTextLength)
253 {
254 return Localizer.Key("The text is too long.");
255 }
256
257 pull.Title = title;
258 pull.Description = description;
259 pull.UpdatedAt = DateTime.UtcNow;
260 await db.SaveChangesAsync(ct);
261 return null;
262 }
263
264 public async Task<string?> AddCommentAsync(PullRequest pull, long authorId, string? body, CancellationToken ct = default)
265 {
266 body = body?.Trim() ?? "";
267 if (body.Length == 0)
268 {
269 return Localizer.Key("Write a comment first.");
270 }
271
272 if (body.Length > MaxTextLength)
273 {
274 return Localizer.Key("The text is too long.");
275 }
276
277 var now = DateTime.UtcNow;
278 db.PullRequestComments.Add(new PullRequestComment
279 {
280 PullRequestId = pull.Id,
281 AuthorId = authorId,
282 Body = body,
283 CreatedAt = now,
284 });
285 pull.UpdatedAt = now;
286 await db.SaveChangesAsync(ct);
287 return null;
288 }
289 }
added forge/Features/Pulls/PullStatusBadge.razor +17 −0View file
@@ -0,0 +1,17 @@
1 @switch (Status)
2 {
3 case PullRequestStatus.Open:
4 <span class="badge badge-added"><Icon Name="pull" Size="12"/> @T["open"]</span>
5 break;
6 case PullRequestStatus.Merged:
7 <span class="badge badge-merged"><Icon Name="merge" Size="12"/> @T["merged"]</span>
8 break;
9 default:
10 <span class="badge badge-deleted"><Icon Name="x" Size="12"/> @T["closed"]</span>
11 break;
12 }
13
14 @code {
15 [Parameter, EditorRequired]
16 public PullRequestStatus Status { get; set; }
17 }
added forge/Features/Repos/BranchProtectionSettings.razor +151 −0View file
@@ -0,0 +1,151 @@
1 @page "/{Owner}/{Repo}/settings/branches"
2 @inherits RepoPageBase
3 @inject ForgeDb Db
4 @inject RefService Refs
5
6 @if (Repository is not null)
7 {
8 <PageTitle>@T["Protected branches"] · @Repository.Owner.Username/@Repository.Name</PageTitle>
9
10 <RepoHeader Repository="Repository" Active="settings" IsOwner="IsOwner"/>
11
12 <nav class="subtabs">
13 <a href="@Urls.Settings(Repository)">@T["General"]</a>
14 <a href="@Urls.Webhooks(Repository)">@T["Webhooks"]</a>
15 <a class="active" href="@Urls.Protection(Repository)">@T["Protected branches"]</a>
16 </nav>
17
18 <p class="muted">@T["A protected branch cannot be force-pushed or deleted, from git or from the web. Merging into it still works."]</p>
19
20 @if (_error is not null)
21 {
22 <p class="alert error">@_error</p>
23 }
24
25 @if (_rules.Count == 0)
26 {
27 <div class="card empty"><p>@T["No branch is protected yet."]</p></div>
28 }
29 else
30 {
31 <form method="post" @formname="remove-rule" @onsubmit="RemoveAsync">
32 <AntiforgeryToken/>
33 <table class="table">
34 <thead>
35 <tr>
36 <th>@T["Branch"]</th>
37 <th>@T["Direct pushes"]</th>
38 <th></th>
39 </tr>
40 </thead>
41 <tbody>
42 @foreach (var rule in _rules)
43 {
44 <tr>
45 <td><code>@rule.Pattern</code></td>
46 <td>@(rule.BlockPush ? T["refused, changes only through merges on the web"] : T["allowed"])</td>
47 <td class="right">
48 <button type="submit" name="RuleId" value="@rule.Id" class="button danger small">@T["Remove protection"]</button>
49 </td>
50 </tr>
51 }
52 </tbody>
53 </table>
54 </form>
55 }
56
57 <section class="card">
58 <h2>@T["Protect a branch"]</h2>
59 <form method="post" @formname="add-rule" @onsubmit="AddAsync" class="form">
60 <AntiforgeryToken/>
61 <label>
62 @T["Branch"]
63 <input name="Pattern" value="@(Pattern ?? Repository.DefaultBranch)" required maxlength="200"/>
64 <small class="muted">@T.Html("A branch name, or a prefix ending in <code>/*</code> such as <code>release/*</code>.")</small>
65 </label>
66 <label class="choice">
67 <input type="checkbox" name="BlockPush" value="true"/>
68 @T["Also refuse direct pushes (changes only through merges on the web)"]
69 </label>
70 <button type="submit" class="button primary">@T["Protect"]</button>
71 </form>
72 </section>
73 }
74
75 @code {
76 [SupplyParameterFromForm(FormName = "add-rule")]
77 private string? Pattern { get; set; }
78
79 [SupplyParameterFromForm(FormName = "add-rule")]
80 private bool BlockPush { get; set; }
81
82 [SupplyParameterFromForm(FormName = "remove-rule")]
83 private long? RuleId { get; set; }
84
85 private List<BranchProtection> _rules = [];
86 private string? _error;
87
88 protected override async Task OnInitializedAsync()
89 {
90 if (await LoadRepoAsync(requireAdmin: true))
91 {
92 await LoadAsync();
93 }
94 }
95
96 private async Task LoadAsync()
97 {
98 var repoId = Repository!.Id;
99 _rules = await Db.BranchProtections.Where(r => r.RepoId == repoId).OrderBy(r => r.Pattern).ToListAsync();
100 }
101
102 private async Task AddAsync()
103 {
104 if (Repository is null)
105 {
106 return;
107 }
108
109 // The pattern later becomes part of a git option, so it must be a real branch name (plus an optional /*).
110 var pattern = Pattern?.Trim() ?? "";
111 if (!await Refs.IsValidBranchNameAsync(BranchRules.NamePart(pattern)))
112 {
113 _error = T["This is not a valid branch name."];
114 return;
115 }
116
117 if (_rules.Any(r => r.Pattern == pattern))
118 {
119 _error = T["This branch is already protected."];
120 return;
121 }
122
123 Db.BranchProtections.Add(new BranchProtection
124 {
125 RepoId = Repository.Id,
126 Pattern = pattern,
127 BlockPush = BlockPush,
128 CreatedAt = DateTime.UtcNow,
129 });
130 await Db.SaveChangesAsync();
131 Pattern = null;
132 await LoadAsync();
133 }
134
135 private async Task RemoveAsync()
136 {
137 if (Repository is null)
138 {
139 return;
140 }
141
142 var rule = _rules.FirstOrDefault(r => r.Id == RuleId);
143 if (rule is not null)
144 {
145 Db.BranchProtections.Remove(rule);
146 await Db.SaveChangesAsync();
147 }
148
149 await LoadAsync();
150 }
151 }
added forge/Features/Repos/Home.razor +198 −0View file
@@ -0,0 +1,198 @@
1 @page "/"
2 @page "/{Owner}"
3 @inject ForgeDb Db
4 @inject CurrentUser Me
5 @inject NavigationManager Nav
6
7 @if (_loaded)
8 {
9 <PageTitle>@(_owner is null ? "Forge" : _owner.Username + " · Forge")</PageTitle>
10
11 @if (_owner is not null)
12 {
13 <section class="profile">
14 <Avatar Name="@_owner.Username" Size="lg"/>
15 <div>
16 <h1>@_owner.DisplayName</h1>
17 <p class="muted">
18 @@@_owner.Username
19 <span class="sep">·</span>
20 @T["Joined"] <TimeAgo Value="Format.Utc(_owner.CreatedAt)"/>
21 </p>
22 </div>
23 </section>
24 }
25
26 <div class="page-head">
27 <div>
28 @if (_owner is null)
29 {
30 <h1>@T["Repositories"]</h1>
31 }
32 else
33 {
34 <h2>@T["Repositories"]</h2>
35 }
36 <p class="muted small page-sub">@T.Plural(_repos.Count, "{0} repository", "{0} repositories")</p>
37 </div>
38 @if (Me.IsAuthenticated)
39 {
40 <a class="button primary" href="/new"><Icon Name="plus"/> @T["New repository"]</a>
41 }
42 </div>
43
44 @if (_repos.Count > 0 || HasQuery)
45 {
46 <div class="filter-bar">
47 <form class="search filter-search" method="get" action="@BasePath" role="search">
48 <Icon Name="search" Size="15"/>
49 <input type="search" name="q" value="@Query" placeholder="@T["Find a repository"]"
50 aria-label="@T["Find a repository"]" autocomplete="off"/>
51 @if (SortByName)
52 {
53 <input type="hidden" name="sort" value="name"/>
54 }
55 </form>
56 <nav class="segmented" aria-label="@T["Sort"]">
57 <a class="@(SortByName ? "" : "active")" href="@ListUrl(sortByName: false)">@T["Recently updated"]</a>
58 <a class="@(SortByName ? "active" : "")" href="@ListUrl(sortByName: true)">@T["Name"]</a>
59 </nav>
60 </div>
61 }
62
63 @if (_repos.Count == 0 && HasQuery)
64 {
65 <div class="empty-state">
66 <Icon Name="search" Size="32"/>
67 <h2>@T["No repository matches “{0}”.", Query!.Trim()]</h2>
68 <p><a href="@ListUrl(SortByName, keepQuery: false)">@T["Clear the search"]</a></p>
69 </div>
70 }
71 else if (_repos.Count == 0)
72 {
73 <div class="empty-state">
74 <Icon Name="inbox" Size="32"/>
75 <h2>@T["There are no repositories here yet."]</h2>
76 @if (Me.IsAuthenticated)
77 {
78 <p class="muted"><a href="/new">@T["Create your first repository"]</a> @T["and push your code to it."]</p>
79 }
80 </div>
81 }
82 else
83 {
84 <ul class="repo-list">
85 @foreach (var repo in _repos)
86 {
87 var isPrivate = repo.Visibility == Visibility.Private;
88 <li class="repo-row">
89 <span class="repo-icon"><Icon Name="@(isPrivate ? "lock" : "book")" Size="18"/></span>
90 <div class="repo-main">
91 <a class="repo-link" href="@Urls.Repo(repo)">@repo.Owner.Username/<strong>@repo.Name</strong></a>
92 @if (isPrivate)
93 {
94 <span class="badge">@T["private"]</span>
95 }
96 @if (repo.Description.Length > 0)
97 {
98 <p class="muted repo-row-description">@repo.Description</p>
99 }
100 </div>
101 <div class="repo-meta muted small">
102 <span class="meta-item"><Icon Name="branch" Size="13"/> @repo.DefaultBranch</span>
103 @if (repo.PushedAt is { } pushed)
104 {
105 <span class="meta-item"><Icon Name="history" Size="13"/> @T["pushed"] <TimeAgo Value="Format.Utc(pushed)"/></span>
106 }
107 else
108 {
109 <span class="badge">@T["empty"]</span>
110 }
111 </div>
112 </li>
113 }
114 </ul>
115 }
116 }
117
118 @code {
119 /// <summary>When set, lists only this user's repositories.</summary>
120 [Parameter]
121 public string? Owner { get; set; }
122
123 [SupplyParameterFromQuery(Name = "q")]
124 private string? Query { get; set; }
125
126 [SupplyParameterFromQuery(Name = "sort")]
127 private string? Sort { get; set; }
128
129 private bool _loaded;
130 private User? _owner;
131 private List<Repository> _repos = [];
132
133 private bool HasQuery => !string.IsNullOrWhiteSpace(Query);
134 private bool SortByName => Sort == "name";
135 private string BasePath => _owner is null ? "/" : Urls.User(_owner.Username);
136
137 private string ListUrl(bool sortByName, bool keepQuery = true)
138 {
139 var parts = new List<string>();
140 if (keepQuery && HasQuery)
141 {
142 parts.Add("q=" + Uri.EscapeDataString(Query!.Trim()));
143 }
144
145 if (sortByName)
146 {
147 parts.Add("sort=name");
148 }
149
150 return parts.Count == 0 ? BasePath : BasePath + "?" + string.Join('&', parts);
151 }
152
153 protected override async Task OnInitializedAsync()
154 {
155 if (!await Db.Users.AnyAsync())
156 {
157 Nav.NavigateTo("/setup");
158 return;
159 }
160
161 var query = Db.Repositories.Include(r => r.Owner).AsQueryable();
162 if (Owner is not null)
163 {
164 _owner = await Db.Users.FirstOrDefaultAsync(u => u.Username == Owner);
165 if (_owner is null)
166 {
167 Nav.NotFound();
168 return;
169 }
170
171 var ownerId = _owner.Id;
172 query = query.Where(r => r.OwnerId == ownerId);
173 }
174
175 // Anonymous visitors see public repositories only; the owner sees everything of theirs.
176 var me = Me.UserId;
177 query = query.Where(r => r.Visibility == Visibility.Public || r.OwnerId == me);
178
179 if (HasQuery)
180 {
181 // LIKE with the wildcards of the search text escaped, so "%" finds a literal percent sign.
182 var text = Query!.Trim();
183 text = text.Length > 100 ? text[..100] : text;
184 var pattern = "%" + text.Replace("\\", "\\\\").Replace("%", "\\%").Replace("_", "\\_") + "%";
185 query = query.Where(r =>
186 EF.Functions.Like(r.Name, pattern, "\\")
187 || EF.Functions.Like(r.Description, pattern, "\\")
188 || EF.Functions.Like(r.Owner.Username, pattern, "\\"));
189 }
190
191 query = SortByName
192 ? query.OrderBy(r => r.Name)
193 : query.OrderByDescending(r => r.PushedAt ?? r.CreatedAt);
194
195 _repos = await query.ToListAsync();
196 _loaded = true;
197 }
198 }
added forge/Features/Repos/NewRepo.razor +78 −0View file
@@ -0,0 +1,78 @@
1 @page "/new"
2 @attribute [Authorize]
3 @inject RepoService Repos
4 @inject CurrentUser Me
5 @inject NavigationManager Nav
6
7 <PageTitle>@T["New repository"] · Forge</PageTitle>
8
9 <section class="narrow">
10 <h1>@T["New repository"]</h1>
11
12 @if (_error is not null)
13 {
14 <p class="alert error">@_error</p>
15 }
16
17 <form method="post" @formname="new-repo" @onsubmit="CreateAsync" class="form">
18 <AntiforgeryToken/>
19 <label>
20 @T["Name"]
21 <input name="Name" value="@Name" required maxlength="100" pattern="[A-Za-z0-9._\-]+" autofocus/>
22 <small class="muted">@T["Letters, digits, dots, hyphens and underscores."]</small>
23 </label>
24 <label>
25 <span>@T["Description"] <span class="muted">@T["(optional)"]</span></span>
26 <input name="Description" value="@Description" maxlength="300"/>
27 </label>
28 <fieldset>
29 <legend>@T["Visibility"]</legend>
30 <label class="choice">
31 <input type="radio" name="Visibility" value="private" checked="@(Visibility != "public")"/>
32 @T["Private: only you can see it"]
33 </label>
34 <label class="choice">
35 <input type="radio" name="Visibility" value="public" checked="@(Visibility == "public")"/>
36 @T["Public: anyone can read and clone it"]
37 </label>
38 </fieldset>
39 <button type="submit" class="button primary">@T["Create repository"]</button>
40 </form>
41 </section>
42
43 @code {
44 [SupplyParameterFromForm]
45 private string? Name { get; set; }
46
47 [SupplyParameterFromForm]
48 private string? Description { get; set; }
49
50 [SupplyParameterFromForm]
51 private string? Visibility { get; set; }
52
53 private string? _error;
54
55 private async Task CreateAsync()
56 {
57 var description = Description?.Trim() ?? "";
58 if (description.Length > 300)
59 {
60 _error = T["The description can be at most 300 characters."];
61 return;
62 }
63
64 var (repo, error) = await Repos.CreateAsync(
65 Me.UserId!.Value,
66 Name?.Trim(),
67 description,
68 Visibility == "public" ? Data.Visibility.Public : Data.Visibility.Private);
69 if (repo is null)
70 {
71 // The service answers with an English message; show it in the visitor's language.
72 _error = error is null ? null : T[error];
73 return;
74 }
75
76 Nav.NavigateTo(Urls.Repo(repo));
77 }
78 }
added forge/Features/Repos/RepoService.cs +158 −0View file
@@ -0,0 +1,158 @@
1 using System.Text.RegularExpressions;
2 using Forge.Data;
3 using Forge.Git;
4 using Forge.Localization;
5 using Microsoft.EntityFrameworkCore;
6
7 namespace Forge.Features.Repos;
8
9 public sealed partial class RepoService(ForgeDb db, GitRepo git, RepoPaths paths, ILogger<RepoService> log)
10 {
11 /// <summary>Returns an English message (a translation key) for the user, or null when the name is acceptable.</summary>
12 public static string? ValidateName(string? name)
13 {
14 if (string.IsNullOrEmpty(name) || !NamePattern().IsMatch(name))
15 {
16 return Localizer.Key("A name may contain letters, digits, dots, hyphens and underscores (1 to 100 characters).");
17 }
18
19 if (name.Contains("..", StringComparison.Ordinal) || name is ".")
20 {
21 return Localizer.Key("A name must not contain '..'.");
22 }
23
24 if (name.EndsWith(".git", StringComparison.OrdinalIgnoreCase))
25 {
26 return Localizer.Key("A name must not end with '.git'.");
27 }
28
29 return null;
30 }
31
32 public Task<Repository?> FindAsync(string owner, string name, CancellationToken ct = default)
33 {
34 // Clone URLs end in .git; browsing one should still find the repository.
35 var bare = name.EndsWith(".git", StringComparison.OrdinalIgnoreCase) ? name[..^4] : name;
36 return db.Repositories
37 .Include(r => r.Owner)
38 .FirstOrDefaultAsync(r => r.Owner.Username == owner && r.Name == bare, ct);
39 }
40
41 public async Task<(Repository? Repo, string? Error)> CreateAsync(
42 long ownerId,
43 string? name,
44 string? description,
45 Visibility visibility,
46 CancellationToken ct = default)
47 {
48 if (ValidateName(name) is { } invalid)
49 {
50 return (null, invalid);
51 }
52
53 if (await db.Repositories.AnyAsync(r => r.OwnerId == ownerId && r.Name == name, ct))
54 {
55 return (null, Localizer.Key("A repository with this name already exists."));
56 }
57
58 var repo = new Repository
59 {
60 OwnerId = ownerId,
61 Name = name!,
62 Description = (description ?? "").Trim(),
63 Visibility = visibility,
64 DefaultBranch = "main",
65 CreatedAt = DateTime.UtcNow,
66 };
67 db.Repositories.Add(repo);
68 try
69 {
70 await db.SaveChangesAsync(ct);
71 }
72 catch (DbUpdateException)
73 {
74 db.Entry(repo).State = EntityState.Detached;
75 return (null, Localizer.Key("A repository with this name already exists."));
76 }
77
78 var path = paths.For(repo.Id);
79 try
80 {
81 await git.InitBareAsync(path, ct);
82 }
83 catch (Exception ex)
84 {
85 // No row without a repository on disk: undo both halves.
86 log.LogError(ex, "git init failed for repository {RepoId}; removing the row", repo.Id);
87 db.Repositories.Remove(repo);
88 await db.SaveChangesAsync(CancellationToken.None);
89 TryDeleteDirectory(path);
90 return (null, Localizer.Key("The repository could not be created on disk. See the server log for details."));
91 }
92
93 await db.Entry(repo).Reference(r => r.Owner).LoadAsync(ct);
94 return (repo, null);
95 }
96
97 /// <summary>Persists edits made to a repository returned by <see cref="FindAsync"/>.</summary>
98 public Task SaveAsync(CancellationToken ct = default) => db.SaveChangesAsync(ct);
99
100 /// <summary>Renames in the database only. The directory is named after the ID and does not move.</summary>
101 public async Task<string?> RenameAsync(Repository repo, string? newName, CancellationToken ct = default)
102 {
103 if (ValidateName(newName) is { } invalid)
104 {
105 return invalid;
106 }
107
108 if (await db.Repositories.AnyAsync(r => r.OwnerId == repo.OwnerId && r.Name == newName && r.Id != repo.Id, ct))
109 {
110 return Localizer.Key("A repository with this name already exists.");
111 }
112
113 repo.Name = newName!;
114 await db.SaveChangesAsync(ct);
115 return null;
116 }
117
118 public async Task<string?> SetDefaultBranchAsync(Repository repo, string? branch, CancellationToken ct = default)
119 {
120 var path = paths.For(repo.Id);
121 var refs = await git.ListRefsAsync(path, ct);
122 // Only a name that exists in the repository is ever handed to git.
123 var match = refs.FirstOrDefault(r => r.Kind == RefKind.Branch && r.Name == branch);
124 if (match is null)
125 {
126 return Localizer.Key("There is no such branch in the repository.");
127 }
128
129 await git.SetHeadBranchAsync(path, match.Name, ct);
130 repo.DefaultBranch = match.Name;
131 await db.SaveChangesAsync(ct);
132 return null;
133 }
134
135 public async Task DeleteAsync(Repository repo, CancellationToken ct = default)
136 {
137 var path = paths.For(repo.Id);
138 db.Repositories.Remove(repo);
139 await db.SaveChangesAsync(ct);
140 TryDeleteDirectory(path);
141 }
142
143 private void TryDeleteDirectory(string path)
144 {
145 try
146 {
147 RepoPaths.DeleteDirectory(path);
148 }
149 catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
150 {
151 log.LogWarning(ex, "Could not delete repository directory {Path}", path);
152 }
153 }
154
155 // \z rather than $: $ would also accept a trailing newline.
156 [GeneratedRegex(@"^[A-Za-z0-9._-]{1,100}\z")]
157 private static partial Regex NamePattern();
158 }
added forge/Features/Repos/RepoSettings.razor +196 −0View file
@@ -0,0 +1,196 @@
1 @page "/{Owner}/{Repo}/settings"
2 @inherits RepoPageBase
3
4 @if (Repository is not null)
5 {
6 <PageTitle>@T["Settings"] · @Repository.Owner.Username/@Repository.Name</PageTitle>
7
8 <RepoHeader Repository="Repository" Active="settings" IsOwner="IsOwner"/>
9
10 <nav class="subtabs">
11 <a class="active" href="@Urls.Settings(Repository)">@T["General"]</a>
12 <a href="@Urls.Webhooks(Repository)">@T["Webhooks"]</a>
13 <a href="@Urls.Protection(Repository)">@T["Protected branches"]</a>
14 </nav>
15
16 @if (_message is not null)
17 {
18 <p class="alert success">@_message</p>
19 }
20 @if (_error is not null)
21 {
22 <p class="alert error">@_error</p>
23 }
24
25 <section class="card">
26 <h2>@T["Description and visibility"]</h2>
27 <form method="post" @formname="general" @onsubmit="SaveGeneralAsync" class="form">
28 <AntiforgeryToken/>
29 <label>
30 @T["Description"]
31 <input name="Description" value="@Repository.Description" maxlength="300"/>
32 </label>
33 <fieldset>
34 <legend>@T["Visibility"]</legend>
35 <label class="choice">
36 <input type="radio" name="Visibility" value="private" checked="@(Repository.Visibility == Data.Visibility.Private)"/>
37 @T["Private"]
38 </label>
39 <label class="choice">
40 <input type="radio" name="Visibility" value="public" checked="@(Repository.Visibility == Data.Visibility.Public)"/>
41 @T["Public"]
42 </label>
43 </fieldset>
44 <button type="submit" class="button primary">@T["Save"]</button>
45 </form>
46 </section>
47
48 <section class="card">
49 <h2>@T["Default branch"]</h2>
50 @if (_branches.Count == 0)
51 {
52 <p class="muted">@T["This repository has no branches yet."]</p>
53 }
54 else
55 {
56 <form method="post" @formname="default-branch" @onsubmit="SaveDefaultBranchAsync" class="form">
57 <AntiforgeryToken/>
58 <label>
59 @T.Html("The branch that is shown first and that <code>git clone</code> checks out")
60 <select name="Branch">
61 @foreach (var branch in _branches)
62 {
63 <option value="@branch" selected="@(branch == Repository.DefaultBranch)">@branch</option>
64 }
65 </select>
66 </label>
67 <button type="submit" class="button">@T["Set"]</button>
68 </form>
69 }
70 </section>
71
72 <section class="card">
73 <h2>@T["Rename repository"]</h2>
74 <p class="muted">@T["The repository address changes. Old clone URLs stop working."]</p>
75 <form method="post" @formname="rename" @onsubmit="RenameAsync" class="form">
76 <AntiforgeryToken/>
77 <label>
78 @T["New name"]
79 <input name="NewName" value="@(NewName ?? Repository.Name)" required maxlength="100"/>
80 </label>
81 <button type="submit" class="button">@T["Rename"]</button>
82 </form>
83 </section>
84
85 <section class="card danger-zone">
86 <h2>@T["Delete this repository"]</h2>
87 <p>@T["This deletes the code, the history and the webhooks. It cannot be undone."]</p>
88 <form method="post" @formname="delete" @onsubmit="DeleteAsync" class="form">
89 <AntiforgeryToken/>
90 <label>
91 @T["To confirm, type the repository name:"] <strong>@Repository.Name</strong>
92 <input name="ConfirmName" required autocomplete="off"/>
93 </label>
94 <button type="submit" class="button danger">@T["Delete repository"]</button>
95 </form>
96 </section>
97 }
98
99 @code {
100 [SupplyParameterFromForm(FormName = "general")]
101 private string? Description { get; set; }
102
103 [SupplyParameterFromForm(FormName = "general")]
104 private string? Visibility { get; set; }
105
106 [SupplyParameterFromForm(FormName = "default-branch")]
107 private string? Branch { get; set; }
108
109 [SupplyParameterFromForm(FormName = "rename")]
110 private string? NewName { get; set; }
111
112 [SupplyParameterFromForm(FormName = "delete")]
113 private string? ConfirmName { get; set; }
114
115 private List<string> _branches = [];
116 private string? _message;
117 private string? _error;
118
119 /// <summary>The service answers with an English message, or null for success; show it in the visitor's language.</summary>
120 private string? Translate(string? error) => error is null ? null : T[error];
121
122 protected override async Task OnInitializedAsync()
123 {
124 if (!await LoadRepoAsync(requireAdmin: true))
125 {
126 return;
127 }
128
129 _branches = (await Git.ListRefsAsync(RepoPath))
130 .Where(r => r.Kind == RefKind.Branch)
131 .Select(r => r.Name)
132 .ToList();
133 }
134
135 private async Task SaveGeneralAsync()
136 {
137 if (Repository is null)
138 {
139 return;
140 }
141
142 var description = Description?.Trim() ?? "";
143 if (description.Length > 300)
144 {
145 _error = T["The description can be at most 300 characters."];
146 return;
147 }
148
149 Repository.Description = description;
150 Repository.Visibility = Visibility == "public" ? Data.Visibility.Public : Data.Visibility.Private;
151 await Repos.SaveAsync();
152 _message = T["Saved."];
153 }
154
155 private async Task SaveDefaultBranchAsync()
156 {
157 if (Repository is null)
158 {
159 return;
160 }
161
162 _error = Translate(await Repos.SetDefaultBranchAsync(Repository, Branch));
163 _message = _error is null ? T["The default branch is set."] : null;
164 }
165
166 private async Task RenameAsync()
167 {
168 if (Repository is null)
169 {
170 return;
171 }
172
173 _error = Translate(await Repos.RenameAsync(Repository, NewName?.Trim()));
174 if (_error is null)
175 {
176 Redirect(Urls.Settings(Repository));
177 }
178 }
179
180 private async Task DeleteAsync()
181 {
182 if (Repository is null)
183 {
184 return;
185 }
186
187 if (!string.Equals(ConfirmName?.Trim(), Repository.Name, StringComparison.Ordinal))
188 {
189 _error = T["The name does not match. The repository was not deleted."];
190 return;
191 }
192
193 await Repos.DeleteAsync(Repository);
194 Redirect("/");
195 }
196 }
added forge/Features/SmartHttp/PushGuard.cs +164 −0View file
@@ -0,0 +1,164 @@
1 using System.Globalization;
2 using System.Text;
3 using Forge.Data;
4 using Forge.Features.History;
5 using Forge.Git;
6
7 namespace Forge.Features.SmartHttp;
8
9 /// <summary>
10 /// Enforces branch protection on pushes without git hooks. A push request starts with the list of
11 /// refs it wants to change; that list is read first, and when it touches a protected branch
12 /// receive-pack is started with settings that make git itself refuse the dangerous updates.
13 /// Git then reports the refusal to the client in the normal way ("remote rejected").
14 /// </summary>
15 public static class PushGuard
16 {
17 private const int MaxCommandBytes = 4 * 1024 * 1024;
18
19 /// <summary>
20 /// Returns the `-c` options for receive-pack and a stream that replays what was read.
21 /// </summary>
22 public static async Task<(Stream Input, List<string> GitOptions)> InspectAsync(
23 Stream input,
24 IReadOnlyList<BranchProtection> rules,
25 CancellationToken ct)
26 {
27 var options = new List<string>();
28
29 // Branches closed to pushes are hidden from receive-pack; git rejects any update of a hidden ref.
30 foreach (var rule in rules.Where(r => r.BlockPush))
31 {
32 options.Add("-c");
33 options.Add("receive.hideRefs=" + BranchRules.RefPrefix(rule.Pattern));
34 }
35
36 var (refs, consumed, understood) = await ReadCommandsAsync(input, ct);
37
38 // Force-pushes and deletions can only be switched off for a whole push. If the command list
39 // could not be read, assume the worst rather than let a protected branch through.
40 var touchesProtected = !understood || refs.Any(r =>
41 r.StartsWith("refs/heads/", StringComparison.Ordinal)
42 && BranchRules.Find(rules, r["refs/heads/".Length..]) is not null);
43 if (touchesProtected)
44 {
45 options.AddRange(["-c", "receive.denyNonFastForwards=true", "-c", "receive.denyDeletes=true"]);
46 }
47
48 return (new ReplayStream(consumed, input), options);
49 }
50
51 /// <summary>
52 /// Reads the pkt-lines up to the first flush packet: "old SP new SP ref [NUL capabilities] LF" each.
53 /// Returns the ref names, every byte consumed, and whether the section was well-formed.
54 /// </summary>
55 public static async Task<(List<string> Refs, byte[] Consumed, bool Understood)> ReadCommandsAsync(Stream input, CancellationToken ct)
56 {
57 var refs = new List<string>();
58 using var consumed = new MemoryStream();
59 var header = new byte[4];
60
61 while (true)
62 {
63 var read = await ReadFullyAsync(input, header, ct);
64 consumed.Write(header, 0, read);
65 if (read == 0 && consumed.Length == 0)
66 {
67 return (refs, [], true); // An empty body: nothing is being pushed.
68 }
69
70 if (read < 4
71 || !int.TryParse(Encoding.ASCII.GetString(header), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out var length))
72 {
73 return (refs, consumed.ToArray(), false);
74 }
75
76 if (length == 0)
77 {
78 return (refs, consumed.ToArray(), true); // Flush packet: end of the command list.
79 }
80
81 if (length < 4 || length > 65520 || consumed.Length + length > MaxCommandBytes)
82 {
83 return (refs, consumed.ToArray(), false);
84 }
85
86 var payload = new byte[length - 4];
87 read = await ReadFullyAsync(input, payload, ct);
88 consumed.Write(payload, 0, read);
89 if (read < payload.Length)
90 {
91 return (refs, consumed.ToArray(), false);
92 }
93
94 var line = Encoding.UTF8.GetString(payload);
95 var nul = line.IndexOf('\0');
96 var parts = (nul >= 0 ? line[..nul] : line).TrimEnd('\n').Split(' ');
97 if (parts.Length == 3 && GitParsers.IsHex(parts[0]) && GitParsers.IsHex(parts[1]))
98 {
99 refs.Add(parts[2]);
100 }
101 }
102 }
103
104 private static async Task<int> ReadFullyAsync(Stream stream, byte[] buffer, CancellationToken ct)
105 {
106 var total = 0;
107 while (total < buffer.Length)
108 {
109 var n = await stream.ReadAsync(buffer.AsMemory(total), ct);
110 if (n == 0)
111 {
112 break;
113 }
114
115 total += n;
116 }
117
118 return total;
119 }
120
121 /// <summary>Serves bytes that were already read, then continues with the rest of the stream.</summary>
122 private sealed class ReplayStream(byte[] prefix, Stream rest) : Stream
123 {
124 private int _position;
125
126 public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
127 {
128 if (_position < prefix.Length)
129 {
130 var n = Math.Min(buffer.Length, prefix.Length - _position);
131 prefix.AsMemory(_position, n).CopyTo(buffer);
132 _position += n;
133 return n;
134 }
135
136 return await rest.ReadAsync(buffer, cancellationToken);
137 }
138
139 public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
140 ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
141
142 public override int Read(byte[] buffer, int offset, int count) =>
143 throw new NotSupportedException("Use ReadAsync.");
144
145 public override bool CanRead => true;
146 public override bool CanSeek => false;
147 public override bool CanWrite => false;
148 public override long Length => throw new NotSupportedException();
149
150 public override long Position
151 {
152 get => throw new NotSupportedException();
153 set => throw new NotSupportedException();
154 }
155
156 public override void Flush()
157 {
158 }
159
160 public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
161 public override void SetLength(long value) => throw new NotSupportedException();
162 public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
163 }
164 }
added forge/Features/SmartHttp/PushRecorder.cs +163 −0View file
@@ -0,0 +1,163 @@
1 using System.Collections.Concurrent;
2 using Forge.Data;
3 using Forge.Features.Webhooks;
4 using Forge.Git;
5 using Microsoft.EntityFrameworkCore;
6
7 namespace Forge.Features.SmartHttp;
8
9 /// <summary>One lock per repository, so two pushes never interleave their before/after snapshots.</summary>
10 public sealed class PushLocks
11 {
12 private readonly ConcurrentDictionary<long, SemaphoreSlim> _locks = new();
13
14 public async Task<IDisposable> AcquireAsync(long repoId, CancellationToken ct)
15 {
16 var semaphore = _locks.GetOrAdd(repoId, _ => new SemaphoreSlim(1, 1));
17 await semaphore.WaitAsync(ct);
18 return new Releaser(semaphore);
19 }
20
21 private sealed class Releaser(SemaphoreSlim semaphore) : IDisposable
22 {
23 private int _released;
24
25 public void Dispose()
26 {
27 if (Interlocked.Exchange(ref _released, 1) == 0)
28 {
29 semaphore.Release();
30 }
31 }
32 }
33 }
34
35 public sealed record RefChange(string RefName, string OldSha, string NewSha);
36
37 /// <summary>
38 /// Turns the difference between two ref snapshots into push events. There are no git hooks:
39 /// the server runs receive-pack itself, so it can simply look before and after.
40 /// </summary>
41 public sealed class PushRecorder(
42 ForgeDb db,
43 GitRepo git,
44 RepoPaths paths,
45 WebhookQueue queue,
46 ILogger<PushRecorder> log)
47 {
48 public static List<RefChange> Diff(
49 IReadOnlyDictionary<string, string> before,
50 IReadOnlyDictionary<string, string> after)
51 {
52 var changes = new List<RefChange>();
53 foreach (var (name, newSha) in after)
54 {
55 if (!before.TryGetValue(name, out var oldSha))
56 {
57 changes.Add(new RefChange(name, GitParsers.ZeroSha, newSha));
58 }
59 else if (oldSha != newSha)
60 {
61 changes.Add(new RefChange(name, oldSha, newSha));
62 }
63 }
64
65 foreach (var (name, oldSha) in before)
66 {
67 if (!after.ContainsKey(name))
68 {
69 changes.Add(new RefChange(name, oldSha, GitParsers.ZeroSha));
70 }
71 }
72
73 changes.Sort((a, b) => string.CompareOrdinal(a.RefName, b.RefName));
74 return changes;
75 }
76
77 public async Task RecordAsync(
78 long repoId,
79 IReadOnlyDictionary<string, string> before,
80 IReadOnlyDictionary<string, string> after,
81 CancellationToken ct = default)
82 {
83 var changes = Diff(before, after);
84 if (changes.Count == 0)
85 {
86 return;
87 }
88
89 var repo = await db.Repositories.FirstOrDefaultAsync(r => r.Id == repoId, ct);
90 if (repo is null)
91 {
92 return;
93 }
94
95 var now = DateTime.UtcNow;
96 var events = changes
97 .Select(c => new PushEvent
98 {
99 RepoId = repoId,
100 RefName = c.RefName,
101 OldSha = c.OldSha,
102 NewSha = c.NewSha,
103 PushedAt = now,
104 })
105 .ToList();
106 db.PushEvents.AddRange(events);
107 repo.PushedAt = now;
108
109 await FixDefaultBranchAsync(repo, before, after, ct);
110 await db.SaveChangesAsync(ct);
111
112 foreach (var e in events)
113 {
114 queue.Enqueue(e.Id);
115 }
116 }
117
118 /// <summary>
119 /// After the first push into an empty repository HEAD may still name a branch nobody pushed
120 /// (HEAD says main, the push brought master). Point HEAD and the row at a branch that exists.
121 /// </summary>
122 private async Task FixDefaultBranchAsync(
123 Repository repo,
124 IReadOnlyDictionary<string, string> before,
125 IReadOnlyDictionary<string, string> after,
126 CancellationToken ct)
127 {
128 const string heads = "refs/heads/";
129 if (before.Keys.Any(k => k.StartsWith(heads, StringComparison.Ordinal)))
130 {
131 return;
132 }
133
134 var pushed = after.Keys
135 .Where(k => k.StartsWith(heads, StringComparison.Ordinal))
136 .Select(k => k[heads.Length..])
137 .Order(StringComparer.Ordinal)
138 .ToList();
139 if (pushed.Count == 0)
140 {
141 return;
142 }
143
144 var path = paths.For(repo.Id);
145 try
146 {
147 var head = await git.GetHeadBranchAsync(path, ct);
148 if (head is not null && pushed.Contains(head))
149 {
150 repo.DefaultBranch = head;
151 return;
152 }
153
154 var chosen = pushed.FirstOrDefault(b => b is "main" or "master") ?? pushed[0];
155 await git.SetHeadBranchAsync(path, chosen, ct);
156 repo.DefaultBranch = chosen;
157 }
158 catch (GitException ex)
159 {
160 log.LogWarning(ex, "Could not set the default branch of repository {RepoId}", repo.Id);
161 }
162 }
163 }
added forge/Features/SmartHttp/SmartHttpEndpoints.cs +428 −0View file
@@ -0,0 +1,428 @@
1 using System.IO.Compression;
2 using System.Text;
3 using System.Text.RegularExpressions;
4 using CliWrap;
5 using Forge.Data;
6 using Forge.Features.Auth;
7 using Forge.Features.Repos;
8 using Forge.Git;
9 using Microsoft.AspNetCore.Diagnostics;
10 using Microsoft.AspNetCore.Http.Features;
11 using Microsoft.EntityFrameworkCore;
12 using Microsoft.Extensions.Options;
13
14 namespace Forge.Features.SmartHttp;
15
16 /// <summary>
17 /// Git smart HTTP. The app does not implement the protocol: it authenticates the request,
18 /// starts `git upload-pack` or `git receive-pack`, and streams bytes in both directions.
19 /// </summary>
20 public static partial class SmartHttpEndpoints
21 {
22 private const string UploadPack = "git-upload-pack";
23 private const string ReceivePack = "git-receive-pack";
24
25 public static void MapSmartHttp(this IEndpointRouteBuilder app)
26 {
27 // {repo} is "name.git" in clone URLs; the suffix is stripped when the repository is looked up.
28 app.MapGet("/{owner}/{repo}/info/refs", InfoRefsAsync);
29 app.MapPost("/{owner}/{repo}/" + UploadPack,
30 (HttpContext context, string owner, string repo, SmartHttpHandler handler) =>
31 handler.RpcAsync(context, owner, repo, UploadPack));
32 app.MapPost("/{owner}/{repo}/" + ReceivePack,
33 (HttpContext context, string owner, string repo, SmartHttpHandler handler) =>
34 handler.RpcAsync(context, owner, repo, ReceivePack));
35 }
36
37 private static Task InfoRefsAsync(HttpContext context, string owner, string repo, SmartHttpHandler handler) =>
38 handler.InfoRefsAsync(context, owner, repo);
39
40 /// <summary>Formats one pkt-line: four hex digits of total length, then the payload.</summary>
41 public static byte[] PktLine(string payload)
42 {
43 var body = Encoding.UTF8.GetBytes(payload);
44 var line = new byte[body.Length + 4];
45 Encoding.ASCII.GetBytes((body.Length + 4).ToString("x4"), line);
46 body.CopyTo(line, 4);
47 return line;
48 }
49
50 public static readonly byte[] FlushPkt = "0000"u8.ToArray();
51
52 /// <summary>The Git-Protocol header becomes GIT_PROTOCOL, but only if it looks like "version=2".</summary>
53 public static string? ValidateProtocolHeader(string? value) =>
54 value is { Length: > 0 and <= 128 } && ProtocolPattern().IsMatch(value) ? value : null;
55
56 public static bool RequestsProtocolV2(string? protocol) =>
57 protocol is not null && protocol.Split(':').Contains("version=2");
58
59 /// <summary>Extracts the password of a Basic Authorization header. The username is ignored: the token is the credential.</summary>
60 public static string? ParseBasicPassword(string? header)
61 {
62 const string scheme = "Basic ";
63 if (header is null || !header.StartsWith(scheme, StringComparison.OrdinalIgnoreCase))
64 {
65 return null;
66 }
67
68 try
69 {
70 var decoded = Encoding.UTF8.GetString(Convert.FromBase64String(header[scheme.Length..].Trim()));
71 var colon = decoded.IndexOf(':');
72 return colon < 0 ? "" : decoded[(colon + 1)..];
73 }
74 catch (FormatException)
75 {
76 return "";
77 }
78 }
79
80 [GeneratedRegex(@"^[A-Za-z0-9=:._-]+\z")]
81 private static partial Regex ProtocolPattern();
82 }
83
84 public sealed class SmartHttpHandler(
85 ForgeDb db,
86 RepoService repos,
87 TokenService tokens,
88 AuthFailureLimiter limiter,
89 GitCli git,
90 GitRepo gitRepo,
91 RepoPaths paths,
92 PushLocks locks,
93 PushRecorder recorder,
94 IOptions<ForgeOptions> options,
95 ILogger<SmartHttpHandler> log)
96 {
97 private const string UploadPack = "git-upload-pack";
98 private const string ReceivePack = "git-receive-pack";
99
100 public async Task InfoRefsAsync(HttpContext context, string owner, string repoName)
101 {
102 DisableStatusPages(context);
103
104 // Only these two values ever become part of a command line.
105 var service = context.Request.Query["service"].ToString();
106 if (service is not (UploadPack or ReceivePack))
107 {
108 await WriteTextAsync(context, StatusCodes.Status400BadRequest, "Unsupported service.");
109 return;
110 }
111
112 var repo = await AuthorizeAsync(context, owner, repoName, write: service == ReceivePack);
113 if (repo is null)
114 {
115 return;
116 }
117
118 var protocol = SmartHttpEndpoints.ValidateProtocolHeader(context.Request.Headers["Git-Protocol"]);
119 context.Response.ContentType = $"application/x-{service}-advertisement";
120 context.Response.Headers.CacheControl = "no-cache";
121
122 var body = context.Response.Body;
123 // Protocol v2 advertisements carry no service announcement (same as git http-backend).
124 if (!(service == UploadPack && SmartHttpEndpoints.RequestsProtocolV2(protocol)))
125 {
126 await body.WriteAsync(SmartHttpEndpoints.PktLine($"# service={service}\n"), context.RequestAborted);
127 await body.WriteAsync(SmartHttpEndpoints.FlushPkt, context.RequestAborted);
128 }
129
130 try
131 {
132 var (exitCode, stderr) = await git.StreamAsync(
133 null,
134 [service["git-".Length..], "--stateless-rpc", "--advertise-refs", paths.For(repo.Id)],
135 PipeSource.Null,
136 PipeTarget.ToStream(body),
137 ProtocolEnvironment(protocol),
138 TimeSpan.FromMinutes(2),
139 context.RequestAborted);
140 if (exitCode != 0)
141 {
142 log.LogWarning("git {Service} --advertise-refs exited with {ExitCode}: {StdErr}", service, exitCode, stderr.Trim());
143 }
144 }
145 catch (OperationCanceledException) when (context.RequestAborted.IsCancellationRequested)
146 {
147 // The client went away; the process is already killed.
148 }
149 }
150
151 public async Task RpcAsync(HttpContext context, string owner, string repoName, string service)
152 {
153 DisableStatusPages(context);
154 var write = service == ReceivePack;
155
156 var repo = await AuthorizeAsync(context, owner, repoName, write);
157 if (repo is null)
158 {
159 return;
160 }
161
162 // Pushes are capped; fetch requests are small negotiation messages and stay unlimited.
163 var sizeFeature = context.Features.Get<IHttpMaxRequestBodySizeFeature>();
164 if (sizeFeature is { IsReadOnly: false })
165 {
166 sizeFeature.MaxRequestBodySize = write ? options.Value.MaxPushBytes : null;
167 }
168
169 var input = context.Request.Body;
170 if (string.Equals(context.Request.Headers.ContentEncoding, "gzip", StringComparison.OrdinalIgnoreCase))
171 {
172 input = new GZipStream(input, CompressionMode.Decompress);
173 if (write)
174 {
175 // The body limit above counts compressed bytes; this one stops a gzip bomb.
176 input = new LimitedReadStream(input, options.Value.MaxPushBytes);
177 }
178 }
179
180 var protocol = SmartHttpEndpoints.ValidateProtocolHeader(context.Request.Headers["Git-Protocol"]);
181 context.Response.ContentType = $"application/x-{service}-result";
182 context.Response.Headers.CacheControl = "no-cache";
183 context.Features.Get<IHttpResponseBodyFeature>()?.DisableBuffering();
184
185 var repoPath = paths.For(repo.Id);
186 if (!write)
187 {
188 await RunServiceAsync(context, service, repoPath, input, protocol);
189 return;
190 }
191
192 IDisposable pushLock;
193 try
194 {
195 pushLock = await locks.AcquireAsync(repo.Id, context.RequestAborted);
196 }
197 catch (OperationCanceledException)
198 {
199 return;
200 }
201
202 using var releaseLock = pushLock;
203 var rules = await db.BranchProtections.AsNoTracking().Where(r => r.RepoId == repo.Id).ToListAsync(CancellationToken.None);
204 var before = await gitRepo.SnapshotRefsAsync(repoPath, CancellationToken.None);
205 try
206 {
207 await RunServiceAsync(context, service, repoPath, input, protocol, rules);
208 }
209 finally
210 {
211 // Refs may have moved even if the client disconnected halfway, so this must not be cancellable.
212 try
213 {
214 var after = await gitRepo.SnapshotRefsAsync(repoPath, CancellationToken.None);
215 await recorder.RecordAsync(repo.Id, before, after, CancellationToken.None);
216 }
217 catch (Exception ex)
218 {
219 log.LogError(ex, "Could not record push events for repository {RepoId}", repo.Id);
220 }
221 }
222 }
223
224 private async Task RunServiceAsync(
225 HttpContext context,
226 string service,
227 string repoPath,
228 Stream input,
229 string? protocol,
230 IReadOnlyList<BranchProtection>? rules = null)
231 {
232 try
233 {
234 // With protected branches, git is told what to refuse before it sees the push.
235 List<string> gitOptions = [];
236 if (rules is { Count: > 0 })
237 {
238 (input, gitOptions) = await PushGuard.InspectAsync(input, rules, context.RequestAborted);
239 }
240
241 var (exitCode, stderr) = await git.StreamAsync(
242 null,
243 [.. gitOptions, service["git-".Length..], "--stateless-rpc", repoPath],
244 PipeSource.FromStream(input),
245 PipeTarget.ToStream(context.Response.Body),
246 ProtocolEnvironment(protocol),
247 GitCli.TransportTimeout,
248 context.RequestAborted);
249 if (exitCode != 0)
250 {
251 log.LogWarning("git {Service} exited with {ExitCode}: {StdErr}", service, exitCode, stderr.Trim());
252 }
253 }
254 catch (OperationCanceledException) when (context.RequestAborted.IsCancellationRequested)
255 {
256 // The client went away; the process is already killed.
257 }
258 catch (Exception ex) when (ex is IOException or InvalidDataException)
259 {
260 // Reading the request body failed: too large, cut off, or not valid gzip.
261 var status = ex switch
262 {
263 PushTooLargeException => StatusCodes.Status413PayloadTooLarge,
264 BadHttpRequestException bad => bad.StatusCode,
265 _ => StatusCodes.Status400BadRequest,
266 };
267 log.LogWarning("git {Service} request failed with {Status}: {Message}", service, status, ex.Message);
268 if (!context.Response.HasStarted)
269 {
270 await WriteTextAsync(
271 context,
272 status,
273 status == StatusCodes.Status413PayloadTooLarge
274 ? "Push is larger than the server allows."
275 : "The request body could not be read.");
276 }
277 else
278 {
279 context.Abort();
280 }
281 }
282 }
283
284 /// <summary>
285 /// Returns the repository when the request may proceed; otherwise writes the response and returns null.
286 /// Anonymous requests that cannot proceed always get 401, whether or not the repository exists:
287 /// git only sends credentials after a 401, and the identical answer keeps private repositories hidden.
288 /// A valid token without access gets 404.
289 /// </summary>
290 private async Task<Repository?> AuthorizeAsync(HttpContext context, string owner, string repoName, bool write)
291 {
292 var ct = context.RequestAborted;
293 var client = context.Connection.RemoteIpAddress?.ToString() ?? "unknown";
294 var actor = Actor.Anonymous;
295
296 var password = SmartHttpEndpoints.ParseBasicPassword(context.Request.Headers.Authorization);
297 if (password is not null)
298 {
299 if (limiter.IsBlocked(client))
300 {
301 context.Response.Headers.RetryAfter = ((int)AuthFailureLimiter.Window.TotalSeconds).ToString();
302 await WriteTextAsync(context, StatusCodes.Status429TooManyRequests, "Too many failed sign-in attempts. Try again later.");
303 return null;
304 }
305
306 var token = await tokens.ValidateAsync(password, ct);
307 if (token is null)
308 {
309 limiter.RecordFailure(client);
310 await ChallengeAsync(context);
311 return null;
312 }
313
314 actor = new Actor(token.UserId, token.CanWrite);
315 }
316
317 var repo = await repos.FindAsync(owner, repoName, ct);
318 var allowed = repo is not null
319 && (write ? RepoAccess.CanWrite(repo, actor) : RepoAccess.CanRead(repo, actor));
320 if (allowed)
321 {
322 return repo;
323 }
324
325 if (actor.IsAnonymous)
326 {
327 await ChallengeAsync(context);
328 }
329 else if (repo is not null && RepoAccess.CanRead(repo, actor))
330 {
331 await WriteTextAsync(context, StatusCodes.Status403Forbidden, "This token is read-only.");
332 }
333 else
334 {
335 await WriteTextAsync(context, StatusCodes.Status404NotFound, "Repository not found.");
336 }
337
338 return null;
339 }
340
341 private static Task ChallengeAsync(HttpContext context)
342 {
343 context.Response.Headers.WWWAuthenticate = "Basic realm=\"forge\", charset=\"UTF-8\"";
344 return WriteTextAsync(context, StatusCodes.Status401Unauthorized, "Authentication required.");
345 }
346
347 private static Dictionary<string, string?> ProtocolEnvironment(string? protocol) =>
348 new(StringComparer.Ordinal) { ["GIT_PROTOCOL"] = protocol };
349
350 private static Task WriteTextAsync(HttpContext context, int status, string message)
351 {
352 context.Response.StatusCode = status;
353 context.Response.ContentType = "text/plain; charset=utf-8";
354 return context.Response.WriteAsync(message + "\n");
355 }
356
357 /// <summary>Git clients need the bare status code, not the HTML error page.</summary>
358 private static void DisableStatusPages(HttpContext context)
359 {
360 if (context.Features.Get<IStatusCodePagesFeature>() is { } feature)
361 {
362 feature.Enabled = false;
363 }
364 }
365 }
366
367 public sealed class PushTooLargeException() : IOException("The decompressed push is larger than the configured limit.");
368
369 /// <summary>Read-only wrapper that fails once more than <paramref name="limit"/> bytes have been read.</summary>
370 public sealed class LimitedReadStream(Stream inner, long limit) : Stream
371 {
372 private long _read;
373
374 public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
375 {
376 var n = await inner.ReadAsync(buffer, cancellationToken);
377 Count(n);
378 return n;
379 }
380
381 public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
382 ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
383
384 public override int Read(byte[] buffer, int offset, int count)
385 {
386 var n = inner.Read(buffer, offset, count);
387 Count(n);
388 return n;
389 }
390
391 private void Count(int n)
392 {
393 _read += n;
394 if (_read > limit)
395 {
396 throw new PushTooLargeException();
397 }
398 }
399
400 public override bool CanRead => true;
401 public override bool CanSeek => false;
402 public override bool CanWrite => false;
403 public override long Length => throw new NotSupportedException();
404
405 public override long Position
406 {
407 get => _read;
408 set => throw new NotSupportedException();
409 }
410
411 public override void Flush()
412 {
413 }
414
415 public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
416 public override void SetLength(long value) => throw new NotSupportedException();
417 public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
418
419 protected override void Dispose(bool disposing)
420 {
421 if (disposing)
422 {
423 inner.Dispose();
424 }
425
426 base.Dispose(disposing);
427 }
428 }
added forge/Features/Webhooks/DeliveryStatus.razor +21 −0View file
@@ -0,0 +1,21 @@
1 @if (Delivery.Succeeded)
2 {
3 <span class="badge badge-added">@Delivery.StatusCode</span>
4 }
5 else if (Delivery.StatusCode is not null)
6 {
7 <span class="badge badge-deleted">@Delivery.StatusCode</span>
8 }
9 else if (Delivery.Error is null)
10 {
11 <span class="badge">@T["in progress"]</span>
12 }
13 else
14 {
15 <span class="badge badge-deleted">@T["failed"]</span>
16 }
17
18 @code {
19 [Parameter, EditorRequired]
20 public WebhookDelivery Delivery { get; set; } = null!;
21 }
added forge/Features/Webhooks/WebhookDetail.razor +227 −0View file
@@ -0,0 +1,227 @@
1 @page "/{Owner}/{Repo}/settings/webhooks/{Id:long}"
2 @inherits RepoPageBase
3 @inject ForgeDb Db
4 @inject WebhookSender Sender
5
6 @if (Repository is not null && _hook is not null)
7 {
8 <PageTitle>@T["Webhook"] · @Repository.Owner.Username/@Repository.Name</PageTitle>
9
10 <RepoHeader Repository="Repository" Active="settings" IsOwner="IsOwner"/>
11
12 <nav class="subtabs">
13 <a href="@Urls.Settings(Repository)">@T["General"]</a>
14 <a class="active" href="@Urls.Webhooks(Repository)">@T["Webhooks"]</a>
15 <a href="@Urls.Protection(Repository)">@T["Protected branches"]</a>
16 </nav>
17
18 @if (_message is not null)
19 {
20 <p class="alert success">@_message</p>
21 }
22 @if (_error is not null)
23 {
24 <p class="alert error">@_error</p>
25 }
26
27 <section class="card">
28 <h2 class="break">@_hook.Url</h2>
29 <dl class="meta">
30 <dt>@T["Status"]</dt>
31 <dd>@(_hook.Active ? T["active"] : T["disabled"])</dd>
32 <dt>@T["Event"]</dt>
33 <dd>push</dd>
34 <dt>@T["Secret"]</dt>
35 <dd><code class="break">@_hook.Secret</code></dd>
36 <dt>@T["Created"]</dt>
37 <dd><TimeAgo Value="Format.Utc(_hook.CreatedAt)"/></dd>
38 </dl>
39 <form method="post" @formname="hook-action" @onsubmit="ActAsync" class="button-row">
40 <AntiforgeryToken/>
41 <button type="submit" name="Action" value="ping" class="button">@T["Send test ping"]</button>
42 <button type="submit" name="Action" value="toggle" class="button">@(_hook.Active ? T["Disable"] : T["Enable"])</button>
43 <button type="submit" name="Action" value="delete" class="button danger">@T["Delete webhook"]</button>
44 </form>
45 </section>
46
47 <section>
48 <h2>@T["Delivery history"]</h2>
49 @if (_deliveries.Count == 0)
50 {
51 <p class="muted">@T["No deliveries yet. Push to the repository or send a test ping."]</p>
52 }
53 else
54 {
55 <form method="post" @formname="redeliver" @onsubmit="RedeliverAsync">
56 <AntiforgeryToken/>
57 <table class="table">
58 <thead>
59 <tr>
60 <th>#</th>
61 <th>@T["Event"]</th>
62 <th>@T["Result"]</th>
63 <th>@T["Attempt"]</th>
64 <th>@T["Duration"]</th>
65 <th>@T["When"]</th>
66 <th></th>
67 </tr>
68 </thead>
69 <tbody>
70 @foreach (var d in _deliveries)
71 {
72 <tr>
73 <td>@d.Id</td>
74 <td>
75 @if (d.PushEvent is { } push)
76 {
77 <span>push <code>@push.RefName</code></span>
78 }
79 else
80 {
81 <span>ping</span>
82 }
83 </td>
84 <td>
85 <DeliveryStatus Delivery="d"/>
86 @if (d.Error is not null)
87 {
88 <span class="muted small break"> @d.Error</span>
89 }
90 </td>
91 <td>@d.Attempt</td>
92 <td>@d.DurationMs ms</td>
93 <td class="small"><TimeAgo Value="Format.Utc(d.DeliveredAt)"/></td>
94 <td class="right">
95 @if (d.PushEventId is not null)
96 {
97 <button type="submit" name="DeliveryId" value="@d.Id" class="button small">@T["Redeliver"]</button>
98 }
99 </td>
100 </tr>
101 }
102 </tbody>
103 </table>
104 </form>
105 }
106 </section>
107 }
108
109 @code {
110 private const int MaxDeliveriesShown = 50;
111
112 [Parameter]
113 public long Id { get; set; }
114
115 [SupplyParameterFromForm(FormName = "hook-action")]
116 private string? Action { get; set; }
117
118 [SupplyParameterFromForm(FormName = "redeliver")]
119 private long? DeliveryId { get; set; }
120
121 private Webhook? _hook;
122 private List<WebhookDelivery> _deliveries = [];
123 private string? _message;
124 private string? _error;
125
126 protected override async Task OnInitializedAsync()
127 {
128 if (!await LoadRepoAsync(requireAdmin: true))
129 {
130 return;
131 }
132
133 // The repository ID is part of the lookup, so a webhook of another repository is simply not found.
134 var repoId = Repository!.Id;
135 _hook = await Db.Webhooks.FirstOrDefaultAsync(w => w.Id == Id && w.RepoId == repoId);
136 if (_hook is null)
137 {
138 NotFound();
139 return;
140 }
141
142 await LoadDeliveriesAsync();
143 }
144
145 private async Task LoadDeliveriesAsync()
146 {
147 var hookId = _hook!.Id;
148 _deliveries = await Db.WebhookDeliveries
149 .AsNoTracking()
150 .Include(d => d.PushEvent)
151 .Where(d => d.WebhookId == hookId)
152 .OrderByDescending(d => d.Id)
153 .Take(MaxDeliveriesShown)
154 .ToListAsync();
155 }
156
157 private async Task ActAsync()
158 {
159 if (Repository is null || _hook is null)
160 {
161 return;
162 }
163
164 switch (Action)
165 {
166 case "ping":
167 // Sent inline (at most the 10 s timeout) so the result is on the page right away.
168 var ok = await Sender.DeliverAsync(_hook.Id, null, 1);
169 if (ok)
170 {
171 _message = T["The ping was delivered."];
172 }
173 else
174 {
175 _error = T["The ping could not be delivered. See the history below for details."];
176 }
177
178 await LoadDeliveriesAsync();
179 break;
180
181 case "toggle":
182 _hook.Active = !_hook.Active;
183 await Db.SaveChangesAsync();
184 _message = _hook.Active ? T["The webhook is enabled."] : T["The webhook is disabled."];
185 break;
186
187 case "delete":
188 Db.Webhooks.Remove(_hook);
189 await Db.SaveChangesAsync();
190 Redirect(Urls.Webhooks(Repository));
191 break;
192 }
193 }
194
195 private async Task RedeliverAsync()
196 {
197 if (Repository is null || _hook is null)
198 {
199 return;
200 }
201
202 var hookId = _hook.Id;
203 var original = await Db.WebhookDeliveries
204 .AsNoTracking()
205 .FirstOrDefaultAsync(d => d.Id == DeliveryId && d.WebhookId == hookId);
206 if (original?.PushEventId is not { } pushEventId)
207 {
208 _error = T["This delivery cannot be repeated."];
209 return;
210 }
211
212 var attempt = await Db.WebhookDeliveries
213 .Where(d => d.WebhookId == hookId && d.PushEventId == pushEventId)
214 .MaxAsync(d => d.Attempt) + 1;
215
216 if (await Sender.DeliverAsync(hookId, pushEventId, attempt))
217 {
218 _message = T["Delivered again."];
219 }
220 else
221 {
222 _error = T["Redelivery failed. See the history below for details."];
223 }
224
225 await LoadDeliveriesAsync();
226 }
227 }
added forge/Features/Webhooks/WebhookList.razor +150 −0View file
@@ -0,0 +1,150 @@
1 @page "/{Owner}/{Repo}/settings/webhooks"
2 @inherits RepoPageBase
3 @using System.Security.Cryptography
4 @inject ForgeDb Db
5
6 @if (Repository is not null)
7 {
8 <PageTitle>@T["Webhooks"] · @Repository.Owner.Username/@Repository.Name</PageTitle>
9
10 <RepoHeader Repository="Repository" Active="settings" IsOwner="IsOwner"/>
11
12 <nav class="subtabs">
13 <a href="@Urls.Settings(Repository)">@T["General"]</a>
14 <a class="active" href="@Urls.Webhooks(Repository)">@T["Webhooks"]</a>
15 <a href="@Urls.Protection(Repository)">@T["Protected branches"]</a>
16 </nav>
17
18 <p class="muted">@T["After every push Forge sends signed JSON to the given address. Useful for triggering an external CI."]</p>
19
20 @if (_error is not null)
21 {
22 <p class="alert error">@_error</p>
23 }
24
25 @if (_hooks.Count == 0)
26 {
27 <div class="card empty"><p>@T["This repository has no webhooks yet."]</p></div>
28 }
29 else
30 {
31 <table class="table">
32 <thead>
33 <tr>
34 <th>@T["URL"]</th>
35 <th>@T["Status"]</th>
36 <th>@T["Last delivery"]</th>
37 </tr>
38 </thead>
39 <tbody>
40 @foreach (var hook in _hooks)
41 {
42 <tr>
43 <td><a href="@Urls.Webhook(Repository, hook.Id)">@hook.Url</a></td>
44 <td>@(hook.Active ? T["active"] : T["disabled"])</td>
45 <td>
46 @if (_last.TryGetValue(hook.Id, out var last))
47 {
48 <DeliveryStatus Delivery="last"/>
49 <span class="muted small"> · <TimeAgo Value="Format.Utc(last.DeliveredAt)"/></span>
50 }
51 else
52 {
53 <span class="muted">@T["none yet"]</span>
54 }
55 </td>
56 </tr>
57 }
58 </tbody>
59 </table>
60 }
61
62 <section class="card">
63 <h2>@T["Add webhook"]</h2>
64 <form method="post" @formname="add-webhook" @onsubmit="AddAsync" class="form">
65 <AntiforgeryToken/>
66 <label>
67 @T["URL"]
68 <input name="Url" type="url" value="@Url" required maxlength="2000" placeholder="https://ci.example.com/hooks/forge"/>
69 </label>
70 <label>
71 <span>@T["Secret"] <span class="muted">@T["(optional, generated if empty)"]</span></span>
72 <input name="Secret" maxlength="200" autocomplete="off"/>
73 <small class="muted">@T.Html("Used to sign <code>X-Forge-Signature</code> (HMAC-SHA256 of the request body).")</small>
74 </label>
75 <button type="submit" class="button primary">@T["Add webhook"]</button>
76 </form>
77 </section>
78 }
79
80 @code {
81 [SupplyParameterFromForm]
82 private string? Url { get; set; }
83
84 [SupplyParameterFromForm]
85 private string? Secret { get; set; }
86
87 private List<Webhook> _hooks = [];
88 private Dictionary<long, WebhookDelivery> _last = [];
89 private string? _error;
90
91 protected override async Task OnInitializedAsync()
92 {
93 if (await LoadRepoAsync(requireAdmin: true))
94 {
95 await LoadAsync();
96 }
97 }
98
99 private async Task LoadAsync()
100 {
101 var repoId = Repository!.Id;
102 _hooks = await Db.Webhooks.Where(w => w.RepoId == repoId).OrderBy(w => w.Id).ToListAsync();
103
104 _last = [];
105 foreach (var hook in _hooks)
106 {
107 var last = await Db.WebhookDeliveries
108 .Where(d => d.WebhookId == hook.Id)
109 .OrderByDescending(d => d.Id)
110 .FirstOrDefaultAsync();
111 if (last is not null)
112 {
113 _last[hook.Id] = last;
114 }
115 }
116 }
117
118 private async Task AddAsync()
119 {
120 if (Repository is null)
121 {
122 return;
123 }
124
125 var url = Url?.Trim() ?? "";
126 if (url.Length > 2000
127 || !Uri.TryCreate(url, UriKind.Absolute, out var uri)
128 || (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps))
129 {
130 _error = T["Enter a full address starting with http:// or https://."];
131 return;
132 }
133
134 var secret = string.IsNullOrWhiteSpace(Secret)
135 ? Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(24))
136 : Secret.Trim();
137
138 var hook = new Webhook
139 {
140 RepoId = Repository.Id,
141 Url = url,
142 Secret = secret,
143 Active = true,
144 CreatedAt = DateTime.UtcNow,
145 };
146 Db.Webhooks.Add(hook);
147 await Db.SaveChangesAsync();
148 Redirect(Urls.Webhook(Repository, hook.Id));
149 }
150 }
added forge/Features/Webhooks/WebhookSender.cs +202 −0View file
@@ -0,0 +1,202 @@
1 using System.Diagnostics;
2 using System.Globalization;
3 using System.Net.Http.Headers;
4 using System.Security.Cryptography;
5 using System.Text;
6 using System.Text.Json;
7 using System.Threading.Channels;
8 using Forge.Data;
9 using Forge.Git;
10 using Microsoft.EntityFrameworkCore;
11 using Microsoft.Extensions.Options;
12
13 namespace Forge.Features.Webhooks;
14
15 /// <summary>Hands push event IDs from the request that received the push to the background worker.</summary>
16 public sealed class WebhookQueue
17 {
18 private readonly Channel<long> _channel = Channel.CreateUnbounded<long>(
19 new UnboundedChannelOptions { SingleReader = true });
20
21 public ChannelReader<long> Reader => _channel.Reader;
22
23 public void Enqueue(long pushEventId) => _channel.Writer.TryWrite(pushEventId);
24 }
25
26 /// <summary>Performs single delivery attempts. Every attempt becomes a row in webhook_deliveries.</summary>
27 public sealed class WebhookSender(
28 IServiceScopeFactory scopes,
29 IHttpClientFactory httpClients,
30 GitRepo git,
31 RepoPaths paths,
32 IOptions<ForgeOptions> options,
33 ILogger<WebhookSender> log)
34 {
35 public const string HttpClientName = "webhooks";
36 public const int MaxCommits = 20;
37 public static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10);
38
39 private static readonly JsonSerializerOptions Json = new() { WriteIndented = false };
40
41 /// <summary>"sha256=&lt;hex&gt;": HMAC-SHA256 of the exact request body, keyed with the webhook secret.</summary>
42 public static string Sign(string secret, ReadOnlySpan<byte> body) =>
43 "sha256=" + Convert.ToHexStringLower(HMACSHA256.HashData(Encoding.UTF8.GetBytes(secret), body));
44
45 /// <summary>
46 /// Sends one attempt and records it. A null <paramref name="pushEventId"/> sends a ping.
47 /// Returns true when the receiver answered with a 2xx status.
48 /// </summary>
49 public async Task<bool> DeliverAsync(long webhookId, long? pushEventId, int attempt, CancellationToken ct = default)
50 {
51 await using var scope = scopes.CreateAsyncScope();
52 var db = scope.ServiceProvider.GetRequiredService<ForgeDb>();
53
54 var hook = await db.Webhooks
55 .Include(w => w.Repo).ThenInclude(r => r.Owner)
56 .FirstOrDefaultAsync(w => w.Id == webhookId, ct);
57 if (hook is null)
58 {
59 return true; // Deleted meanwhile: nothing left to retry.
60 }
61
62 PushEvent? push = null;
63 if (pushEventId is not null)
64 {
65 push = await db.PushEvents.FirstOrDefaultAsync(e => e.Id == pushEventId, ct);
66 if (push is null)
67 {
68 return true;
69 }
70 }
71
72 var delivery = new WebhookDelivery
73 {
74 WebhookId = hook.Id,
75 PushEventId = push?.Id,
76 Attempt = attempt,
77 DeliveredAt = DateTime.UtcNow,
78 };
79 db.WebhookDeliveries.Add(delivery);
80 await db.SaveChangesAsync(ct);
81
82 var stopwatch = Stopwatch.StartNew();
83 try
84 {
85 var body = push is null
86 ? BuildPingPayload(hook)
87 : await BuildPushPayloadAsync(hook.Repo, push, ct);
88
89 using var request = new HttpRequestMessage(HttpMethod.Post, hook.Url);
90 request.Content = new ByteArrayContent(body);
91 request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json") { CharSet = "utf-8" };
92 request.Headers.TryAddWithoutValidation("User-Agent", "Forge-Webhook");
93 request.Headers.TryAddWithoutValidation("X-Forge-Event", push is null ? "ping" : "push");
94 request.Headers.TryAddWithoutValidation("X-Forge-Delivery", delivery.Id.ToString(CultureInfo.InvariantCulture));
95 request.Headers.TryAddWithoutValidation("X-Forge-Signature", Sign(hook.Secret, body));
96
97 using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
98 timeout.CancelAfter(Timeout);
99 using var response = await httpClients.CreateClient(HttpClientName)
100 .SendAsync(request, HttpCompletionOption.ResponseHeadersRead, timeout.Token);
101
102 delivery.StatusCode = (int)response.StatusCode;
103 if (!response.IsSuccessStatusCode)
104 {
105 delivery.Error = $"HTTP {(int)response.StatusCode} {response.ReasonPhrase}".Trim();
106 }
107 }
108 catch (OperationCanceledException) when (ct.IsCancellationRequested)
109 {
110 delivery.Error = "Cancelled because the server was shutting down.";
111 }
112 catch (OperationCanceledException)
113 {
114 delivery.Error = $"Timed out after {Timeout.TotalSeconds:0} s.";
115 }
116 catch (Exception ex) when (ex is HttpRequestException or InvalidOperationException or UriFormatException or GitException or GitTimeoutException)
117 {
118 delivery.Error = Truncate(ex.InnerException?.Message ?? ex.Message, 500);
119 }
120
121 delivery.DurationMs = (int)Math.Min(int.MaxValue, stopwatch.ElapsedMilliseconds);
122 await db.SaveChangesAsync(CancellationToken.None);
123
124 if (!delivery.Succeeded)
125 {
126 log.LogInformation(
127 "Webhook {WebhookId} delivery {DeliveryId} failed (attempt {Attempt}): {Error}",
128 hook.Id, delivery.Id, attempt, delivery.Error);
129 }
130
131 return delivery.Succeeded;
132 }
133
134 private byte[] BuildPingPayload(Webhook hook) =>
135 JsonSerializer.SerializeToUtf8Bytes(
136 new
137 {
138 zen = "Small commits, clear messages.",
139 hook_id = hook.Id,
140 repository = DescribeRepository(hook.Repo),
141 },
142 Json);
143
144 private async Task<byte[]> BuildPushPayloadAsync(Repository repo, PushEvent push, CancellationToken ct)
145 {
146 var o = options.Value;
147 var created = push.OldSha == GitParsers.ZeroSha;
148 var deleted = push.NewSha == GitParsers.ZeroSha;
149
150 IReadOnlyList<CommitInfo> commits = [];
151 if (!deleted && GitParsers.IsFullSha(push.NewSha) && GitParsers.IsFullSha(push.OldSha))
152 {
153 commits = await git.LogRangeAsync(paths.For(repo.Id), push.OldSha, push.NewSha, MaxCommits, ct);
154 }
155
156 var compare = created || deleted
157 ? Urls.Absolute(o, Urls.Commit(repo, deleted ? push.OldSha : push.NewSha))
158 : Urls.Absolute(o, Urls.Compare(repo, push.OldSha, push.NewSha));
159
160 return JsonSerializer.SerializeToUtf8Bytes(
161 new
162 {
163 @ref = push.RefName,
164 before = push.OldSha,
165 after = push.NewSha,
166 created,
167 deleted,
168 compare,
169 pushed_at = Format.IsoTime(Format.Utc(push.PushedAt)),
170 repository = DescribeRepository(repo),
171 // Oldest first, the order in which they were written.
172 commits = commits.Reverse().Select(c => new
173 {
174 id = c.Sha,
175 message = c.Body.Length == 0 ? c.Subject : c.Subject + "\n\n" + c.Body,
176 timestamp = Format.IsoTime(c.AuthorDate),
177 url = Urls.Absolute(o, Urls.Commit(repo, c.Sha)),
178 author = new { name = c.AuthorName, email = c.AuthorEmail },
179 committer = new { name = c.CommitterName, email = c.CommitterEmail },
180 }),
181 },
182 Json);
183 }
184
185 private object DescribeRepository(Repository repo)
186 {
187 var o = options.Value;
188 return new
189 {
190 id = repo.Id,
191 name = repo.Name,
192 full_name = $"{repo.Owner.Username}/{repo.Name}",
193 @private = repo.Visibility == Visibility.Private,
194 description = repo.Description,
195 default_branch = repo.DefaultBranch,
196 html_url = Urls.Absolute(o, Urls.Repo(repo)),
197 clone_url = Urls.Clone(o, repo),
198 };
199 }
200
201 private static string Truncate(string value, int max) => value.Length <= max ? value : value[..max];
202 }
added forge/Features/Webhooks/WebhookWorker.cs +155 −0View file
@@ -0,0 +1,155 @@
1 using Forge.Data;
2 using Microsoft.EntityFrameworkCore;
3
4 namespace Forge.Features.Webhooks;
5
6 /// <summary>
7 /// Delivers push events to webhooks in the background, so a push never waits for a receiver.
8 /// A failed delivery is retried with a growing delay; each (webhook, event) pair retries on its own.
9 /// </summary>
10 public sealed class WebhookWorker(
11 WebhookQueue queue,
12 WebhookSender sender,
13 IServiceScopeFactory scopes,
14 ILogger<WebhookWorker> log) : BackgroundService
15 {
16 public const int MaxAttempts = 3;
17
18 /// <summary>Wait before attempt 2 and before attempt 3. Settable so tests do not wait a minute.</summary>
19 public static TimeSpan[] RetryDelays { get; set; } = [TimeSpan.FromSeconds(10), TimeSpan.FromMinutes(1)];
20
21 /// <summary>Events older than this are not picked up again after a restart.</summary>
22 private static readonly TimeSpan RequeueWindow = TimeSpan.FromDays(3);
23
24 protected override async Task ExecuteAsync(CancellationToken stoppingToken)
25 {
26 try
27 {
28 await RequeueUndeliveredAsync(stoppingToken);
29 }
30 catch (Exception ex) when (ex is not OperationCanceledException)
31 {
32 log.LogError(ex, "Could not requeue undelivered webhook events");
33 }
34
35 try
36 {
37 await foreach (var pushEventId in queue.Reader.ReadAllAsync(stoppingToken))
38 {
39 try
40 {
41 foreach (var webhookId in await ActiveWebhooksForAsync(pushEventId, stoppingToken))
42 {
43 _ = DeliverWithRetriesAsync(webhookId, pushEventId, 1, stoppingToken);
44 }
45 }
46 catch (Exception ex) when (ex is not OperationCanceledException)
47 {
48 log.LogError(ex, "Could not dispatch webhooks for push event {PushEventId}", pushEventId);
49 }
50 }
51 }
52 catch (OperationCanceledException)
53 {
54 // Shutting down.
55 }
56 }
57
58 private async Task<List<long>> ActiveWebhooksForAsync(long pushEventId, CancellationToken ct)
59 {
60 await using var scope = scopes.CreateAsyncScope();
61 var db = scope.ServiceProvider.GetRequiredService<ForgeDb>();
62 var push = await db.PushEvents.AsNoTracking().FirstOrDefaultAsync(e => e.Id == pushEventId, ct);
63 if (push is null)
64 {
65 return [];
66 }
67
68 return await db.Webhooks
69 .Where(w => w.RepoId == push.RepoId && w.Active)
70 .Select(w => w.Id)
71 .ToListAsync(ct);
72 }
73
74 private async Task DeliverWithRetriesAsync(long webhookId, long pushEventId, int firstAttempt, CancellationToken ct)
75 {
76 try
77 {
78 for (var attempt = firstAttempt; attempt <= MaxAttempts; attempt++)
79 {
80 if (attempt > firstAttempt)
81 {
82 var delays = RetryDelays;
83 await Task.Delay(delays[Math.Min(attempt - 2, delays.Length - 1)], ct);
84 }
85
86 if (await sender.DeliverAsync(webhookId, pushEventId, attempt, ct))
87 {
88 return;
89 }
90 }
91 }
92 catch (OperationCanceledException)
93 {
94 // Shutting down; the event is picked up again on the next start.
95 }
96 catch (Exception ex)
97 {
98 log.LogError(ex, "Webhook {WebhookId} delivery for push event {PushEventId} crashed", webhookId, pushEventId);
99 }
100 }
101
102 /// <summary>On startup, continues deliveries that never succeeded and still have attempts left.</summary>
103 private async Task RequeueUndeliveredAsync(CancellationToken ct)
104 {
105 List<(long WebhookId, long PushEventId, int Attempts)> pending;
106 await using (var scope = scopes.CreateAsyncScope())
107 {
108 var db = scope.ServiceProvider.GetRequiredService<ForgeDb>();
109 var since = DateTime.UtcNow - RequeueWindow;
110
111 var candidates = await (
112 from e in db.PushEvents
113 join w in db.Webhooks on e.RepoId equals w.RepoId
114 where w.Active && e.PushedAt >= since && e.PushedAt >= w.CreatedAt
115 select new { WebhookId = w.Id, PushEventId = e.Id })
116 .ToListAsync(ct);
117 if (candidates.Count == 0)
118 {
119 return;
120 }
121
122 var eventIds = candidates.Select(c => c.PushEventId).Distinct().ToList();
123 var attempts = await db.WebhookDeliveries
124 .Where(d => d.PushEventId != null && eventIds.Contains(d.PushEventId.Value))
125 .Select(d => new { d.WebhookId, d.PushEventId, d.Attempt, d.StatusCode })
126 .ToListAsync(ct);
127
128 var summary = attempts
129 .GroupBy(d => (d.WebhookId, PushEventId: d.PushEventId!.Value))
130 .ToDictionary(
131 g => g.Key,
132 g => (Max: g.Max(d => d.Attempt), Succeeded: g.Any(d => d.StatusCode is >= 200 and < 300)));
133
134 pending = [];
135 foreach (var c in candidates)
136 {
137 var (max, succeeded) = summary.GetValueOrDefault((c.WebhookId, c.PushEventId));
138 if (!succeeded && max < MaxAttempts)
139 {
140 pending.Add((c.WebhookId, c.PushEventId, max));
141 }
142 }
143 }
144
145 if (pending.Count > 0)
146 {
147 log.LogInformation("Resuming {Count} undelivered webhook deliveries", pending.Count);
148 }
149
150 foreach (var (webhookId, pushEventId, attempts) in pending)
151 {
152 _ = DeliverWithRetriesAsync(webhookId, pushEventId, attempts + 1, ct);
153 }
154 }
155 }
added forge/ForgeApp.cs +291 −0View file
@@ -0,0 +1,291 @@
1 using System.Threading.RateLimiting;
2 using Forge.Components;
3 using Forge.Data;
4 using Forge.Features.Auth;
5 using Forge.Features.Browse;
6 using Forge.Features.History;
7 using Forge.Features.Pulls;
8 using Forge.Features.Repos;
9 using Forge.Features.SmartHttp;
10 using Forge.Features.Webhooks;
11 using Forge.Git;
12 using Forge.Localization;
13 using Microsoft.AspNetCore.Authentication;
14 using Microsoft.AspNetCore.Authentication.Cookies;
15 using Microsoft.AspNetCore.DataProtection;
16 using Microsoft.AspNetCore.Identity;
17 using Microsoft.AspNetCore.Localization;
18 using Microsoft.AspNetCore.Mvc;
19 using Microsoft.AspNetCore.RateLimiting;
20 using Microsoft.EntityFrameworkCore;
21 using Microsoft.Extensions.Options;
22
23 namespace Forge;
24
25 public sealed class ForgeStartupException(string message) : Exception(message);
26
27 public static class ForgeApp
28 {
29 public const string LoginRateLimit = "login";
30 public const string LanguageCookie = "forge_lang";
31
32 /// <summary>Oldest git the app works with (`merge-tree --merge-base` needs 2.40).</summary>
33 public static readonly Version MinimumGitVersion = new(2, 40);
34
35 public const string ContentSecurityPolicy =
36 "default-src 'self'; img-src 'self' data:; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'";
37
38 public static WebApplication Build(string[] args)
39 {
40 var builder = WebApplication.CreateBuilder(new WebApplicationOptions
41 {
42 Args = args,
43 // Stays correct when the app is hosted from another process, such as the test runner.
44 ApplicationName = typeof(ForgeApp).Assembly.GetName().Name,
45 });
46
47 ConfigureServices(builder);
48 var app = builder.Build();
49 ConfigurePipeline(app);
50 return app;
51 }
52
53 /// <summary>
54 /// Prepares everything the app needs before it accepts requests: data directories, a working git,
55 /// and an up-to-date database. Throws <see cref="ForgeStartupException"/> with a message for the operator.
56 /// </summary>
57 public static async Task InitializeAsync(WebApplication app, CancellationToken ct = default)
58 {
59 ForgeOptions options;
60 try
61 {
62 options = app.Services.GetRequiredService<IOptions<ForgeOptions>>().Value;
63 }
64 catch (OptionsValidationException ex)
65 {
66 throw new ForgeStartupException("Invalid configuration: " + string.Join(" ", ex.Failures));
67 }
68
69 Directory.CreateDirectory(options.DataRoot);
70 Directory.CreateDirectory(options.ReposRoot);
71
72 Version version;
73 try
74 {
75 version = await app.Services.GetRequiredService<GitCli>().GetVersionAsync(ct);
76 }
77 catch (GitException ex)
78 {
79 throw new ForgeStartupException(
80 $"Git is required but could not be run. {ex.Message} "
81 + "Install git or set Forge:GitPath to the git executable.");
82 }
83
84 if (version < MinimumGitVersion)
85 {
86 throw new ForgeStartupException(
87 $"Git {version} is too old; Forge needs git {MinimumGitVersion} or newer.");
88 }
89
90 await using var scope = app.Services.CreateAsyncScope();
91 await scope.ServiceProvider.GetRequiredService<ForgeDb>().Database.MigrateAsync(ct);
92
93 app.Logger.LogInformation("Forge data in {DataRoot}, git {GitVersion}", options.DataRoot, version);
94 }
95
96 private static void ConfigureServices(WebApplicationBuilder builder)
97 {
98 var services = builder.Services;
99
100 services.AddOptions<ForgeOptions>()
101 .Bind(builder.Configuration.GetSection(ForgeOptions.SectionName))
102 .ValidateDataAnnotations()
103 .ValidateOnStart();
104 services.AddSingleton<IValidateOptions<ForgeOptions>, ForgeOptionsValidator>();
105
106 services.AddDbContext<ForgeDb>((provider, options) =>
107 ForgeDb.Configure(options, provider.GetRequiredService<IOptions<ForgeOptions>>().Value.DatabasePath));
108
109 // Language of a request: the visitor's saved choice, else the browser's Accept-Language, else English.
110 var translations = new Translations();
111 services.AddSingleton(translations);
112 services.AddSingleton<Localizer>();
113 services.Configure<RequestLocalizationOptions>(options =>
114 {
115 var languages = translations.Languages.ToArray();
116 options.SetDefaultCulture(Translations.DefaultLanguage);
117 options.AddSupportedCultures(languages);
118 options.AddSupportedUICultures(languages);
119 options.RequestCultureProviders =
120 [
121 new CookieRequestCultureProvider { CookieName = LanguageCookie },
122 new AcceptLanguageHeaderRequestCultureProvider(),
123 ];
124 });
125
126 services.AddSingleton(TimeProvider.System);
127 services.AddSingleton<GitCli>();
128 services.AddSingleton<GitRepo>();
129 services.AddSingleton<RefResolver>();
130 services.AddSingleton<RepoPaths>();
131 services.AddSingleton<ContentCache>();
132 services.AddSingleton<RepoInsights>();
133 services.AddSingleton<MarkdownRenderer>();
134 services.AddSingleton<PushLocks>();
135 services.AddSingleton<AuthFailureLimiter>();
136 services.AddSingleton<IPasswordHasher<User>, PasswordHasher<User>>();
137
138 services.AddHttpContextAccessor();
139 services.AddScoped<CurrentUser>();
140 services.AddScoped<TokenService>();
141 services.AddScoped<RepoService>();
142 services.AddScoped<PushRecorder>();
143 services.AddScoped<RefService>();
144 services.AddScoped<PullRequestService>();
145 services.AddScoped<SmartHttpHandler>();
146
147 services.AddSingleton<WebhookQueue>();
148 services.AddSingleton<WebhookSender>();
149 services.AddHostedService<WebhookWorker>();
150 services.AddHttpClient(WebhookSender.HttpClientName)
151 .ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
152 {
153 // A receiver must answer itself; following redirects would re-send the signed body elsewhere.
154 AllowAutoRedirect = false,
155 ConnectTimeout = WebhookSender.Timeout,
156 });
157
158 var configured = builder.Configuration.GetSection(ForgeOptions.SectionName).Get<ForgeOptions>() ?? new ForgeOptions();
159 var https = configured.IsHttps;
160
161 // Keys that protect the session and CSRF cookies live with the rest of the data, so sessions
162 // survive restarts and container rebuilds, and backing up DataPath covers them too.
163 services.AddDataProtection()
164 .SetApplicationName("forge")
165 .PersistKeysToFileSystem(new DirectoryInfo(Path.Combine(configured.DataRoot, "keys")));
166
167 services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
168 .AddCookie(options =>
169 {
170 options.Cookie.Name = "forge_session";
171 options.Cookie.HttpOnly = true;
172 options.Cookie.SameSite = SameSiteMode.Lax;
173 // Secure whenever the site is served over HTTPS. Plain-HTTP development still works.
174 options.Cookie.SecurePolicy = https ? CookieSecurePolicy.Always : CookieSecurePolicy.SameAsRequest;
175 options.LoginPath = "/login";
176 options.AccessDeniedPath = "/login";
177 options.ReturnUrlParameter = "returnUrl";
178 options.ExpireTimeSpan = TimeSpan.FromDays(30);
179 options.SlidingExpiration = true;
180 options.Events.OnValidatePrincipal = RejectUnknownUserAsync;
181 });
182 services.AddAuthorization();
183 services.AddAntiforgery(options =>
184 {
185 options.Cookie.Name = "forge_csrf";
186 options.Cookie.SecurePolicy = https ? CookieSecurePolicy.Always : CookieSecurePolicy.SameAsRequest;
187 });
188
189 services.AddRateLimiter(options =>
190 {
191 options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
192 // Fixed window per client address. Only form posts count, so reading the page is never limited.
193 options.AddPolicy(LoginRateLimit, context =>
194 HttpMethods.IsPost(context.Request.Method)
195 ? RateLimitPartition.GetFixedWindowLimiter(
196 context.Connection.RemoteIpAddress?.ToString() ?? "unknown",
197 _ => new FixedWindowRateLimiterOptions
198 {
199 PermitLimit = 10,
200 Window = TimeSpan.FromMinutes(1),
201 QueueLimit = 0,
202 })
203 : RateLimitPartition.GetNoLimiter("read"));
204 });
205
206 services.AddRazorComponents();
207 }
208
209 private static void ConfigurePipeline(WebApplication app)
210 {
211 if (!app.Environment.IsDevelopment())
212 {
213 app.UseExceptionHandler("/error", createScopeForErrors: true);
214 }
215
216 app.Use(async (context, next) =>
217 {
218 var headers = context.Response.Headers;
219 headers.XContentTypeOptions = "nosniff";
220 headers.XFrameOptions = "DENY";
221 headers["Referrer-Policy"] = "same-origin";
222 headers.ContentSecurityPolicy = ContentSecurityPolicy;
223 await next();
224 });
225
226 app.UseStatusCodePagesWithReExecute("/status/{0}", createScopeForStatusCodePages: true);
227 // Static files go before routing. Otherwise /style.css matches the /{owner} page route,
228 // and the static file middleware steps aside for a request that already has an endpoint.
229 app.UseStaticFiles();
230 app.UseRequestLocalization();
231 app.UseRouting();
232
233 app.UseAuthentication();
234 app.UseAuthorization();
235 app.UseRateLimiter();
236 app.UseAntiforgery();
237
238 app.MapSmartHttp();
239 app.MapRaw();
240 app.MapAtom();
241
242 // [FromForm] makes the antiforgery middleware validate the token posted by the layout's form.
243 app.MapPost("/logout", async (HttpContext context, [FromForm] string? returnUrl) =>
244 {
245 await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
246 return Results.LocalRedirect(CurrentUser.SafeReturnUrl(returnUrl));
247 });
248
249 // The language switcher in the page footer. Remembers the choice for a year.
250 app.MapPost("/language", (
251 HttpContext context,
252 [FromForm] string? lang,
253 [FromForm] string? returnUrl,
254 Translations translations,
255 IOptions<ForgeOptions> options) =>
256 {
257 var language = translations.Languages.FirstOrDefault(l => string.Equals(l, lang, StringComparison.OrdinalIgnoreCase));
258 if (language is not null)
259 {
260 context.Response.Cookies.Append(
261 LanguageCookie,
262 CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(language)),
263 new CookieOptions
264 {
265 MaxAge = TimeSpan.FromDays(365),
266 HttpOnly = true,
267 IsEssential = true,
268 SameSite = SameSiteMode.Lax,
269 Secure = options.Value.IsHttps,
270 Path = "/",
271 });
272 }
273
274 return Results.LocalRedirect(CurrentUser.SafeReturnUrl(returnUrl));
275 });
276
277 app.MapRazorComponents<App>();
278 }
279
280 /// <summary>A cookie for a user that no longer exists (fresh database, deleted account) is not a session.</summary>
281 private static async Task RejectUnknownUserAsync(CookieValidatePrincipalContext context)
282 {
283 var db = context.HttpContext.RequestServices.GetRequiredService<ForgeDb>();
284 var idText = context.Principal?.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;
285 if (!long.TryParse(idText, out var id) || !await db.Users.AnyAsync(u => u.Id == id))
286 {
287 context.RejectPrincipal();
288 await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
289 }
290 }
291 }
added forge/ForgeOptions.cs +46 −0View file
@@ -0,0 +1,46 @@
1 using System.ComponentModel.DataAnnotations;
2 using Microsoft.Extensions.Options;
3
4 namespace Forge;
5
6 public sealed class ForgeOptions
7 {
8 public const string SectionName = "Forge";
9
10 /// <summary>Directory holding forge.db and repos/. Relative paths resolve against the working directory.</summary>
11 [Required]
12 public string DataPath { get; set; } = "data";
13
14 /// <summary>Public URL of the app, used for clone URLs, feeds and webhook payloads.</summary>
15 [Required]
16 public string BaseUrl { get; set; } = "http://localhost:5207";
17
18 [Range(1, 102_400)]
19 public int MaxPushSizeMb { get; set; } = 500;
20
21 /// <summary>Git executable: a name resolved through PATH or an absolute path.</summary>
22 [Required]
23 public string GitPath { get; set; } = "git";
24
25 public string DataRoot => Path.GetFullPath(DataPath);
26 public string ReposRoot => Path.Combine(DataRoot, "repos");
27 public string DatabasePath => Path.Combine(DataRoot, "forge.db");
28 public string BaseUrlTrimmed => BaseUrl.TrimEnd('/');
29 public bool IsHttps => BaseUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase);
30 public long MaxPushBytes => MaxPushSizeMb * 1024L * 1024L;
31 }
32
33 public sealed class ForgeOptionsValidator : IValidateOptions<ForgeOptions>
34 {
35 public ValidateOptionsResult Validate(string? name, ForgeOptions options)
36 {
37 if (!Uri.TryCreate(options.BaseUrl, UriKind.Absolute, out var uri)
38 || (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps))
39 {
40 return ValidateOptionsResult.Fail(
41 $"Forge:BaseUrl must be an absolute http(s) URL, got '{options.BaseUrl}'.");
42 }
43
44 return ValidateOptionsResult.Success;
45 }
46 }
added forge/Format.cs +23 −0View file
@@ -0,0 +1,23 @@
1 using System.Globalization;
2
3 namespace Forge;
4
5 /// <summary>Formatting that follows the language of the current request (<see cref="CultureInfo.CurrentCulture"/>).</summary>
6 public static class Format
7 {
8 public static string ExactTime(DateTimeOffset value) =>
9 value.ToUniversalTime().ToString("d MMM yyyy HH:mm", CultureInfo.CurrentCulture) + " UTC";
10
11 public static string IsoTime(DateTimeOffset value) =>
12 value.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture);
13
14 public static DateTimeOffset Utc(DateTime value) =>
15 new(DateTime.SpecifyKind(value, DateTimeKind.Utc));
16
17 public static string Size(long bytes) => bytes switch
18 {
19 < 1024 => $"{bytes} B",
20 < 1024 * 1024 => string.Create(CultureInfo.CurrentCulture, $"{bytes / 1024.0:0.#} kB"),
21 _ => string.Create(CultureInfo.CurrentCulture, $"{bytes / (1024.0 * 1024.0):0.#} MB"),
22 };
23 }
added forge/Git/GitCli.cs +288 −0View file
@@ -0,0 +1,288 @@
1 using System.ComponentModel;
2 using System.Text;
3 using CliWrap;
4 using Microsoft.Extensions.Options;
5
6 namespace Forge.Git;
7
8 public sealed record GitResult(int ExitCode, byte[] StdOut, string StdErr, bool Truncated)
9 {
10 public bool Ok => ExitCode == 0 && !Truncated;
11 public string Text => Encoding.UTF8.GetString(StdOut);
12 }
13
14 /// <summary>
15 /// The only place that starts git processes. Every process gets an isolated environment,
16 /// a timeout, and is killed when the caller cancels.
17 /// </summary>
18 public sealed class GitCli
19 {
20 public static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(30);
21
22 /// <summary>Clone and push can legitimately run long; they still must not run forever.</summary>
23 public static readonly TimeSpan TransportTimeout = TimeSpan.FromHours(2);
24
25 public const long DefaultMaxOutputBytes = 32 * 1024 * 1024;
26
27 private readonly string _gitPath;
28 private readonly string _workDir;
29
30 /// <summary>The data directory; git processes run here and scratch files go below it.</summary>
31 public string WorkDirectory => _workDir;
32 private readonly Dictionary<string, string?> _environment;
33
34 public GitCli(IOptions<ForgeOptions> options)
35 {
36 var o = options.Value;
37 _gitPath = o.GitPath;
38 _workDir = o.DataRoot;
39 _environment = new Dictionary<string, string?>(StringComparer.Ordinal)
40 {
41 // Isolation: no system config, no config from the real home directory, never prompt.
42 ["GIT_CONFIG_NOSYSTEM"] = "1",
43 ["HOME"] = o.DataRoot,
44 ["XDG_CONFIG_HOME"] = Path.Combine(o.DataRoot, ".config"),
45 ["GIT_TERMINAL_PROMPT"] = "0",
46 // Paths from URLs are plain paths, never pathspec magic such as ":(glob)".
47 ["GIT_LITERAL_PATHSPECS"] = "1",
48 ["GIT_OPTIONAL_LOCKS"] = "0",
49 ["LC_ALL"] = "C",
50 // Nothing inherited from the server's own environment may redirect git elsewhere.
51 ["GIT_DIR"] = null,
52 ["GIT_WORK_TREE"] = null,
53 ["GIT_INDEX_FILE"] = null,
54 ["GIT_OBJECT_DIRECTORY"] = null,
55 ["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = null,
56 ["GIT_NAMESPACE"] = null,
57 ["GIT_CONFIG_GLOBAL"] = null,
58 ["GIT_CONFIG_PARAMETERS"] = null,
59 ["GIT_CONFIG_COUNT"] = null,
60 ["GIT_PROTOCOL"] = null,
61 };
62 }
63
64 /// <summary>Runs git and buffers stdout. Pass <paramref name="repoPath"/> as null for commands outside a repo.</summary>
65 public async Task<GitResult> RunAsync(
66 string? repoPath,
67 IEnumerable<string> args,
68 Stream? stdin = null,
69 CancellationToken ct = default,
70 TimeSpan? timeout = null,
71 long maxOutputBytes = DefaultMaxOutputBytes,
72 bool throwOnError = true,
73 IReadOnlyDictionary<string, string?>? extraEnvironment = null)
74 {
75 var fullArgs = BuildArgs(repoPath, args);
76 var limit = timeout ?? DefaultTimeout;
77 var environment = MergeEnvironment(extraEnvironment);
78
79 using var timeoutCts = new CancellationTokenSource(limit);
80 using var capCts = new CancellationTokenSource();
81 using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, timeoutCts.Token, capCts.Token);
82
83 await using var stdout = new CappedBuffer(maxOutputBytes, capCts);
84 var stderr = new StringBuilder();
85
86 var command = Cli.Wrap(_gitPath)
87 .WithArguments(fullArgs)
88 .WithWorkingDirectory(_workDir)
89 .WithEnvironmentVariables(environment)
90 .WithStandardInputPipe(stdin is null ? PipeSource.Null : PipeSource.FromStream(stdin))
91 .WithStandardOutputPipe(PipeTarget.ToStream(stdout))
92 .WithStandardErrorPipe(PipeTarget.ToStringBuilder(stderr))
93 .WithValidation(CommandResultValidation.None);
94
95 try
96 {
97 var result = await command.ExecuteAsync(linked.Token);
98 if (result.ExitCode != 0 && throwOnError && !stdout.Truncated)
99 {
100 throw new GitException(
101 $"git {Describe(fullArgs)} exited with code {result.ExitCode}: {stderr.ToString().Trim()}",
102 result.ExitCode,
103 stderr.ToString());
104 }
105
106 return new GitResult(result.ExitCode, stdout.ToArray(), stderr.ToString(), stdout.Truncated);
107 }
108 catch (OperationCanceledException) when (!ct.IsCancellationRequested && stdout.Truncated)
109 {
110 // Output went over the cap, so the process was killed on purpose.
111 return new GitResult(-1, stdout.ToArray(), stderr.ToString(), Truncated: true);
112 }
113 catch (OperationCanceledException) when (!ct.IsCancellationRequested && timeoutCts.IsCancellationRequested)
114 {
115 throw new GitTimeoutException($"git {Describe(fullArgs)} did not finish within {limit.TotalSeconds:0} s and was killed.");
116 }
117 }
118
119 /// <summary>Runs git with caller-supplied pipes, for output that must not be buffered.</summary>
120 public async Task<(int ExitCode, string StdErr)> StreamAsync(
121 string? repoPath,
122 IEnumerable<string> args,
123 PipeSource stdin,
124 PipeTarget stdout,
125 IReadOnlyDictionary<string, string?>? extraEnvironment = null,
126 TimeSpan? timeout = null,
127 CancellationToken ct = default)
128 {
129 var fullArgs = BuildArgs(repoPath, args);
130 var limit = timeout ?? DefaultTimeout;
131
132 var environment = MergeEnvironment(extraEnvironment);
133
134 using var timeoutCts = new CancellationTokenSource(limit);
135 using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, timeoutCts.Token);
136 var stderr = new StringBuilder();
137
138 var command = Cli.Wrap(_gitPath)
139 .WithArguments(fullArgs)
140 .WithWorkingDirectory(_workDir)
141 .WithEnvironmentVariables(environment)
142 .WithStandardInputPipe(stdin)
143 .WithStandardOutputPipe(stdout)
144 .WithStandardErrorPipe(PipeTarget.ToStringBuilder(stderr))
145 .WithValidation(CommandResultValidation.None);
146
147 try
148 {
149 var result = await command.ExecuteAsync(linked.Token);
150 return (result.ExitCode, stderr.ToString());
151 }
152 catch (OperationCanceledException) when (!ct.IsCancellationRequested && timeoutCts.IsCancellationRequested)
153 {
154 throw new GitTimeoutException($"git {Describe(fullArgs)} did not finish within {limit.TotalMinutes:0} min and was killed.");
155 }
156 }
157
158 /// <summary>Returns the installed git version, or throws with a message suitable for the startup log.</summary>
159 public async Task<Version> GetVersionAsync(CancellationToken ct = default)
160 {
161 GitResult result;
162 try
163 {
164 result = await RunAsync(null, ["--version"], ct: ct, throwOnError: false);
165 }
166 catch (Exception ex) when (ex is Win32Exception or FileNotFoundException or InvalidOperationException)
167 {
168 throw new GitException($"Could not start git ('{_gitPath}'): {ex.Message}", -1, "");
169 }
170
171 var version = result.ExitCode == 0 ? GitParsers.ParseVersion(result.Text) : null;
172 return version ?? throw new GitException(
173 $"'{_gitPath} --version' did not report a git version (exit code {result.ExitCode}): {result.Text.Trim()} {result.StdErr.Trim()}",
174 result.ExitCode,
175 result.StdErr);
176 }
177
178 private Dictionary<string, string?> MergeEnvironment(IReadOnlyDictionary<string, string?>? extra)
179 {
180 if (extra is not { Count: > 0 })
181 {
182 return _environment;
183 }
184
185 var merged = new Dictionary<string, string?>(_environment, StringComparer.Ordinal);
186 foreach (var (key, value) in extra)
187 {
188 merged[key] = value;
189 }
190
191 return merged;
192 }
193
194 private static List<string> BuildArgs(string? repoPath, IEnumerable<string> args)
195 {
196 var list = new List<string>();
197 if (repoPath is not null)
198 {
199 list.Add("--git-dir=" + repoPath);
200 }
201
202 // Print non-ASCII paths as UTF-8 instead of octal escapes.
203 list.Add("-c");
204 list.Add("core.quotePath=false");
205 list.AddRange(args);
206 return list;
207 }
208
209 private static string Describe(List<string> args)
210 {
211 var text = string.Join(' ', args.Where(a => !a.StartsWith("--git-dir=", StringComparison.Ordinal)));
212 return text.Length > 200 ? text[..200] + "…" : text;
213 }
214
215 /// <summary>Collects process output up to a cap, then cancels the run instead of growing without bound.</summary>
216 private sealed class CappedBuffer(long cap, CancellationTokenSource onOverflow) : Stream
217 {
218 private readonly MemoryStream _buffer = new();
219
220 public bool Truncated { get; private set; }
221
222 public byte[] ToArray() => _buffer.ToArray();
223
224 public override void Write(byte[] buffer, int offset, int count) => Write(buffer.AsSpan(offset, count));
225
226 public override void Write(ReadOnlySpan<byte> buffer)
227 {
228 var room = cap - _buffer.Length;
229 if (room >= buffer.Length)
230 {
231 _buffer.Write(buffer);
232 return;
233 }
234
235 if (room > 0)
236 {
237 _buffer.Write(buffer[..(int)room]);
238 }
239
240 if (!Truncated)
241 {
242 Truncated = true;
243 onOverflow.Cancel();
244 }
245 }
246
247 public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
248 {
249 Write(buffer.AsSpan(offset, count));
250 return Task.CompletedTask;
251 }
252
253 public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
254 {
255 Write(buffer.Span);
256 return ValueTask.CompletedTask;
257 }
258
259 public override void Flush()
260 {
261 }
262
263 public override bool CanRead => false;
264 public override bool CanSeek => false;
265 public override bool CanWrite => true;
266 public override long Length => _buffer.Length;
267
268 public override long Position
269 {
270 get => _buffer.Length;
271 set => throw new NotSupportedException();
272 }
273
274 public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
275 public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
276 public override void SetLength(long value) => throw new NotSupportedException();
277
278 protected override void Dispose(bool disposing)
279 {
280 if (disposing)
281 {
282 _buffer.Dispose();
283 }
284
285 base.Dispose(disposing);
286 }
287 }
288 }
added forge/Git/GitModels.cs +137 −0View file
@@ -0,0 +1,137 @@
1 using System.Text;
2
3 namespace Forge.Git;
4
5 public enum RefKind
6 {
7 Branch,
8 Tag,
9 Other,
10 }
11
12 /// <param name="FullName">For example refs/heads/feature/x.</param>
13 /// <param name="Name">Short name, for example feature/x.</param>
14 /// <param name="Sha">Object the ref points at (a tag object for annotated tags).</param>
15 /// <param name="ObjectType">commit, tag, tree or blob.</param>
16 /// <param name="PeeledSha">For annotated tags, the object the tag points at.</param>
17 public sealed record GitRef(
18 string FullName,
19 string Name,
20 RefKind Kind,
21 string Sha,
22 string ObjectType,
23 string? PeeledSha,
24 DateTimeOffset? Date,
25 string Subject)
26 {
27 public string TargetSha => PeeledSha ?? Sha;
28 }
29
30 public sealed record TreeEntry(string Name, string Mode, string Type, string Sha, long? Size)
31 {
32 public bool IsTree => Type == "tree";
33 public bool IsBlob => Type == "blob";
34 public bool IsSubmodule => Type == "commit";
35 public bool IsSymlink => Mode == "120000";
36 }
37
38 /// <summary>A file anywhere in a commit's tree, with its path from the repository root.</summary>
39 public sealed record FileEntry(string Path, long Size);
40
41 /// <summary>One line found by a content search.</summary>
42 public sealed record GrepMatch(string Path, int Line, string Text);
43
44 public sealed record CommitInfo(
45 string Sha,
46 IReadOnlyList<string> Parents,
47 string AuthorName,
48 string AuthorEmail,
49 DateTimeOffset AuthorDate,
50 string CommitterName,
51 string CommitterEmail,
52 DateTimeOffset CommitDate,
53 string Subject,
54 string Body,
55 string AuthorDateRaw = "")
56 {
57 public string ShortSha => Sha.Length > 8 ? Sha[..8] : Sha;
58 }
59
60 public sealed record BlobContent(byte[] Bytes, bool Truncated)
61 {
62 public bool IsBinary => GitParsers.IsBinary(Bytes);
63 public string Text => Encoding.UTF8.GetString(Bytes);
64 }
65
66 public enum FileChange
67 {
68 Modified,
69 Added,
70 Deleted,
71 Renamed,
72 Copied,
73 }
74
75 /// <summary>One row of `--numstat`. Counts are null for binary files.</summary>
76 public sealed record FileStat(string Path, string? OldPath, int? Added, int? Deleted)
77 {
78 public bool IsBinary => Added is null;
79 }
80
81 public enum DiffLineKind
82 {
83 Context,
84 Added,
85 Deleted,
86 NoNewline,
87 }
88
89 public sealed record DiffLine(DiffLineKind Kind, int? OldNumber, int? NewNumber, string Text);
90
91 public sealed class DiffHunk
92 {
93 public required string Header { get; init; }
94 public List<DiffLine> Lines { get; } = [];
95 }
96
97 public sealed class FileDiff
98 {
99 public string OldPath { get; set; } = "";
100 public string NewPath { get; set; } = "";
101 public FileChange Change { get; set; } = FileChange.Modified;
102 public bool IsBinary { get; set; }
103
104 /// <summary>The file went over the per-file line limit; its hunks were dropped.</summary>
105 public bool TooLarge { get; set; }
106
107 public int Added { get; set; }
108 public int Deleted { get; set; }
109 public List<DiffHunk> Hunks { get; } = [];
110
111 public string DisplayPath => Change == FileChange.Deleted ? OldPath : NewPath;
112 }
113
114 /// <param name="Truncated">The diff went over a limit (files, or bytes read from git) and is incomplete.</param>
115 public sealed record ParsedDiff(IReadOnlyList<FileDiff> Files, bool Truncated);
116
117 public sealed record CommitDiff(IReadOnlyList<FileStat> Stats, ParsedDiff Patch);
118
119 public sealed record GitIdentity(string Name, string Email);
120
121 /// <summary>Outcome of a tree-level merge.</summary>
122 /// <param name="TreeSha">The merged tree when the merge was clean; otherwise null.</param>
123 /// <param name="ConflictTreeSha">On conflict, a tree in which the conflicted files carry conflict markers.</param>
124 /// <param name="Conflicts">Paths that could not be merged automatically.</param>
125 /// <param name="Error">Set when git could not attempt the merge at all (for example unrelated histories).</param>
126 public sealed record MergeTreeResult(string? TreeSha, IReadOnlyList<string> Conflicts, string? Error, string? ConflictTreeSha = null)
127 {
128 public bool IsClean => TreeSha is not null;
129 }
130
131 public class GitException(string message, int exitCode, string stdErr) : Exception(message)
132 {
133 public int ExitCode { get; } = exitCode;
134 public string StdErr { get; } = stdErr;
135 }
136
137 public sealed class GitTimeoutException(string message) : Exception(message);
added forge/Git/GitParsers.cs +609 −0View file
@@ -0,0 +1,609 @@
1 using System.Globalization;
2 using System.Text;
3 using System.Text.RegularExpressions;
4
5 namespace Forge.Git;
6
7 /// <summary>Pure parsers for git plumbing output. No process access, so they are testable with canned input.</summary>
8 public static partial class GitParsers
9 {
10 public const string ZeroSha = "0000000000000000000000000000000000000000";
11
12 /// <summary>for-each-ref format matching <see cref="ParseRefs"/>. %00 is a NUL in for-each-ref formats.</summary>
13 public const string RefFormat =
14 "%(refname)%00%(objectname)%00%(objecttype)%00%(*objectname)%00%(creatordate:unix)%00%(contents:subject)";
15
16 /// <summary>log/show format matching <see cref="ParseLog"/>: ten fields, each terminated by NUL.</summary>
17 public const string LogFormat =
18 "%H%x00%P%x00%an%x00%ae%x00%ad%x00%cn%x00%ce%x00%ct%x00%s%x00%b%x00";
19
20 private const int LogFieldCount = 10;
21
22 public const int MaxDiffFiles = 300;
23 public const int MaxDiffLinesPerFile = 1000;
24
25 public static bool IsFullSha(string? value) => value is { Length: 40 } && IsHex(value);
26
27 public static bool IsHex(string value)
28 {
29 foreach (var c in value)
30 {
31 if (!char.IsAsciiHexDigit(c))
32 {
33 return false;
34 }
35 }
36
37 return value.Length > 0;
38 }
39
40 /// <summary>Same heuristic as git: a NUL byte in the first 8000 bytes means binary.</summary>
41 public static bool IsBinary(ReadOnlySpan<byte> content)
42 {
43 var head = content.Length > 8000 ? content[..8000] : content;
44 return head.Contains((byte)0);
45 }
46
47 public static Version? ParseVersion(string output)
48 {
49 var match = VersionPattern().Match(output);
50 return match.Success
51 ? new Version(int.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture),
52 int.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture))
53 : null;
54 }
55
56 public static IReadOnlyList<GitRef> ParseRefs(string output)
57 {
58 var refs = new List<GitRef>();
59 foreach (var line in output.Split('\n', StringSplitOptions.RemoveEmptyEntries))
60 {
61 var f = line.Split('\0');
62 if (f.Length < 6)
63 {
64 continue;
65 }
66
67 var fullName = f[0];
68 var (kind, name) = fullName switch
69 {
70 _ when fullName.StartsWith("refs/heads/", StringComparison.Ordinal) =>
71 (RefKind.Branch, fullName["refs/heads/".Length..]),
72 _ when fullName.StartsWith("refs/tags/", StringComparison.Ordinal) =>
73 (RefKind.Tag, fullName["refs/tags/".Length..]),
74 _ => (RefKind.Other, fullName),
75 };
76
77 DateTimeOffset? date = long.TryParse(f[4], NumberStyles.Integer, CultureInfo.InvariantCulture, out var unix)
78 ? DateTimeOffset.FromUnixTimeSeconds(unix)
79 : null;
80
81 refs.Add(new GitRef(fullName, name, kind, f[1], f[2], f[3].Length == 0 ? null : f[3], date, f[5]));
82 }
83
84 return refs;
85 }
86
87 /// <summary>Parses `for-each-ref --format=%(refname)%00%(objectname)` into name → sha.</summary>
88 public static Dictionary<string, string> ParseRefSnapshot(string output)
89 {
90 var map = new Dictionary<string, string>(StringComparer.Ordinal);
91 foreach (var line in output.Split('\n', StringSplitOptions.RemoveEmptyEntries))
92 {
93 var sep = line.IndexOf('\0');
94 if (sep > 0)
95 {
96 map[line[..sep]] = line[(sep + 1)..];
97 }
98 }
99
100 return map;
101 }
102
103 /// <summary>Parses `ls-tree -z --long`: "mode SP type SP sha SP+ size TAB path NUL".</summary>
104 public static IReadOnlyList<TreeEntry> ParseTree(string output)
105 {
106 var entries = new List<TreeEntry>();
107 foreach (var record in output.Split('\0', StringSplitOptions.RemoveEmptyEntries))
108 {
109 var tab = record.IndexOf('\t');
110 if (tab < 0)
111 {
112 continue;
113 }
114
115 var meta = record[..tab].Split(' ', StringSplitOptions.RemoveEmptyEntries);
116 if (meta.Length < 4)
117 {
118 continue;
119 }
120
121 var path = record[(tab + 1)..];
122 var slash = path.LastIndexOf('/');
123 var name = slash >= 0 ? path[(slash + 1)..] : path;
124 long? size = long.TryParse(meta[3], NumberStyles.Integer, CultureInfo.InvariantCulture, out var s) ? s : null;
125 entries.Add(new TreeEntry(name, meta[0], meta[1], meta[2], size));
126 }
127
128 return entries;
129 }
130
131 /// <summary>Parses `ls-tree -r -z --long` into the blobs of a whole tree, keeping full paths.</summary>
132 public static IReadOnlyList<FileEntry> ParseFileList(string output)
133 {
134 var files = new List<FileEntry>();
135 foreach (var record in output.Split('\0', StringSplitOptions.RemoveEmptyEntries))
136 {
137 var tab = record.IndexOf('\t');
138 if (tab < 0)
139 {
140 continue;
141 }
142
143 var meta = record[..tab].Split(' ', StringSplitOptions.RemoveEmptyEntries);
144 if (meta.Length < 4 || meta[1] != "blob")
145 {
146 continue;
147 }
148
149 files.Add(new FileEntry(
150 record[(tab + 1)..],
151 long.TryParse(meta[3], NumberStyles.Integer, CultureInfo.InvariantCulture, out var size) ? size : 0));
152 }
153
154 return files;
155 }
156
157 public const int MaxGrepLineLength = 300;
158
159 /// <summary>
160 /// Parses `grep -n -z &lt;commit&gt;`: each line is "commit:path NUL line-number NUL text".
161 /// Long lines (minified files) are cut to <see cref="MaxGrepLineLength"/> characters.
162 /// </summary>
163 public static IReadOnlyList<GrepMatch> ParseGrep(string output)
164 {
165 var matches = new List<GrepMatch>();
166 foreach (var record in output.Split('\n', StringSplitOptions.RemoveEmptyEntries))
167 {
168 var parts = record.Split('\0', 3);
169 var colon = parts[0].IndexOf(':');
170 if (parts.Length < 3
171 || colon < 0
172 || !int.TryParse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture, out var line))
173 {
174 continue;
175 }
176
177 var text = parts[2].TrimEnd('\r');
178 matches.Add(new GrepMatch(
179 parts[0][(colon + 1)..],
180 line,
181 text.Length > MaxGrepLineLength ? text[..MaxGrepLineLength] : text));
182 }
183
184 return matches;
185 }
186
187 public static IReadOnlyList<CommitInfo> ParseLog(string output)
188 {
189 var commits = new List<CommitInfo>();
190 var f = output.Split('\0');
191 for (var i = 0; i + LogFieldCount <= f.Length; i += LogFieldCount)
192 {
193 var sha = f[i].TrimStart('\n');
194 if (sha.Length == 0)
195 {
196 break;
197 }
198
199 commits.Add(new CommitInfo(
200 sha,
201 f[i + 1].Split(' ', StringSplitOptions.RemoveEmptyEntries),
202 f[i + 2],
203 f[i + 3],
204 RawDate(f[i + 4]),
205 f[i + 5],
206 f[i + 6],
207 UnixTime(f[i + 7]),
208 f[i + 8],
209 f[i + 9].TrimEnd('\n'),
210 f[i + 4].Trim()));
211 }
212
213 return commits;
214 }
215
216 /// <summary>Parses git's raw date format, "1700000000 +0100", keeping the author's time zone.</summary>
217 private static DateTimeOffset RawDate(string value)
218 {
219 var parts = value.Trim().Split(' ');
220 var time = UnixTime(parts[0]);
221 if (parts.Length == 2
222 && parts[1].Length == 5
223 && int.TryParse(parts[1].AsSpan(1, 2), NumberStyles.None, CultureInfo.InvariantCulture, out var hours)
224 && int.TryParse(parts[1].AsSpan(3, 2), NumberStyles.None, CultureInfo.InvariantCulture, out var minutes)
225 && hours <= 14
226 && minutes < 60)
227 {
228 var offset = new TimeSpan(hours, minutes, 0);
229 return time.ToOffset(parts[1][0] == '-' ? -offset : offset);
230 }
231
232 return time;
233 }
234
235 private static DateTimeOffset UnixTime(string value) =>
236 long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var unix)
237 ? DateTimeOffset.FromUnixTimeSeconds(unix)
238 : DateTimeOffset.UnixEpoch;
239
240 /// <summary>
241 /// Parses `--numstat -z`. Normal rows are "added TAB deleted TAB path NUL"; renames are
242 /// "added TAB deleted TAB NUL old NUL new NUL". Binary files report "-" for both counts.
243 /// </summary>
244 public static IReadOnlyList<FileStat> ParseNumstat(string output)
245 {
246 var stats = new List<FileStat>();
247 var tokens = output.Split('\0');
248 for (var i = 0; i < tokens.Length; i++)
249 {
250 var token = tokens[i].TrimStart('\n');
251 if (token.Length == 0)
252 {
253 continue;
254 }
255
256 var parts = token.Split('\t', 3);
257 if (parts.Length < 3)
258 {
259 continue;
260 }
261
262 int? added = int.TryParse(parts[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out var a) ? a : null;
263 int? deleted = int.TryParse(parts[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out var d) ? d : null;
264
265 if (parts[2].Length > 0)
266 {
267 stats.Add(new FileStat(parts[2], null, added, deleted));
268 }
269 else if (i + 2 < tokens.Length)
270 {
271 stats.Add(new FileStat(tokens[i + 2], tokens[i + 1], added, deleted));
272 i += 2;
273 }
274 }
275
276 return stats;
277 }
278
279 /// <summary>`rev-list --left-right --count base...tip` prints "behind TAB ahead".</summary>
280 public static (int Ahead, int Behind) ParseAheadBehind(string output)
281 {
282 var parts = output.Trim().Split('\t', ' ');
283 return parts.Length == 2
284 && int.TryParse(parts[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out var behind)
285 && int.TryParse(parts[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out var ahead)
286 ? (ahead, behind)
287 : (0, 0);
288 }
289
290 /// <summary>
291 /// Parses `merge-tree --write-tree --name-only -z`: "tree NUL", then on conflict (exit code 1)
292 /// "path NUL" per conflicted file, an empty field, and messages. Any other exit code is a failure.
293 /// </summary>
294 public static MergeTreeResult ParseMergeTree(int exitCode, string output, string stdErr)
295 {
296 var fields = output.Split('\0');
297 var tree = fields[0].Trim();
298 if (exitCode == 0 && IsFullSha(tree))
299 {
300 return new MergeTreeResult(tree, [], null);
301 }
302
303 if (exitCode == 1 && IsFullSha(tree))
304 {
305 var conflicts = fields.Skip(1).TakeWhile(f => f.Length > 0).Distinct().ToList();
306 return new MergeTreeResult(null, conflicts, null, tree);
307 }
308
309 var error = stdErr.Trim();
310 return new MergeTreeResult(null, [], error.Length > 0 ? error : $"git merge-tree exited with code {exitCode}.");
311 }
312
313 /// <summary>Parses a unified diff as printed by `git show --patch` into files and hunks.</summary>
314 public static ParsedDiff ParseDiff(
315 string patch,
316 bool inputTruncated = false,
317 int maxFiles = MaxDiffFiles,
318 int maxLinesPerFile = MaxDiffLinesPerFile)
319 {
320 var files = new List<FileDiff>();
321 var truncated = inputTruncated;
322 FileDiff? file = null;
323 DiffHunk? hunk = null;
324 var oldNo = 0;
325 var newNo = 0;
326 var lineCount = 0;
327
328 var lines = patch.Split('\n');
329 var last = lines.Length - 1;
330 for (var i = 0; i < lines.Length; i++)
331 {
332 var line = lines[i];
333 if (line.EndsWith('\r'))
334 {
335 line = line[..^1];
336 }
337
338 if (line.StartsWith("diff --git ", StringComparison.Ordinal))
339 {
340 if (files.Count >= maxFiles)
341 {
342 truncated = true;
343 break;
344 }
345
346 file = new FileDiff();
347 hunk = null;
348 lineCount = 0;
349 ParseDiffHeaderPaths(line["diff --git ".Length..], file);
350 files.Add(file);
351 continue;
352 }
353
354 if (file is null)
355 {
356 continue;
357 }
358
359 if (line.StartsWith("@@ ", StringComparison.Ordinal))
360 {
361 var match = HunkHeader().Match(line);
362 if (match.Success)
363 {
364 oldNo = int.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture);
365 newNo = int.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture);
366 hunk = new DiffHunk { Header = line };
367 if (!file.TooLarge)
368 {
369 file.Hunks.Add(hunk);
370 }
371
372 continue;
373 }
374 }
375
376 if (hunk is null)
377 {
378 ParseDiffHeaderLine(line, file);
379 continue;
380 }
381
382 // The trailing empty string after the final newline is not a diff line.
383 if (i == last && line.Length == 0)
384 {
385 break;
386 }
387
388 DiffLine parsed;
389 switch (line.Length == 0 ? ' ' : line[0])
390 {
391 case '+':
392 parsed = new DiffLine(DiffLineKind.Added, null, newNo++, line[1..]);
393 file.Added++;
394 break;
395 case '-':
396 parsed = new DiffLine(DiffLineKind.Deleted, oldNo++, null, line[1..]);
397 file.Deleted++;
398 break;
399 case '\\':
400 parsed = new DiffLine(DiffLineKind.NoNewline, null, null, line[1..].Trim());
401 break;
402 default:
403 parsed = new DiffLine(DiffLineKind.Context, oldNo++, newNo++, line.Length == 0 ? "" : line[1..]);
404 break;
405 }
406
407 if (file.TooLarge)
408 {
409 continue;
410 }
411
412 if (++lineCount > maxLinesPerFile)
413 {
414 file.TooLarge = true;
415 file.Hunks.Clear();
416 continue;
417 }
418
419 hunk.Lines.Add(parsed);
420 }
421
422 return new ParsedDiff(files, truncated);
423 }
424
425 private static void ParseDiffHeaderLine(string line, FileDiff file)
426 {
427 if (line.StartsWith("new file mode", StringComparison.Ordinal))
428 {
429 file.Change = FileChange.Added;
430 }
431 else if (line.StartsWith("deleted file mode", StringComparison.Ordinal))
432 {
433 file.Change = FileChange.Deleted;
434 }
435 else if (line.StartsWith("rename from ", StringComparison.Ordinal))
436 {
437 file.Change = FileChange.Renamed;
438 file.OldPath = Unquote(line["rename from ".Length..]);
439 }
440 else if (line.StartsWith("rename to ", StringComparison.Ordinal))
441 {
442 file.Change = FileChange.Renamed;
443 file.NewPath = Unquote(line["rename to ".Length..]);
444 }
445 else if (line.StartsWith("copy from ", StringComparison.Ordinal))
446 {
447 file.Change = FileChange.Copied;
448 file.OldPath = Unquote(line["copy from ".Length..]);
449 }
450 else if (line.StartsWith("copy to ", StringComparison.Ordinal))
451 {
452 file.Change = FileChange.Copied;
453 file.NewPath = Unquote(line["copy to ".Length..]);
454 }
455 else if (line.StartsWith("Binary files ", StringComparison.Ordinal)
456 || line.StartsWith("GIT binary patch", StringComparison.Ordinal))
457 {
458 file.IsBinary = true;
459 }
460 else if (line.StartsWith("--- ", StringComparison.Ordinal))
461 {
462 var path = StripDiffPrefix(line[4..]);
463 if (path is not null)
464 {
465 file.OldPath = path;
466 }
467 }
468 else if (line.StartsWith("+++ ", StringComparison.Ordinal))
469 {
470 var path = StripDiffPrefix(line[4..]);
471 if (path is not null)
472 {
473 file.NewPath = path;
474 }
475 }
476 }
477
478 /// <summary>Turns "a/src/x.cs" from a ---/+++ line into "src/x.cs"; null for /dev/null.</summary>
479 private static string? StripDiffPrefix(string raw)
480 {
481 // Git appends a tab after names containing whitespace, for GNU patch.
482 var path = Unquote(raw.TrimEnd('\t'));
483 if (path == "/dev/null")
484 {
485 return null;
486 }
487
488 return path.Length > 2 && path[1] == '/' ? path[2..] : path;
489 }
490
491 /// <summary>
492 /// Best-effort path extraction from "a/old b/new". Used for files with no ---/+++ lines
493 /// (binary, mode-only, empty); rename headers override it afterwards.
494 /// </summary>
495 private static void ParseDiffHeaderPaths(string rest, FileDiff file)
496 {
497 string a, b;
498 if (rest.StartsWith('"'))
499 {
500 var end = FindClosingQuote(rest, 0);
501 a = Unquote(rest[..(end + 1)]);
502 b = Unquote(rest[(end + 1)..].TrimStart());
503 }
504 else if (rest.Length >= 5
505 && rest.Length % 2 == 1
506 && rest[rest.Length / 2] == ' '
507 && rest.AsSpan(2, rest.Length / 2 - 2).SequenceEqual(rest.AsSpan(rest.Length / 2 + 3)))
508 {
509 // Same path on both sides: "a/P b/P" splits exactly in the middle.
510 a = rest[..(rest.Length / 2)];
511 b = rest[(rest.Length / 2 + 1)..];
512 }
513 else
514 {
515 var split = rest.IndexOf(" b/", StringComparison.Ordinal);
516 if (split < 0)
517 {
518 split = rest.IndexOf(" \"b/", StringComparison.Ordinal);
519 }
520
521 if (split < 0)
522 {
523 return;
524 }
525
526 a = rest[..split];
527 b = Unquote(rest[(split + 1)..]);
528 }
529
530 file.OldPath = a.Length > 2 ? a[2..] : a;
531 file.NewPath = b.Length > 2 ? b[2..] : b;
532 }
533
534 private static int FindClosingQuote(string value, int open)
535 {
536 for (var i = open + 1; i < value.Length; i++)
537 {
538 if (value[i] == '\\')
539 {
540 i++;
541 }
542 else if (value[i] == '"')
543 {
544 return i;
545 }
546 }
547
548 return value.Length - 1;
549 }
550
551 /// <summary>Reverses git's C-style path quoting ("a\tb\303\251"). Unquoted input is returned as is.</summary>
552 public static string Unquote(string value)
553 {
554 if (value.Length < 2 || value[0] != '"' || value[^1] != '"')
555 {
556 return value;
557 }
558
559 var bytes = new List<byte>(value.Length);
560 for (var i = 1; i < value.Length - 1; i++)
561 {
562 var c = value[i];
563 if (c != '\\' || i + 1 >= value.Length - 1)
564 {
565 var pair = char.IsHighSurrogate(c) && i + 1 < value.Length - 1 && char.IsLowSurrogate(value[i + 1]);
566 bytes.AddRange(Encoding.UTF8.GetBytes(value.Substring(i, pair ? 2 : 1)));
567 if (pair)
568 {
569 i++;
570 }
571
572 continue;
573 }
574
575 var next = value[++i];
576 if (next is >= '0' and <= '7')
577 {
578 var octal = next - '0';
579 for (var n = 0; n < 2 && i + 1 < value.Length - 1 && value[i + 1] is >= '0' and <= '7'; n++)
580 {
581 octal = octal * 8 + (value[++i] - '0');
582 }
583
584 bytes.Add((byte)octal);
585 continue;
586 }
587
588 bytes.Add(next switch
589 {
590 'n' => (byte)'\n',
591 't' => (byte)'\t',
592 'r' => (byte)'\r',
593 'a' => 7,
594 'b' => 8,
595 'f' => 12,
596 'v' => 11,
597 _ => (byte)next,
598 });
599 }
600
601 return Encoding.UTF8.GetString(bytes.ToArray());
602 }
603
604 [GeneratedRegex(@"^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@")]
605 private static partial Regex HunkHeader();
606
607 [GeneratedRegex(@"(\d+)\.(\d+)")]
608 private static partial Regex VersionPattern();
609 }
added forge/Git/GitRepo.cs +558 −0View file
@@ -0,0 +1,558 @@
1 using System.Globalization;
2
3 namespace Forge.Git;
4
5 /// <summary>
6 /// Read and write operations on one bare repository, built on <see cref="GitCli"/>.
7 /// Every revision argument here is expected to be a full SHA that came out of
8 /// <see cref="RefResolver"/> or out of git itself; user-typed names never reach git.
9 /// </summary>
10 public sealed class GitRepo(GitCli git)
11 {
12 public const int MaxDiffBytes = 4 * 1024 * 1024;
13
14 public async Task InitBareAsync(string repoPath, CancellationToken ct = default)
15 {
16 await git.RunAsync(null, ["init", "--bare", "--initial-branch=main", repoPath], ct: ct);
17 await git.RunAsync(repoPath, ["config", "receive.fsckObjects", "true"], ct: ct);
18 // Lets clients use partial clone (--filter=blob:none).
19 await git.RunAsync(repoPath, ["config", "uploadpack.allowFilter", "true"], ct: ct);
20 }
21
22 /// <summary>Branches and tags, branches first, each group sorted by name.</summary>
23 public async Task<IReadOnlyList<GitRef>> ListRefsAsync(string repoPath, CancellationToken ct = default)
24 {
25 var result = await git.RunAsync(
26 repoPath,
27 ["for-each-ref", "--format=" + GitParsers.RefFormat, "refs/heads", "refs/tags"],
28 ct: ct);
29 return GitParsers.ParseRefs(result.Text);
30 }
31
32 /// <summary>Tags, newest first.</summary>
33 public async Task<IReadOnlyList<GitRef>> ListTagsByDateAsync(string repoPath, CancellationToken ct = default)
34 {
35 var result = await git.RunAsync(
36 repoPath,
37 ["for-each-ref", "--sort=-creatordate", "--format=" + GitParsers.RefFormat, "refs/tags"],
38 ct: ct);
39 return GitParsers.ParseRefs(result.Text);
40 }
41
42 /// <summary>Every ref with its SHA. Two snapshots around a push give the list of changed refs.</summary>
43 public async Task<Dictionary<string, string>> SnapshotRefsAsync(string repoPath, CancellationToken ct = default)
44 {
45 var result = await git.RunAsync(
46 repoPath,
47 ["for-each-ref", "--format=%(refname)%00%(objectname)"],
48 ct: ct);
49 return GitParsers.ParseRefSnapshot(result.Text);
50 }
51
52 /// <summary>Resolves a full or abbreviated hex SHA to a commit SHA. Anything that is not hex is rejected before git runs.</summary>
53 public async Task<string?> ResolveCommitAsync(string repoPath, string hex, CancellationToken ct = default)
54 {
55 if (hex.Length is < 4 or > 40 || !GitParsers.IsHex(hex))
56 {
57 return null;
58 }
59
60 var result = await git.RunAsync(
61 repoPath,
62 ["rev-parse", "--verify", "--quiet", "--end-of-options", hex + "^{commit}"],
63 ct: ct,
64 throwOnError: false);
65 var sha = result.Text.Trim();
66 return result.ExitCode == 0 && GitParsers.IsFullSha(sha) ? sha : null;
67 }
68
69 public async Task<string?> GetRootTreeShaAsync(string repoPath, string commitSha, CancellationToken ct = default)
70 {
71 RequireSha(commitSha);
72 var result = await git.RunAsync(
73 repoPath,
74 ["rev-parse", "--verify", "--quiet", "--end-of-options", commitSha + "^{tree}"],
75 ct: ct,
76 throwOnError: false);
77 var sha = result.Text.Trim();
78 return result.ExitCode == 0 && GitParsers.IsFullSha(sha) ? sha : null;
79 }
80
81 /// <summary>Looks up one path inside a commit. Returns null when the path does not exist.</summary>
82 public async Task<TreeEntry?> GetEntryAsync(string repoPath, string commitSha, string path, CancellationToken ct = default)
83 {
84 RequireSha(commitSha);
85 var result = await git.RunAsync(
86 repoPath,
87 ["ls-tree", "-z", "--long", commitSha, "--", path.TrimEnd('/')],
88 ct: ct,
89 throwOnError: false);
90 return result.ExitCode == 0 ? GitParsers.ParseTree(result.Text).FirstOrDefault() : null;
91 }
92
93 /// <summary>Lists the direct children of a tree object.</summary>
94 public async Task<IReadOnlyList<TreeEntry>> ListTreeAsync(string repoPath, string treeSha, CancellationToken ct = default)
95 {
96 RequireSha(treeSha);
97 var result = await git.RunAsync(repoPath, ["ls-tree", "-z", "--long", treeSha], ct: ct);
98 return GitParsers.ParseTree(result.Text);
99 }
100
101 /// <summary>
102 /// Every file of a commit, in git's path order. Stops at <paramref name="maxOutputBytes"/> of listing,
103 /// so for a huge repository the result is a prefix; <c>Truncated</c> says so.
104 /// </summary>
105 public async Task<(IReadOnlyList<FileEntry> Files, bool Truncated)> ListFilesAsync(
106 string repoPath,
107 string commitSha,
108 long maxOutputBytes = 8 * 1024 * 1024,
109 CancellationToken ct = default)
110 {
111 RequireSha(commitSha);
112 var result = await git.RunAsync(
113 repoPath,
114 ["ls-tree", "-r", "-z", "--long", commitSha],
115 ct: ct,
116 maxOutputBytes: maxOutputBytes);
117 var text = result.Text;
118 if (result.Truncated)
119 {
120 // The last record is probably cut in half.
121 var end = text.LastIndexOf('\0');
122 text = end < 0 ? "" : text[..end];
123 }
124
125 return (GitParsers.ParseFileList(text), result.Truncated);
126 }
127
128 /// <summary>
129 /// Finds lines containing <paramref name="text"/> (literal, case-insensitive) in the text files of a commit.
130 /// At most <paramref name="maxPerFile"/> lines per file; <c>Truncated</c> when the output limit cut the search short.
131 /// </summary>
132 public async Task<(IReadOnlyList<GrepMatch> Matches, bool Truncated)> GrepAsync(
133 string repoPath,
134 string commitSha,
135 string text,
136 int maxPerFile = 10,
137 long maxOutputBytes = 256 * 1024,
138 CancellationToken ct = default)
139 {
140 RequireSha(commitSha);
141 // A newline would split the text into several patterns.
142 if (text.Length == 0 || text.Contains('\n') || text.Contains('\r') || text.Contains('\0'))
143 {
144 return ([], false);
145 }
146
147 var result = await git.RunAsync(
148 repoPath,
149 [
150 "grep", "-n", "-z", "-I", "-i", "-F", "--no-color",
151 "--max-count=" + maxPerFile.ToString(CultureInfo.InvariantCulture),
152 // The text follows -e, so it is never read as an option, whatever it starts with.
153 "-e", text,
154 commitSha, "--",
155 ],
156 ct: ct,
157 maxOutputBytes: maxOutputBytes,
158 throwOnError: false);
159
160 // Exit code 1 means "no match"; anything above is a real error.
161 if (!result.Truncated && result.ExitCode > 1)
162 {
163 throw new GitException($"git grep exited with code {result.ExitCode}: {result.StdErr.Trim()}", result.ExitCode, result.StdErr);
164 }
165
166 var output = result.Text;
167 if (result.Truncated)
168 {
169 var end = output.LastIndexOf('\n');
170 output = end < 0 ? "" : output[..end];
171 }
172
173 return (GitParsers.ParseGrep(output), result.Truncated);
174 }
175
176 /// <summary>Author name, e-mail and time of the newest <paramref name="max"/> commits (mailmap applied), newest first.</summary>
177 public async Task<IReadOnlyList<(string Name, string Email, DateTimeOffset When)>> ListAuthorshipAsync(
178 string repoPath,
179 string commitSha,
180 int max,
181 CancellationToken ct = default)
182 {
183 RequireSha(commitSha);
184 var result = await git.RunAsync(
185 repoPath,
186 [
187 "log", "--format=%aN%x00%aE%x00%at%x00",
188 "-n", max.ToString(CultureInfo.InvariantCulture),
189 "--end-of-options", commitSha, "--",
190 ],
191 ct: ct);
192
193 var fields = result.Text.Split('\0');
194 var rows = new List<(string, string, DateTimeOffset)>(fields.Length / 3);
195 for (var i = 0; i + 3 <= fields.Length; i += 3)
196 {
197 if (long.TryParse(fields[i + 2], NumberStyles.Integer, CultureInfo.InvariantCulture, out var unix))
198 {
199 rows.Add((fields[i].TrimStart('\n'), fields[i + 1], DateTimeOffset.FromUnixTimeSeconds(unix)));
200 }
201 }
202
203 return rows;
204 }
205
206 /// <summary>How many commits are reachable from a commit.</summary>
207 public async Task<int> CountCommitsAsync(string repoPath, string commitSha, CancellationToken ct = default)
208 {
209 RequireSha(commitSha);
210 var result = await git.RunAsync(repoPath, ["rev-list", "--count", commitSha, "--"], ct: ct, throwOnError: false);
211 return result.ExitCode == 0 && int.TryParse(result.Text.Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out var count)
212 ? count
213 : 0;
214 }
215
216 public async Task<long> GetBlobSizeAsync(string repoPath, string blobSha, CancellationToken ct = default)
217 {
218 RequireSha(blobSha);
219 var result = await git.RunAsync(repoPath, ["cat-file", "-s", blobSha], ct: ct);
220 return long.Parse(result.Text.Trim(), CultureInfo.InvariantCulture);
221 }
222
223 /// <summary>Reads a blob, stopping at <paramref name="maxBytes"/>.</summary>
224 public async Task<BlobContent> ReadBlobAsync(string repoPath, string blobSha, long maxBytes, CancellationToken ct = default)
225 {
226 RequireSha(blobSha);
227 var result = await git.RunAsync(
228 repoPath,
229 ["cat-file", "blob", blobSha],
230 ct: ct,
231 maxOutputBytes: maxBytes);
232 return new BlobContent(result.StdOut, result.Truncated);
233 }
234
235 public async Task<IReadOnlyList<CommitInfo>> LogAsync(
236 string repoPath,
237 string commitSha,
238 string? path = null,
239 int skip = 0,
240 int take = 30,
241 CancellationToken ct = default)
242 {
243 RequireSha(commitSha);
244 List<string> args =
245 [
246 "log",
247 "--format=" + GitParsers.LogFormat, "--date=raw",
248 "-n", take.ToString(CultureInfo.InvariantCulture),
249 "--skip=" + skip.ToString(CultureInfo.InvariantCulture),
250 "--end-of-options",
251 commitSha,
252 "--",
253 ];
254 if (!string.IsNullOrEmpty(path))
255 {
256 args.Add(path);
257 }
258
259 var result = await git.RunAsync(repoPath, args, ct: ct);
260 return GitParsers.ParseLog(result.Text);
261 }
262
263 /// <summary>Commits reachable from <paramref name="newSha"/> but not from <paramref name="oldSha"/>, newest first.</summary>
264 public async Task<IReadOnlyList<CommitInfo>> LogRangeAsync(
265 string repoPath,
266 string? oldSha,
267 string newSha,
268 int take,
269 CancellationToken ct = default)
270 {
271 RequireSha(newSha);
272 var range = oldSha is null || oldSha == GitParsers.ZeroSha ? newSha : $"{RequireSha(oldSha)}..{newSha}";
273 var result = await git.RunAsync(
274 repoPath,
275 [
276 "log",
277 "--format=" + GitParsers.LogFormat, "--date=raw",
278 "-n", take.ToString(CultureInfo.InvariantCulture),
279 "--end-of-options",
280 range,
281 "--",
282 ],
283 ct: ct,
284 throwOnError: false);
285 return result.ExitCode == 0 ? GitParsers.ParseLog(result.Text) : [];
286 }
287
288 public async Task<CommitInfo?> GetCommitAsync(string repoPath, string commitSha, CancellationToken ct = default)
289 {
290 RequireSha(commitSha);
291 var result = await git.RunAsync(
292 repoPath,
293 ["show", "--no-patch", "--format=" + GitParsers.LogFormat, "--date=raw", "--end-of-options", commitSha, "--"],
294 ct: ct,
295 throwOnError: false);
296 return result.ExitCode == 0 ? GitParsers.ParseLog(result.Text).FirstOrDefault() : null;
297 }
298
299 /// <summary>Change summary and patch for one commit. Merges are shown against their first parent.</summary>
300 public async Task<CommitDiff> GetDiffAsync(
301 string repoPath,
302 string commitSha,
303 bool ignoreWhitespace = false,
304 CancellationToken ct = default)
305 {
306 RequireSha(commitSha);
307 string[] whitespace = ignoreWhitespace ? ["-w"] : [];
308
309 var numstat = await git.RunAsync(
310 repoPath,
311 [
312 "show", "--format=", "--numstat", "-z", "-M", "--diff-merges=first-parent", .. whitespace,
313 "--end-of-options", commitSha, "--",
314 ],
315 ct: ct);
316
317 var patch = await git.RunAsync(
318 repoPath,
319 [
320 "show", "--format=", "--patch", "-M", "--diff-merges=first-parent",
321 "--no-color", "--no-ext-diff", "--no-textconv", .. whitespace,
322 "--end-of-options", commitSha, "--",
323 ],
324 ct: ct,
325 maxOutputBytes: MaxDiffBytes);
326
327 return new CommitDiff(
328 GitParsers.ParseNumstat(numstat.Text),
329 GitParsers.ParseDiff(patch.Text, inputTruncated: patch.Truncated));
330 }
331
332 public async Task<(int Ahead, int Behind)> AheadBehindAsync(
333 string repoPath,
334 string baseSha,
335 string tipSha,
336 CancellationToken ct = default)
337 {
338 RequireSha(baseSha);
339 RequireSha(tipSha);
340 var result = await git.RunAsync(
341 repoPath,
342 ["rev-list", "--left-right", "--count", "--end-of-options", $"{baseSha}...{tipSha}", "--"],
343 ct: ct,
344 throwOnError: false);
345 return result.ExitCode == 0 ? GitParsers.ParseAheadBehind(result.Text) : (0, 0);
346 }
347
348 /// <summary>The best common ancestor of two commits, or null when their histories are unrelated.</summary>
349 public async Task<string?> MergeBaseAsync(string repoPath, string a, string b, CancellationToken ct = default)
350 {
351 RequireSha(a);
352 RequireSha(b);
353 var result = await git.RunAsync(repoPath, ["merge-base", a, b], ct: ct, throwOnError: false);
354 var sha = result.Text.Trim();
355 return result.ExitCode == 0 && GitParsers.IsFullSha(sha) ? sha : null;
356 }
357
358 /// <summary>Change summary and patch between two commits.</summary>
359 public async Task<CommitDiff> GetRangeDiffAsync(
360 string repoPath,
361 string fromSha,
362 string toSha,
363 bool ignoreWhitespace = false,
364 CancellationToken ct = default)
365 {
366 RequireSha(fromSha);
367 RequireSha(toSha);
368 string[] whitespace = ignoreWhitespace ? ["-w"] : [];
369
370 var numstat = await git.RunAsync(
371 repoPath,
372 ["diff", "--numstat", "-z", "-M", .. whitespace, "--end-of-options", fromSha, toSha, "--"],
373 ct: ct);
374
375 var patch = await git.RunAsync(
376 repoPath,
377 [
378 "diff", "--patch", "-M", "--no-color", "--no-ext-diff", "--no-textconv", .. whitespace,
379 "--end-of-options", fromSha, toSha, "--",
380 ],
381 ct: ct,
382 maxOutputBytes: MaxDiffBytes);
383
384 return new CommitDiff(
385 GitParsers.ParseNumstat(numstat.Text),
386 GitParsers.ParseDiff(patch.Text, inputTruncated: patch.Truncated));
387 }
388
389 /// <summary>
390 /// Merges two commits without a working tree (`git merge-tree --write-tree`). Nothing but loose
391 /// objects is written: on success the caller gets a tree to commit, on conflict the list of files.
392 /// </summary>
393 /// <param name="mergeBaseSha">
394 /// Overrides the common ancestor. This is what turns a merge into a cherry-pick (base = the commit's
395 /// parent), a revert (base = the commit, theirs = its parent) or one step of a rebase.
396 /// </param>
397 public async Task<MergeTreeResult> MergeTreeAsync(
398 string repoPath,
399 string oursSha,
400 string theirsSha,
401 CancellationToken ct = default,
402 string? mergeBaseSha = null)
403 {
404 RequireSha(oursSha);
405 RequireSha(theirsSha);
406 string[] mergeBase = mergeBaseSha is null ? [] : ["--merge-base=" + RequireSha(mergeBaseSha)];
407 var result = await git.RunAsync(
408 repoPath,
409 ["merge-tree", "--write-tree", "--name-only", "-z", .. mergeBase, oursSha, theirsSha],
410 ct: ct,
411 timeout: TimeSpan.FromMinutes(2),
412 throwOnError: false);
413 return GitParsers.ParseMergeTree(result.ExitCode, result.Text, result.StdErr);
414 }
415
416 /// <summary>Creates a commit object for a tree and returns its SHA. No ref is moved.</summary>
417 public async Task<string> CommitTreeAsync(
418 string repoPath,
419 string treeSha,
420 IReadOnlyList<string> parents,
421 string message,
422 GitIdentity who,
423 CancellationToken ct = default,
424 GitIdentity? author = null,
425 string? authorDateRaw = null)
426 {
427 RequireSha(treeSha);
428 List<string> args = ["commit-tree", treeSha];
429 foreach (var parent in parents)
430 {
431 args.Add("-p");
432 args.Add(RequireSha(parent));
433 }
434
435 // The message goes in on stdin, so nothing in it can be read as an option.
436 args.Add("-F");
437 args.Add("-");
438
439 using var stdin = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(message.TrimEnd() + "\n"));
440 var result = await git.RunAsync(
441 repoPath,
442 args,
443 stdin,
444 ct,
445 extraEnvironment: new Dictionary<string, string?>
446 {
447 // A replayed commit keeps its original author and date; the committer is whoever replays it.
448 ["GIT_AUTHOR_NAME"] = (author ?? who).Name,
449 ["GIT_AUTHOR_EMAIL"] = (author ?? who).Email,
450 ["GIT_AUTHOR_DATE"] = string.IsNullOrEmpty(authorDateRaw) ? null : authorDateRaw,
451 ["GIT_COMMITTER_NAME"] = who.Name,
452 ["GIT_COMMITTER_EMAIL"] = who.Email,
453 });
454 return RequireSha(result.Text.Trim());
455 }
456
457 /// <summary>Stores content as a blob and returns its SHA.</summary>
458 public async Task<string> WriteBlobAsync(string repoPath, byte[] content, CancellationToken ct = default)
459 {
460 using var stdin = new MemoryStream(content);
461 var result = await git.RunAsync(repoPath, ["hash-object", "-w", "--stdin"], stdin, ct);
462 return RequireSha(result.Text.Trim());
463 }
464
465 /// <summary>
466 /// Returns a new tree: <paramref name="treeSha"/> with some paths replaced or removed.
467 /// A bare repository has no index, so a throwaway one is used and deleted afterwards.
468 /// </summary>
469 /// <param name="changes">Path → (mode, blob SHA), or null to remove the path.</param>
470 public async Task<string> BuildTreeAsync(
471 string repoPath,
472 string treeSha,
473 IReadOnlyDictionary<string, (string Mode, string BlobSha)?> changes,
474 CancellationToken ct = default)
475 {
476 RequireSha(treeSha);
477 var scratch = Path.Combine(git.WorkDirectory, "tmp");
478 Directory.CreateDirectory(scratch);
479 var index = Path.Combine(scratch, "index-" + Guid.NewGuid().ToString("N"));
480 var environment = new Dictionary<string, string?> { ["GIT_INDEX_FILE"] = index };
481 try
482 {
483 await git.RunAsync(repoPath, ["read-tree", treeSha], ct: ct, extraEnvironment: environment);
484 foreach (var (path, entry) in changes)
485 {
486 // The path is the tail of a single argument (or follows "--"), so it cannot be read as an option.
487 string[] args = entry is { } e
488 ? ["update-index", "--add", "--cacheinfo", $"{e.Mode},{RequireSha(e.BlobSha)},{path}"]
489 : ["update-index", "--force-remove", "--", path];
490 await git.RunAsync(repoPath, args, ct: ct, extraEnvironment: environment);
491 }
492
493 var result = await git.RunAsync(repoPath, ["write-tree"], ct: ct, extraEnvironment: environment);
494 return RequireSha(result.Text.Trim());
495 }
496 finally
497 {
498 File.Delete(index);
499 File.Delete(index + ".lock");
500 }
501 }
502
503 /// <summary>True when "refs/heads/x" or "refs/tags/x" is a name git accepts.</summary>
504 public async Task<bool> IsValidRefNameAsync(string fullRefName, CancellationToken ct = default)
505 {
506 // The refs/ prefix guarantees the argument cannot be taken for an option.
507 if (!fullRefName.StartsWith("refs/", StringComparison.Ordinal) || fullRefName.Length > 250)
508 {
509 return false;
510 }
511
512 var result = await git.RunAsync(null, ["check-ref-format", fullRefName], ct: ct, throwOnError: false);
513 return result.ExitCode == 0;
514 }
515
516 /// <summary>
517 /// Moves, creates or deletes a ref, but only if it still has the expected value
518 /// (<see cref="GitParsers.ZeroSha"/> for "must not exist"). Returns false when it changed meanwhile.
519 /// </summary>
520 public async Task<bool> UpdateRefAsync(
521 string repoPath,
522 string fullRefName,
523 string? newSha,
524 string expectedOldSha,
525 CancellationToken ct = default)
526 {
527 if (!fullRefName.StartsWith("refs/", StringComparison.Ordinal))
528 {
529 throw new ArgumentException("Expected a full ref name.", nameof(fullRefName));
530 }
531
532 RequireSha(expectedOldSha);
533 string[] args = newSha is null
534 ? ["update-ref", "-d", fullRefName, expectedOldSha]
535 : ["update-ref", fullRefName, RequireSha(newSha), expectedOldSha];
536 var result = await git.RunAsync(repoPath, args, ct: ct, throwOnError: false);
537 return result.ExitCode == 0;
538 }
539
540 /// <summary>The branch HEAD points at, or null when HEAD is detached.</summary>
541 public async Task<string?> GetHeadBranchAsync(string repoPath, CancellationToken ct = default)
542 {
543 var result = await git.RunAsync(repoPath, ["symbolic-ref", "--quiet", "HEAD"], ct: ct, throwOnError: false);
544 var target = result.Text.Trim();
545 return result.ExitCode == 0 && target.StartsWith("refs/heads/", StringComparison.Ordinal)
546 ? target["refs/heads/".Length..]
547 : null;
548 }
549
550 /// <summary>Points HEAD at a branch. The caller must have checked that the branch exists.</summary>
551 public Task SetHeadBranchAsync(string repoPath, string branch, CancellationToken ct = default) =>
552 git.RunAsync(repoPath, ["symbolic-ref", "HEAD", "refs/heads/" + branch], ct: ct);
553
554 private static string RequireSha(string value) =>
555 GitParsers.IsFullSha(value)
556 ? value
557 : throw new ArgumentException("Expected a full 40-character SHA.", nameof(value));
558 }
added forge/Git/RefResolver.cs +149 −0View file
@@ -0,0 +1,149 @@
1 namespace Forge.Git;
2
3 public enum ResolvedKind
4 {
5 Branch,
6 Tag,
7 Commit,
8 }
9
10 /// <param name="Name">Branch or tag name, or the full SHA when the URL named a commit.</param>
11 /// <param name="Path">Path inside the tree, without leading or trailing slashes; empty for the root.</param>
12 public sealed record ResolvedRef(string Name, ResolvedKind Kind, string CommitSha, string Path);
13
14 /// <summary>
15 /// Splits "feature/x/src/a.cs" into a ref and a path. The split is ambiguous, so the longest
16 /// prefix that names an existing branch or tag wins; a full SHA is accepted as a fallback.
17 /// Input is only ever compared against the repository's own ref list, so a hostile "ref"
18 /// such as "--upload-pack=..." resolves to nothing and never reaches a git command line.
19 /// </summary>
20 public sealed class RefResolver(GitRepo git)
21 {
22 public async Task<ResolvedRef?> ResolveAsync(
23 string repoPath,
24 string? refAndPath,
25 IReadOnlyList<GitRef>? refs = null,
26 CancellationToken ct = default)
27 {
28 var segments = SplitSegments(refAndPath);
29 if (segments is null)
30 {
31 return null;
32 }
33
34 refs ??= await git.ListRefsAsync(repoPath, ct);
35 var match = Match(refs, segments);
36 if (match is not null)
37 {
38 return match;
39 }
40
41 if (GitParsers.IsFullSha(segments[0]))
42 {
43 var sha = await git.ResolveCommitAsync(repoPath, segments[0], ct);
44 if (sha is not null)
45 {
46 return new ResolvedRef(sha, ResolvedKind.Commit, sha, string.Join('/', segments.Skip(1)));
47 }
48 }
49
50 return null;
51 }
52
53 /// <summary>
54 /// Resolves text that must name one whole ref or commit, with no path after it:
55 /// an existing branch, an existing tag, or a hex SHA. Used by compare and by "create from".
56 /// </summary>
57 public async Task<ResolvedRef?> ResolveExactAsync(
58 string repoPath,
59 string? spec,
60 IReadOnlyList<GitRef> refs,
61 CancellationToken ct = default)
62 {
63 if (string.IsNullOrEmpty(spec))
64 {
65 return null;
66 }
67
68 var found = Find(refs, spec, RefKind.Branch) ?? Find(refs, spec, RefKind.Tag);
69 if (found is not null && (found.ObjectType == "commit" || found.PeeledSha is not null))
70 {
71 return new ResolvedRef(
72 found.Name,
73 found.Kind == RefKind.Branch ? ResolvedKind.Branch : ResolvedKind.Tag,
74 found.TargetSha,
75 "");
76 }
77
78 var sha = await git.ResolveCommitAsync(repoPath, spec, ct);
79 return sha is null ? null : new ResolvedRef(sha, ResolvedKind.Commit, sha, "");
80 }
81
82 /// <summary>Longest-prefix match against existing refs. Branches win over tags of the same name.</summary>
83 public static ResolvedRef? Match(IReadOnlyList<GitRef> refs, string? refAndPath)
84 {
85 var segments = SplitSegments(refAndPath);
86 return segments is null ? null : Match(refs, segments);
87 }
88
89 private static ResolvedRef? Match(IReadOnlyList<GitRef> refs, string[] segments)
90 {
91 for (var take = segments.Length; take >= 1; take--)
92 {
93 var candidate = string.Join('/', segments, 0, take);
94 var found = Find(refs, candidate, RefKind.Branch) ?? Find(refs, candidate, RefKind.Tag);
95 if (found is null)
96 {
97 continue;
98 }
99
100 // Only refs that end at a commit are browsable; a tag of a blob or tree is not.
101 if (found.ObjectType != "commit" && found.PeeledSha is null)
102 {
103 continue;
104 }
105
106 return new ResolvedRef(
107 found.Name,
108 found.Kind == RefKind.Branch ? ResolvedKind.Branch : ResolvedKind.Tag,
109 found.TargetSha,
110 string.Join('/', segments, take, segments.Length - take));
111 }
112
113 return null;
114 }
115
116 private static GitRef? Find(IReadOnlyList<GitRef> refs, string name, RefKind kind)
117 {
118 foreach (var r in refs)
119 {
120 if (r.Kind == kind && string.Equals(r.Name, name, StringComparison.Ordinal))
121 {
122 return r;
123 }
124 }
125
126 return null;
127 }
128
129 /// <summary>Null when the input is empty or contains segments no tree path can have.</summary>
130 private static string[]? SplitSegments(string? refAndPath)
131 {
132 var trimmed = refAndPath?.Trim('/');
133 if (string.IsNullOrEmpty(trimmed))
134 {
135 return null;
136 }
137
138 var segments = trimmed.Split('/');
139 foreach (var segment in segments)
140 {
141 if (segment.Length == 0 || segment == "." || segment == ".." || segment.Contains('\0'))
142 {
143 return null;
144 }
145 }
146
147 return segments;
148 }
149 }
added forge/Git/RepoPaths.cs +41 −0View file
@@ -0,0 +1,41 @@
1 using System.Globalization;
2 using Microsoft.Extensions.Options;
3
4 namespace Forge.Git;
5
6 /// <summary>
7 /// The only place that builds a repository path. Paths are derived from the numeric ID,
8 /// so nothing a user typed ever ends up in a file system path.
9 /// </summary>
10 public sealed class RepoPaths(IOptions<ForgeOptions> options)
11 {
12 private readonly string _root = options.Value.ReposRoot;
13
14 public string Root => _root;
15
16 public string For(long repoId)
17 {
18 ArgumentOutOfRangeException.ThrowIfNegativeOrZero(repoId);
19 return Path.Combine(_root, repoId.ToString(CultureInfo.InvariantCulture) + ".git");
20 }
21
22 /// <summary>Deletes a repository directory. Git marks pack files read-only, which blocks deletion on Windows.</summary>
23 public static void DeleteDirectory(string path)
24 {
25 if (!Directory.Exists(path))
26 {
27 return;
28 }
29
30 foreach (var file in Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories))
31 {
32 var attributes = File.GetAttributes(file);
33 if ((attributes & FileAttributes.ReadOnly) != 0)
34 {
35 File.SetAttributes(file, attributes & ~FileAttributes.ReadOnly);
36 }
37 }
38
39 Directory.Delete(path, recursive: true);
40 }
41 }
added forge/Localization/Localizer.cs +153 −0View file
@@ -0,0 +1,153 @@
1 using System.Globalization;
2 using System.Reflection;
3 using System.Text.Json;
4 using Microsoft.AspNetCore.Components;
5
6 namespace Forge.Localization;
7
8 /// <summary>
9 /// All translations, loaded once from the JSON files embedded from the Localization folder.
10 /// English is the source language: its text is written in the code and doubles as the lookup key,
11 /// so there is no en.json. Adding a language means adding one file named after its code (de.json).
12 /// </summary>
13 public sealed class Translations
14 {
15 public const string DefaultLanguage = "en";
16
17 private const string ResourcePrefix = "Forge.Localization.";
18 private const string ResourceSuffix = ".json";
19
20 private readonly Dictionary<string, Dictionary<string, string[]>> _byLanguage = new(StringComparer.OrdinalIgnoreCase);
21
22 public Translations()
23 {
24 var assembly = typeof(Translations).Assembly;
25 foreach (var resource in assembly.GetManifestResourceNames())
26 {
27 if (!resource.StartsWith(ResourcePrefix, StringComparison.Ordinal)
28 || !resource.EndsWith(ResourceSuffix, StringComparison.Ordinal))
29 {
30 continue;
31 }
32
33 var language = resource[ResourcePrefix.Length..^ResourceSuffix.Length];
34 using var stream = assembly.GetManifestResourceStream(resource)!;
35 _byLanguage[language] = Load(stream, resource);
36 }
37
38 Languages = [DefaultLanguage, .. _byLanguage.Keys.Order(StringComparer.Ordinal)];
39 }
40
41 /// <summary>Language codes, English first.</summary>
42 public IReadOnlyList<string> Languages { get; }
43
44 /// <summary>The translated forms for a key, or null when the language has none (callers fall back to English).</summary>
45 public string[]? Find(string language, string key) =>
46 _byLanguage.TryGetValue(language, out var entries) && entries.TryGetValue(key, out var forms) ? forms : null;
47
48 public IReadOnlyCollection<string> KeysOf(string language) =>
49 _byLanguage.TryGetValue(language, out var entries) ? entries.Keys : [];
50
51 /// <summary>A value is either one string, or an array of plural forms.</summary>
52 private static Dictionary<string, string[]> Load(Stream stream, string resource)
53 {
54 using var document = JsonDocument.Parse(stream, new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip });
55 var entries = new Dictionary<string, string[]>(StringComparer.Ordinal);
56 foreach (var property in document.RootElement.EnumerateObject())
57 {
58 entries[property.Name] = property.Value.ValueKind switch
59 {
60 JsonValueKind.String => [property.Value.GetString()!],
61 JsonValueKind.Array => property.Value.EnumerateArray().Select(v => v.GetString()!).ToArray(),
62 _ => throw new InvalidDataException($"{resource}: the value of \"{property.Name}\" must be a string or an array of strings."),
63 };
64 }
65
66 return entries;
67 }
68 }
69
70 /// <summary>
71 /// Translates UI text into the language of the current request, which the request localization
72 /// middleware has stored in <see cref="CultureInfo.CurrentUICulture"/>. Injected into every component as T.
73 /// </summary>
74 public sealed class Localizer(Translations translations)
75 {
76 /// <summary>The supported language of the current request: "en", "sk", …</summary>
77 public string Language
78 {
79 get
80 {
81 for (var culture = CultureInfo.CurrentUICulture; culture.Name.Length > 0; culture = culture.Parent)
82 {
83 if (translations.Languages.Contains(culture.Name, StringComparer.OrdinalIgnoreCase))
84 {
85 return culture.Name;
86 }
87 }
88
89 return Translations.DefaultLanguage;
90 }
91 }
92
93 public IReadOnlyList<string> Languages => translations.Languages;
94
95 /// <summary>Translates English text. Untranslated text comes back unchanged.</summary>
96 public string this[string english] => translations.Find(Language, english)?[0] ?? english;
97
98 /// <summary>Translates an English template and fills its {0}, {1}… placeholders.</summary>
99 public string this[string english, params object?[] args] =>
100 string.Format(CultureInfo.CurrentCulture, this[english], args);
101
102 /// <summary>
103 /// Translates text that contains markup, such as &lt;code&gt;. Only for constant text:
104 /// nothing is encoded, so user data must never be put into it.
105 /// </summary>
106 public MarkupString Html(string english) => new(this[english]);
107
108 /// <summary>
109 /// Picks the plural form for <paramref name="count"/> and fills {0} with it. English has two forms;
110 /// a translation supplies as many as its language needs, as an array under the key "one|other".
111 /// </summary>
112 public string Plural(long count, string one, string other)
113 {
114 var language = Language;
115 var forms = translations.Find(language, one + "|" + other) ?? [one, other];
116 var index = Math.Min(PluralIndex(language, count), forms.Length - 1);
117 return string.Format(CultureInfo.CurrentCulture, forms[index], count);
118 }
119
120 /// <summary>"3 hours ago". The exact time belongs in a title attribute next to it.</summary>
121 public string RelativeTime(DateTimeOffset value, DateTimeOffset now)
122 {
123 var delta = now - value;
124 return delta switch
125 {
126 _ when delta.TotalSeconds < 45 => this["just now"],
127 _ when delta.TotalMinutes < 1.5 => this["a minute ago"],
128 _ when delta.TotalMinutes < 60 => this["{0} minutes ago", (int)Math.Round(delta.TotalMinutes)],
129 _ when delta.TotalHours < 1.5 => this["an hour ago"],
130 _ when delta.TotalHours < 24 => this["{0} hours ago", (int)Math.Round(delta.TotalHours)],
131 _ when delta.TotalDays < 2 => this["yesterday"],
132 _ when delta.TotalDays < 30 => this["{0} days ago", (int)Math.Floor(delta.TotalDays)],
133 _ when delta.TotalDays < 60 => this["a month ago"],
134 _ when delta.TotalDays < 365 => this["{0} months ago", (int)Math.Floor(delta.TotalDays / 30)],
135 _ when delta.TotalDays < 730 => this["a year ago"],
136 _ => this["{0} years ago", (int)Math.Floor(delta.TotalDays / 365)],
137 };
138 }
139
140 /// <summary>
141 /// Marks English text in code that is translated later, where it is displayed (validation messages
142 /// returned by services). It returns its argument; the marker lets the tests find every key.
143 /// </summary>
144 public static string Key(string english) => english;
145
146 /// <summary>Which plural form a count takes. Languages not listed use the English rule.</summary>
147 private static int PluralIndex(string language, long count) => language.ToLowerInvariant() switch
148 {
149 // One, few (2 to 4), many.
150 "sk" or "cs" => count == 1 ? 0 : count is >= 2 and <= 4 ? 1 : 2,
151 _ => count == 1 ? 0 : 1,
152 };
153 }
added forge/Localization/sk.json +407 −0View file
@@ -0,0 +1,407 @@
1 {
2 // Slovak. Keys are the English text exactly as written in the code.
3 // A value is a string, or for plurals an array: [one, few (2 to 4), many].
4
5 "New repository": "Nový repozitár",
6 "Sign out ({0})": "Odhlásiť sa ({0})",
7 "Sign in": "Prihlásiť sa",
8 "Language": "Jazyk",
9 "Skip to content": "Preskočiť na obsah",
10 "Search repositories": "Hľadať repozitáre",
11 "Switch theme": "Prepnúť tému",
12 "Account menu": "Menu účtu",
13 "Signed in as": "Prihlásený ako",
14 "Your repositories": "Tvoje repozitáre",
15 "self-hosted Git": "vlastný Git server",
16 "Keyboard shortcuts": "Klávesové skratky",
17 "Open the permalink of the file being viewed": "Otvoriť permalink zobrazeného súboru",
18 "Show this help": "Zobraziť túto nápovedu",
19 "Close": "Zavrieť",
20
21 "Not found": "Nenájdené",
22 "Error": "Chyba",
23 "This page does not exist": "Táto stránka neexistuje",
24 "The request could not be processed": "Požiadavku sa nepodarilo spracovať",
25 "Too many attempts": "Priveľa pokusov",
26 "Something went wrong": "Niečo sa pokazilo",
27 "The address is wrong, or you do not have access to this content.": "Adresa je nesprávna, alebo na obsah nemáš prístup.",
28 "The form may have expired. Reload the page and try again.": "Formulár mohol vypršať. Načítaj stránku znova a skús to ešte raz.",
29 "Wait a minute and try again.": "Počkaj minútu a skús to znova.",
30 "Try again in a moment.": "Skús to znova o chvíľu.",
31 "Back to the repository list": "Späť na zoznam repozitárov",
32
33 "just now": "práve teraz",
34 "a minute ago": "pred minútou",
35 "{0} minutes ago": "pred {0} minútami",
36 "an hour ago": "pred hodinou",
37 "{0} hours ago": "pred {0} hodinami",
38 "yesterday": "včera",
39 "{0} days ago": "pred {0} dňami",
40 "a month ago": "pred mesiacom",
41 "{0} months ago": "pred {0} mesiacmi",
42 "a year ago": "pred rokom",
43 "{0} years ago": "pred {0} rokmi",
44
45 "public": "verejný",
46 "private": "súkromný",
47 "Code": "Kód",
48 "Commits": "Commity",
49 "Branches": "Branche",
50 "Tags": "Tagy",
51 "Settings": "Nastavenia",
52 "Copy": "Kopírovať",
53 "Copied": "Skopírované",
54 "Clone URL": "Clone URL",
55 "branch": "branch",
56 "tag": "tag",
57 "commit": "commit",
58 "Path": "Cesta",
59 "(no message)": "(bez správy)",
60
61 "Repositories": "Repozitáre",
62 "There are no repositories here yet.": "Zatiaľ tu nie sú žiadne repozitáre.",
63 "Create your first repository": "Vytvor prvý repozitár",
64 "and push your code to it.": "a pushni doň svoj kód.",
65 "pushed": "push",
66 "empty": "prázdny",
67 "Joined": "Účet vytvorený",
68 "{0} repository|{0} repositories": ["{0} repozitár", "{0} repozitáre", "{0} repozitárov"],
69 "Find a repository": "Nájsť repozitár",
70 "Sort": "Zoradenie",
71 "Recently updated": "Naposledy zmenené",
72 "No repository matches “{0}”.": "Hľadaniu „{0}“ nezodpovedá žiadny repozitár.",
73 "Clear the search": "Zrušiť hľadanie",
74
75 "First run": "Prvé spustenie",
76 "Welcome to Forge": "Vitaj vo Forge",
77 "Create your account. This page then closes for good.": "Vytvor si účet. Táto stránka sa potom natrvalo zatvorí.",
78 "Username": "Používateľské meno",
79 "It becomes part of your repository addresses.": "Bude súčasťou adries tvojich repozitárov.",
80 "Display name": "Zobrazované meno",
81 "Password": "Heslo",
82 "Repeat password": "Heslo znova",
83 "Create account": "Vytvoriť účet",
84 "The passwords do not match.": "Heslá sa nezhodujú.",
85 "A username may contain letters, digits, hyphens and underscores (1 to 39 characters) and must start with a letter or digit.": "Meno môže obsahovať písmená, číslice, pomlčku a podčiarkovník (1 až 39 znakov) a musí začínať písmenom alebo číslicou.",
86 "This username is reserved.": "Toto meno je vyhradené.",
87 "The password must be at least {0} characters long.": "Heslo musí mať aspoň {0} znakov.",
88 "Wrong username or password.": "Nesprávne meno alebo heslo.",
89
90 "Access tokens": "Access tokeny",
91 "A token is the password for <code>git clone</code> and <code>git push</code> over HTTPS. Any username works.": "Token je heslo pre <code>git clone</code> a <code>git push</code> cez HTTPS. Ako meno môžeš zadať čokoľvek.",
92 "The token is created. Copy it now, it will not be shown again.": "Token je vytvorený. Skopíruj si ho teraz, znova sa už nezobrazí.",
93 "New token": "Nový token",
94 "Name": "Názov",
95 "e.g. laptop": "napr. notebook",
96 "Permission": "Oprávnenie",
97 "Read only (clone, fetch)": "Len čítanie (clone, fetch)",
98 "Read and write (push)": "Čítanie aj zápis (push)",
99 "Expires": "Platnosť",
100 "30 days": "30 dní",
101 "90 days": "90 dní",
102 "1 year": "1 rok",
103 "No expiry": "Bez expirácie",
104 "Create token": "Vytvoriť token",
105 "Existing tokens": "Existujúce tokeny",
106 "You have no tokens yet.": "Zatiaľ nemáš žiadny token.",
107 "Created": "Vytvorený",
108 "Last used": "Naposledy použitý",
109 "Valid until": "Platí do",
110 "read and write": "čítanie a zápis",
111 "read only": "len čítanie",
112 "never": "nikdy",
113 "expired {0}": "vypršal {0}",
114 "no expiry": "bez expirácie",
115 "Revoke": "Zrušiť",
116 "Enter a token name (at most 100 characters).": "Zadaj názov tokenu (najviac 100 znakov).",
117 "Choose an expiry from the list.": "Vyber platnosť zo zoznamu.",
118
119 "Letters, digits, dots, hyphens and underscores.": "Písmená, číslice, bodka, pomlčka a podčiarkovník.",
120 "Description": "Popis",
121 "(optional)": "(nepovinný)",
122 "Visibility": "Viditeľnosť",
123 "Private: only you can see it": "Súkromný: vidíš ho len ty",
124 "Public: anyone can read and clone it": "Verejný: ktokoľvek ho môže čítať a klonovať",
125 "Create repository": "Vytvoriť repozitár",
126 "The description can be at most 300 characters.": "Popis môže mať najviac 300 znakov.",
127 "A name may contain letters, digits, dots, hyphens and underscores (1 to 100 characters).": "Názov môže obsahovať písmená, číslice, bodku, pomlčku a podčiarkovník (1 až 100 znakov).",
128 "A name must not contain '..'.": "Názov nesmie obsahovať „..“.",
129 "A name must not end with '.git'.": "Názov nesmie končiť na „.git“.",
130 "A repository with this name already exists.": "Repozitár s týmto názvom už existuje.",
131 "The repository could not be created on disk. See the server log for details.": "Repozitár sa nepodarilo vytvoriť na disku. Podrobnosti sú v logu servera.",
132 "There is no such branch in the repository.": "Taký branch v repozitári nie je.",
133
134 "The repository is empty": "Repozitár je prázdny",
135 "Clone it and push the first commit:": "Naklonuj ho a pushni prvý commit:",
136 "Or push an existing repository:": "Alebo pushni existujúci repozitár:",
137 "Use an access token with write permission as the password.": "Ako heslo použi access token s právom zápisu.",
138 "Create a token": "Vytvoriť token",
139 "History": "História",
140 "Activity": "Aktivita",
141 "Activity on {0}": "Aktivita na {0}",
142 "Only the newest {0} commits are counted.": "Počíta sa len {0} najnovších commitov.",
143 "Contributors": "Prispievatelia",
144 "Commits in the last 30 days": "Commity za posledných 30 dní",
145 "First commit": "Prvý commit",
146 "Commits per week": "Commity za týždeň",
147 "The last 52 weeks, {0} in total": "Posledných 52 týždňov, spolu {0}",
148 "Week of {0}": "Týždeň od {0}",
149 "Only the first {0} contributors are shown.": "Zobrazuje sa len prvých {0} prispievateľov.",
150 "Search": "Hľadať",
151 "Search file names and code": "Hľadať v názvoch súborov a v kóde",
152 "Search this repository": "Hľadanie v repozitári",
153 "Type at least {0} characters. Upper and lower case do not matter.": "Napíš aspoň {0} znaky. Na veľkosti písmen nezáleží.",
154 "Nothing in {0} matches “{1}”.": "V {0} sa nenašlo nič pre „{1}“.",
155 "Results for “{0}” in {1}": "Výsledky pre „{0}“ v {1}",
156 "File names": "Názvy súborov",
157 "Only the first {0} files are shown.": "Zobrazuje sa len prvých {0} súborov.",
158 "There are more matches than shown. Make the search more specific.": "Zhôd je viac, než sa zobrazuje. Spresni hľadanie.",
159 "Clone": "Klonovať",
160 "Clone over HTTP": "Klonovanie cez HTTP",
161 "Use an access token as the password.": "Ako heslo použi access token.",
162 "Parent directory": "Nadradený priečinok",
163 "About": "O repozitári",
164 "No description.": "Bez popisu.",
165 "{0} branch|{0} branches": ["{0} branch", "{0} branche", "{0} branchov"],
166 "{0} tag|{0} tags": ["{0} tag", "{0} tagy", "{0} tagov"],
167 "Commit feed (Atom)": "Feed commitov (Atom)",
168 "Languages": "Jazyky",
169 "Other": "Ostatné",
170 "Submodule {0}": "Submodul {0}",
171
172 "{0} line|{0} lines": ["{0} riadok", "{0} riadky", "{0} riadkov"],
173 "Raw": "Raw",
174 "Preview": "Náhľad",
175 "Permalink": "Permalink",
176 "A link to this exact version of the file": "Odkaz na presne túto verziu súboru",
177 "Commits on {0}": "Commity zo dňa {0}",
178 "Copy the full SHA": "Kopírovať celé SHA",
179 "The file is {0} and too large to display.": "Súbor má {0} a je príliš veľký na zobrazenie.",
180 "Open raw": "Otvoriť raw",
181 "A binary file cannot be displayed.": "Binárny súbor sa nedá zobraziť.",
182 "Download": "Stiahnuť",
183 "The file is empty.": "Súbor je prázdny.",
184
185 "History of path": "História cesty",
186 "Full history": "Celá história",
187 "No more commits.": "Žiadne ďalšie commity.",
188 "← Newer": "← Novšie",
189 "Older →": "Staršie →",
190
191 "The diff is too large; only part of it is shown.": "Diff je príliš veľký, zobrazuje sa len jeho časť.",
192 "added": "pridaný",
193 "deleted": "zmazaný",
194 "renamed": "premenovaný",
195 "copied": "skopírovaný",
196 "modified": "zmenený",
197 "Binary file, diff not shown.": "Binárny súbor, diff sa nezobrazuje.",
198 "The diff is too large (more than {0} lines).": "Diff je príliš veľký (viac ako {0} riadkov).",
199 "No content changes.": "Bez zmien v obsahu.",
200 "No content changes (empty file or mode change).": "Žiadne zmeny v obsahu (prázdny súbor alebo zmena práv).",
201 "No newline at end of file": "Bez znaku nového riadka na konci súboru",
202
203 "Author": "Autor",
204 "Committer": "Commiter",
205 "Commit": "Commit",
206 "Parent": "Rodič",
207 "Parents": "Rodičia",
208 "none (first commit)": "žiadny (prvý commit)",
209 "Browse files at this commit": "Prehliadať súbory v tomto commite",
210 "{0} changed file|{0} changed files": ["{0} zmenený súbor", "{0} zmenené súbory", "{0} zmenených súborov"],
211 "Merge commit: changes are shown against the first parent.": "Merge commit: zmeny sú oproti prvému rodičovi.",
212 "bin": "bin",
213
214 "This repository has no branches yet.": "Repozitár zatiaľ nemá žiadny branch.",
215 "Branch": "Branch",
216 "Last commit": "Posledný commit",
217 "Compared to {0}": "Oproti {0}",
218 "Commits ahead of and behind the default branch": "Commity navyše a chýbajúce oproti default branchu",
219 "default": "default",
220 "{0} ahead, {1} behind": "{0} commitov navyše, {1} chýba",
221
222 "This repository has no tags yet.": "Repozitár zatiaľ nemá žiadny tag.",
223 "Tag": "Tag",
224 "Message": "Správa",
225
226 "Compare": "Porovnanie",
227 "Merge into": "Zlúčiť do",
228 "from": "z",
229 "Show comparison": "Porovnať",
230 "Choose two branches to compare.": "Vyber dva branche na porovnanie.",
231 "These are the same commit. There is nothing to compare.": "Je to ten istý commit. Nie je čo porovnávať.",
232 "{0} commit|{0} commits": ["{0} commit", "{0} commity", "{0} commitov"],
233 "Merge {0} into {1}": "Zlúčiť {0} do {1}",
234 "{0} is already part of {1}. There is nothing to merge.": "{0} je už súčasťou {1}. Nie je čo zlučovať.",
235 "These branches can be merged automatically.": "Tieto branche sa dajú zlúčiť automaticky.",
236 "These branches have conflicts.": "Tieto branche majú konflikty.",
237 "Resolve conflicts": "Vyriešiť konflikty",
238 "Rebase onto the base branch": "Rebase na základný branch",
239 "The branch has too many commits to rebase here.": "Branch má priveľa commitov na rebase tu.",
240 "The branch contains merge commits and cannot be rebased here.": "Branch obsahuje merge commity a tu sa rebasovať nedá.",
241 "Show changes since the branches diverged": "Zobraziť zmeny od rozídenia branchov",
242 "Show the direct difference between both ends": "Zobraziť priamy rozdiel medzi oboma koncami",
243
244 "Unified": "Zjednotený",
245 "Side by side": "Vedľa seba",
246 "Show whitespace changes": "Zobraziť zmeny bielych znakov",
247 "Hide whitespace changes": "Skryť zmeny bielych znakov",
248 "View file": "Zobraziť súbor",
249
250 "Apply to branch": "Aplikovať na branch",
251 "Revert": "Revert",
252 "Cherry-pick": "Cherry-pick",
253 "Merge commits and the first commit cannot be reverted or cherry-picked here.": "Merge commity a prvý commit sa tu nedajú revertnúť ani cherry-picknúť.",
254 "The change conflicts with the branch and cannot be applied automatically.": "Zmena je v konflikte s branchom a nedá sa aplikovať automaticky.",
255 "The branch already contains this change. There is nothing to do.": "Branch túto zmenu už obsahuje. Nie je čo robiť.",
256
257 "Resolve conflicts: {0} into {1}": "Riešenie konfliktov: {0} do {1}",
258 "These branches have no conflicts.": "Tieto branche nemajú konflikty.",
259 "Back to the comparison": "Späť na porovnanie",
260 "Choose a version for every file, or edit the text and remove the conflict markers. Saving creates the merge commit.": "Pre každý súbor vyber verziu, alebo uprav text a odstráň značky konfliktu. Uložením vznikne merge commit.",
261 "Keep the version from {0}": "Ponechať verziu z {0}",
262 "Take the version from {0}": "Prevziať verziu z {0}",
263 "Delete the file (as on {0})": "Zmazať súbor (ako na {0})",
264 "Use the text below": "Použiť text nižšie",
265 "This file is binary or too large to edit here.": "Súbor je binárny alebo príliš veľký na úpravu tu.",
266 "Resolve and merge": "Vyriešiť a zlúčiť",
267 "Choose a resolution for every conflicting file.": "Vyber riešenie pre každý súbor s konfliktom.",
268 "The edited text still contains conflict markers.": "Upravený text stále obsahuje značky konfliktu.",
269
270 "Pull requests": "Pull requesty",
271 "Open ({0})": "Otvorené ({0})",
272 "Closed ({0})": "Zatvorené ({0})",
273 "New pull request": "Nový pull request",
274 "There are no open pull requests.": "Nie sú žiadne otvorené pull requesty.",
275 "There are no closed pull requests.": "Nie sú žiadne zatvorené pull requesty.",
276 "open": "otvorený",
277 "merged": "zlúčený",
278 "closed": "zatvorený",
279 "There is an open pull request for these branches:": "Pre tieto branche je otvorený pull request:",
280 "Open a pull request": "Otvoriť pull request",
281 "Open pull request": "Otvoriť pull request",
282 "Title": "Názov",
283 "(optional, Markdown)": "(nepovinný, Markdown)",
284 "Enter a title (at most 200 characters).": "Zadaj názov (najviac 200 znakov).",
285 "The text is too long.": "Text je príliš dlhý.",
286 "An open pull request for these branches already exists.": "Pre tieto branche už existuje otvorený pull request.",
287 "This pull request can no longer be merged.": "Tento pull request sa už nedá zlúčiť.",
288 "A branch of this pull request no longer exists, so it cannot be reopened.": "Branch tohto pull requestu už neexistuje, preto sa nedá znova otvoriť.",
289 "A branch of this pull request no longer exists.": "Branch tohto pull requestu už neexistuje.",
290 "Merged into {0}.": "Zlúčené do {0}.",
291 "Edit title and description": "Upraviť názov a popis",
292 "Close pull request": "Zatvoriť pull request",
293 "Reopen pull request": "Znova otvoriť pull request",
294 "{0} comment|{0} comments": ["{0} komentár", "{0} komentáre", "{0} komentárov"],
295 "Add a comment": "Pridať komentár",
296 "(Markdown)": "(Markdown)",
297 "Comment": "Komentovať",
298 "Write a comment first.": "Najprv napíš komentár.",
299
300 "Protected branches": "Chránené branche",
301 "A protected branch cannot be force-pushed or deleted, from git or from the web. Merging into it still works.": "Chránený branch sa nedá force-pushnúť ani zmazať, z gitu ani z webu. Merge doň funguje ďalej.",
302 "No branch is protected yet.": "Zatiaľ nie je chránený žiadny branch.",
303 "Direct pushes": "Priame pushe",
304 "refused, changes only through merges on the web": "odmietnuté, zmeny len cez merge na webe",
305 "allowed": "povolené",
306 "Remove protection": "Zrušiť ochranu",
307 "Protect a branch": "Chrániť branch",
308 "A branch name, or a prefix ending in <code>/*</code> such as <code>release/*</code>.": "Názov branchu, alebo prefix končiaci na <code>/*</code>, napríklad <code>release/*</code>.",
309 "Also refuse direct pushes (changes only through merges on the web)": "Odmietať aj priame pushe (zmeny len cez merge na webe)",
310 "Protect": "Chrániť",
311 "This branch is already protected.": "Tento branch je už chránený.",
312 "This branch is protected and cannot be deleted.": "Tento branch je chránený a nedá sa zmazať.",
313 "Conflicting files:": "Súbory s konfliktom:",
314 "Method": "Spôsob",
315 "Merge commit": "Merge commit",
316 "Squash into one commit": "Squash do jedného commitu",
317 "Fast-forward": "Fast-forward",
318 "Commit message": "Správa commitu",
319 "(optional, a default is used if empty)": "(nepovinná, inak sa použije predvolená)",
320 "Delete branch {0} after merging": "Po zlúčení zmazať branch {0}",
321 "Merge": "Zlúčiť",
322 "Choose two different branches.": "Vyber dva rôzne branche.",
323 "There is nothing to merge.": "Nie je čo zlučovať.",
324 "The branches have no common history and cannot be merged here.": "Branche nemajú spoločnú históriu a tu sa zlúčiť nedajú.",
325 "Fast-forward is not possible because the branches have diverged.": "Fast-forward nie je možný, lebo branche sa rozišli.",
326 "The branches have conflicts and cannot be merged automatically.": "Branche majú konflikty a nedajú sa zlúčiť automaticky.",
327 "The branch changed in the meantime. Reload the page and try again.": "Branch sa medzitým zmenil. Načítaj stránku znova a skús to ešte raz.",
328
329 "Delete": "Zmazať",
330 "New branch": "Nový branch",
331 "From": "Z",
332 "(branch, tag or commit SHA)": "(branch, tag alebo SHA commitu)",
333 "Create branch": "Vytvoriť branch",
334 "Branch {0} was created.": "Branch {0} bol vytvorený.",
335 "Branch {0} was deleted (it pointed at {1}).": "Branch {0} bol zmazaný (ukazoval na {1}).",
336 "This is not a valid branch name.": "Toto nie je platný názov branchu.",
337 "A branch with this name already exists.": "Branch s týmto názvom už existuje.",
338 "The default branch cannot be deleted. Choose another default branch first.": "Default branch sa nedá zmazať. Najprv nastav iný default branch.",
339 "The starting point does not exist.": "Východiskový bod neexistuje.",
340 "New tag": "Nový tag",
341 "Create tag": "Vytvoriť tag",
342 "Tag {0} was created.": "Tag {0} bol vytvorený.",
343 "Tag {0} was deleted (it pointed at {1}).": "Tag {0} bol zmazaný (ukazoval na {1}).",
344 "This is not a valid tag name.": "Toto nie je platný názov tagu.",
345 "A tag with this name already exists.": "Tag s týmto názvom už existuje.",
346 "There is no such tag in the repository.": "Taký tag v repozitári nie je.",
347 "There are no new commits between these two commits.": "Medzi týmito commitmi nie sú žiadne nové commity.",
348 "Showing the first {0} commits.": "Zobrazuje sa prvých {0} commitov.",
349
350 "General": "Všeobecné",
351 "Webhooks": "Webhooky",
352 "Description and visibility": "Popis a viditeľnosť",
353 "Private": "Súkromný",
354 "Public": "Verejný",
355 "Save": "Uložiť",
356 "Default branch": "Default branch",
357 "The branch that is shown first and that <code>git clone</code> checks out": "Branch, ktorý sa zobrazí ako prvý a ktorý dostane <code>git clone</code>",
358 "Set": "Nastaviť",
359 "Rename repository": "Premenovanie",
360 "Rename": "Premenovať",
361 "The repository address changes. Old clone URLs stop working.": "Zmení sa adresa repozitára. Staré clone URL prestanú fungovať.",
362 "New name": "Nový názov",
363 "Delete this repository": "Zmazanie repozitára",
364 "Delete repository": "Zmazať repozitár",
365 "This deletes the code, the history and the webhooks. It cannot be undone.": "Zmaže sa kód, história aj webhooky. Nedá sa to vrátiť.",
366 "To confirm, type the repository name:": "Na potvrdenie napíš názov repozitára:",
367 "Saved.": "Uložené.",
368 "The default branch is set.": "Default branch je nastavený.",
369 "The name does not match. The repository was not deleted.": "Názov sa nezhoduje. Repozitár ostal nezmazaný.",
370
371 "After every push Forge sends signed JSON to the given address. Useful for triggering an external CI.": "Po každom pushi pošle Forge na zadanú adresu podpísaný JSON. Hodí sa na spustenie externého CI.",
372 "This repository has no webhooks yet.": "Tento repozitár zatiaľ nemá žiadny webhook.",
373 "URL": "URL",
374 "Status": "Stav",
375 "Last delivery": "Posledné doručenie",
376 "active": "aktívny",
377 "disabled": "vypnutý",
378 "none yet": "zatiaľ žiadne",
379 "Add webhook": "Pridať webhook",
380 "Secret": "Tajomstvo",
381 "(optional, generated if empty)": "(nepovinné, inak sa vygeneruje)",
382 "Used to sign <code>X-Forge-Signature</code> (HMAC-SHA256 of the request body).": "Slúži na podpis <code>X-Forge-Signature</code> (HMAC-SHA256 tela požiadavky).",
383 "Enter a full address starting with http:// or https://.": "Zadaj celú adresu začínajúcu na http:// alebo https://.",
384 "in progress": "prebieha",
385 "failed": "zlyhalo",
386
387 "Webhook": "Webhook",
388 "Event": "Udalosť",
389 "Send test ping": "Poslať testovací ping",
390 "Disable": "Vypnúť",
391 "Enable": "Zapnúť",
392 "Delete webhook": "Zmazať webhook",
393 "Delivery history": "História doručení",
394 "No deliveries yet. Push to the repository or send a test ping.": "Zatiaľ žiadne doručenie. Pushni do repozitára alebo pošli testovací ping.",
395 "Result": "Výsledok",
396 "Attempt": "Pokus",
397 "Duration": "Trvanie",
398 "When": "Kedy",
399 "Redeliver": "Redeliver",
400 "The ping was delivered.": "Ping bol doručený.",
401 "The ping could not be delivered. See the history below for details.": "Ping sa nepodarilo doručiť. Podrobnosti sú v histórii nižšie.",
402 "The webhook is enabled.": "Webhook je zapnutý.",
403 "The webhook is disabled.": "Webhook je vypnutý.",
404 "This delivery cannot be repeated.": "Toto doručenie sa nedá zopakovať.",
405 "Delivered again.": "Doručené znova.",
406 "Redelivery failed. See the history below for details.": "Opakované doručenie zlyhalo. Podrobnosti sú v histórii nižšie."
407 }
added forge/Program.cs +17 −0View file
@@ -0,0 +1,17 @@
1 using Forge;
2
3 var app = ForgeApp.Build(args);
4
5 try
6 {
7 await ForgeApp.InitializeAsync(app);
8 }
9 catch (ForgeStartupException ex)
10 {
11 // No stack trace: this is a message for whoever is starting the app.
12 Console.Error.WriteLine("Forge cannot start: " + ex.Message);
13 return 1;
14 }
15
16 await app.RunAsync();
17 return 0;
added forge/Properties/launchSettings.json +23 −0View file
@@ -0,0 +1,23 @@
1 {
2 "$schema": "https://json.schemastore.org/launchsettings.json",
3 "profiles": {
4 "http": {
5 "commandName": "Project",
6 "dotnetRunMessages": true,
7 "launchBrowser": true,
8 "applicationUrl": "http://localhost:5207",
9 "environmentVariables": {
10 "ASPNETCORE_ENVIRONMENT": "Development"
11 }
12 },
13 "https": {
14 "commandName": "Project",
15 "dotnetRunMessages": true,
16 "launchBrowser": true,
17 "applicationUrl": "https://localhost:7273;http://localhost:5207",
18 "environmentVariables": {
19 "ASPNETCORE_ENVIRONMENT": "Development"
20 }
21 }
22 }
23 }
added forge/Urls.cs +51 −0View file
@@ -0,0 +1,51 @@
1 using Forge.Data;
2
3 namespace Forge;
4
5 /// <summary>Builds site-relative URLs. Every dynamic part is escaped segment by segment.</summary>
6 public static class Urls
7 {
8 public static string EncodePath(string path) =>
9 string.Join('/', path.Split('/').Select(Uri.EscapeDataString));
10
11 public static string User(string username) => "/" + Uri.EscapeDataString(username);
12
13 public static string Repo(string owner, string name) =>
14 $"/{Uri.EscapeDataString(owner)}/{Uri.EscapeDataString(name)}";
15
16 public static string Repo(Repository repo) => Repo(repo.Owner.Username, repo.Name);
17
18 public static string Tree(Repository repo, string refName, string path = "") => WithRef(repo, "tree", refName, path);
19 public static string Blob(Repository repo, string refName, string path) => WithRef(repo, "blob", refName, path);
20 public static string Raw(Repository repo, string refName, string path) => WithRef(repo, "raw", refName, path);
21 public static string Commits(Repository repo, string refName, string path = "") => WithRef(repo, "commits", refName, path);
22
23 public static string Commit(Repository repo, string sha) => $"{Repo(repo)}/commit/{sha}";
24 public static string Compare(Repository repo) => Repo(repo) + "/compare";
25
26 /// <summary>Each side is a branch, a tag or a commit SHA. Ref names cannot contain "..", so "..." splits them unambiguously.</summary>
27 public static string Compare(Repository repo, string before, string after) =>
28 $"{Repo(repo)}/compare/{EncodePath(before)}...{EncodePath(after)}";
29 public static string Conflicts(Repository repo, string baseBranch, string headBranch) =>
30 $"{Repo(repo)}/conflicts/{EncodePath(baseBranch)}...{EncodePath(headBranch)}";
31
32 public static string Search(Repository repo) => Repo(repo) + "/search";
33 public static string Activity(Repository repo) => Repo(repo) + "/activity";
34 public static string Pulls(Repository repo) => Repo(repo) + "/pulls";
35 public static string Pull(Repository repo, int number) => $"{Repo(repo)}/pull/{number}";
36 public static string Branches(Repository repo) => Repo(repo) + "/branches";
37 public static string Tags(Repository repo) => Repo(repo) + "/tags";
38 public static string Atom(Repository repo) => Repo(repo) + "/atom";
39 public static string Settings(Repository repo) => Repo(repo) + "/settings";
40 public static string Webhooks(Repository repo) => Repo(repo) + "/settings/webhooks";
41 public static string Protection(Repository repo) => Repo(repo) + "/settings/branches";
42 public static string Webhook(Repository repo, long id) => $"{Repo(repo)}/settings/webhooks/{id}";
43
44 public static string Clone(ForgeOptions options, Repository repo) =>
45 $"{options.BaseUrlTrimmed}{Repo(repo)}.git";
46
47 public static string Absolute(ForgeOptions options, string relative) => options.BaseUrlTrimmed + relative;
48
49 private static string WithRef(Repository repo, string kind, string refName, string path) =>
50 $"{Repo(repo)}/{kind}/{EncodePath(refName)}" + (path.Length == 0 ? "" : "/" + EncodePath(path));
51 }
added forge/_Imports.razor +21 −0View file
@@ -0,0 +1,21 @@
1 @using System.Globalization
2 @using Microsoft.AspNetCore.Authorization
3 @using Microsoft.AspNetCore.Components.Forms
4 @using Microsoft.AspNetCore.Components.Routing
5 @using Microsoft.AspNetCore.Components.Web
6 @using Microsoft.AspNetCore.RateLimiting
7 @using Microsoft.EntityFrameworkCore
8 @using Microsoft.Extensions.Options
9 @using Forge
10 @using Forge.Components
11 @using Forge.Data
12 @using Forge.Features.Auth
13 @using Forge.Features.Browse
14 @using Forge.Features.History
15 @using Forge.Features.Pulls
16 @using Forge.Features.Repos
17 @using Forge.Features.Webhooks
18 @using Forge.Git
19 @using Forge.Localization
20 @* Every component gets the translator T; see Localization/Localizer.cs. *@
21 @inject Localizer T
added forge/appsettings.Development.json +8 −0View file
@@ -0,0 +1,8 @@
1 {
2 "Logging": {
3 "LogLevel": {
4 "Default": "Information",
5 "Microsoft.AspNetCore": "Warning"
6 }
7 }
8 }
added forge/appsettings.json +16 −0View file
@@ -0,0 +1,16 @@
1 {
2 "Logging": {
3 "LogLevel": {
4 "Default": "Information",
5 "Microsoft.AspNetCore": "Warning",
6 "Microsoft.EntityFrameworkCore": "Warning"
7 }
8 },
9 "AllowedHosts": "*",
10 "Forge": {
11 "DataPath": "data",
12 "BaseUrl": "http://localhost:5207",
13 "MaxPushSizeMb": 500,
14 "GitPath": "git"
15 }
16 }
added forge/forge.csproj +33 −0View file
@@ -0,0 +1,33 @@
1 <Project Sdk="Microsoft.NET.Sdk.Web">
2
3 <PropertyGroup>
4 <TargetFramework>net11.0</TargetFramework>
5 <Nullable>enable</Nullable>
6 <ImplicitUsings>enable</ImplicitUsings>
7 <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
8 <!-- NuGet audit advisories should not break the build. -->
9 <WarningsNotAsErrors>NU1901;NU1902;NU1903;NU1904</WarningsNotAsErrors>
10 <RootNamespace>Forge</RootNamespace>
11 <AssemblyName>forge</AssemblyName>
12 <BlazorDisableThrowNavigationException>true</BlazorDisableThrowNavigationException>
13 </PropertyGroup>
14
15 <ItemGroup>
16 <!-- One translation file per language. WithCulture=false keeps them in the main assembly
17 instead of being split off into satellite assemblies because of their culture-like names. -->
18 <Content Remove="Localization\*.json" />
19 <EmbeddedResource Include="Localization\*.json" WithCulture="false" LogicalName="Forge.Localization.%(Filename)%(Extension)" />
20 </ItemGroup>
21
22 <ItemGroup>
23 <PackageReference Include="CliWrap" Version="3.10.5" />
24 <PackageReference Include="HtmlSanitizer" Version="11.0.26" />
25 <PackageReference Include="Markdig" Version="1.6.0" />
26 <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="11.0.0" />
27 <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="11.0.0">
28 <PrivateAssets>all</PrivateAssets>
29 <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
30 </PackageReference>
31 </ItemGroup>
32
33 </Project>
added forge/wwwroot/app.js +278 −0View file
@@ -0,0 +1,278 @@
1 // Forge has no client-side framework. Pages work without this file; it adds what plain HTML cannot do.
2
3 // 1. Copy buttons: <button data-copy="text to copy" data-copied-label="Copied">.
4 // A button with a <span class="copy-label"> keeps its icon and changes only the label.
5 // data-copy-from="element-id" copies that element's text instead (a whole file).
6 document.addEventListener('click', (event) => {
7 const button = event.target.closest('[data-copy], [data-copy-from]');
8 if (!button || !navigator.clipboard) {
9 return;
10 }
11
12 const source = button.dataset.copyFrom ? document.getElementById(button.dataset.copyFrom) : null;
13 const text = source ? source.textContent : button.dataset.copy;
14 if (text === undefined) {
15 return;
16 }
17
18 navigator.clipboard.writeText(text).then(() => {
19 // An icon-only button has no text to change; the "copied" class alone gives the feedback.
20 const label = button.querySelector('.copy-label') || (button.children.length === 0 ? button : null);
21 const original = label ? label.textContent : null;
22 if (label && button.dataset.copiedLabel) {
23 label.textContent = button.dataset.copiedLabel;
24 }
25
26 button.classList.add('copied');
27 setTimeout(() => {
28 button.classList.remove('copied');
29 if (label && original !== null) {
30 label.textContent = original;
31 }
32 }, 1500);
33 });
34 });
35
36 // 2. Theme switch: system → light → dark → system. theme.js applies the saved choice before paint.
37 function applyHighlightTheme() {
38 // highlight.js ships one stylesheet per theme, chosen by a media query. A manual choice overrides it.
39 const theme = document.documentElement.dataset.theme;
40 document.querySelectorAll('link[data-hl-theme]').forEach((link) => {
41 link.media = theme ? (link.dataset.hlTheme === theme ? 'all' : 'not all') : `(prefers-color-scheme: ${link.dataset.hlTheme})`;
42 });
43 }
44
45 document.addEventListener('click', (event) => {
46 if (!event.target.closest('[data-theme-toggle]')) {
47 return;
48 }
49
50 const root = document.documentElement;
51 const next = { undefined: 'light', light: 'dark', dark: undefined }[root.dataset.theme];
52 if (next) {
53 root.dataset.theme = next;
54 } else {
55 delete root.dataset.theme;
56 }
57
58 try {
59 if (next) {
60 localStorage.setItem('forge-theme', next);
61 } else {
62 localStorage.removeItem('forge-theme');
63 }
64 } catch (e) {
65 // Storage can be blocked; the choice then lasts for this page only.
66 }
67
68 applyHighlightTheme();
69 });
70 applyHighlightTheme();
71
72 // 3. Dropdowns are <details>. Close them on a click elsewhere and on Escape.
73 const dropdowns = 'details.menu[open], details.ref-switcher[open]';
74 document.addEventListener('click', (event) => {
75 document.querySelectorAll(dropdowns).forEach((menu) => {
76 if (!menu.contains(event.target)) {
77 menu.open = false;
78 }
79 });
80 });
81 document.addEventListener('keydown', (event) => {
82 if (event.key !== 'Escape') {
83 return;
84 }
85
86 document.querySelectorAll(dropdowns).forEach((menu) => {
87 menu.open = false;
88 menu.querySelector('summary').focus();
89 });
90 });
91
92 // 4. Keyboard shortcuts: an element with data-hotkey="/" is focused (fields) or followed (links)
93 // when that key is pressed outside a text field.
94 document.addEventListener('keydown', (event) => {
95 if (event.ctrlKey || event.metaKey || event.altKey || event.defaultPrevented) {
96 return;
97 }
98
99 const typing = event.target.closest('input, textarea, select, [contenteditable]');
100 if (typing) {
101 return;
102 }
103
104 if (event.key === '?') {
105 const help = document.getElementById('shortcuts');
106 if (help && !help.open) {
107 event.preventDefault();
108 help.showModal();
109 }
110
111 return;
112 }
113
114 const target = Array.from(document.querySelectorAll('[data-hotkey]')).find((el) => el.dataset.hotkey === event.key);
115 if (!target) {
116 return;
117 }
118
119 event.preventDefault();
120 if (target.matches('input, textarea')) {
121 target.focus();
122 target.select();
123 } else {
124 target.click();
125 }
126 });
127
128 // <button data-open-dialog="id"> opens a <dialog>; a click on its backdrop closes it.
129 document.addEventListener('click', (event) => {
130 const opener = event.target.closest('[data-open-dialog]');
131 if (opener) {
132 const dialog = document.getElementById(opener.dataset.openDialog);
133 if (dialog && !dialog.open) {
134 dialog.showModal();
135 }
136 } else if (event.target instanceof HTMLDialogElement) {
137 event.target.close();
138 }
139 });
140
141 // 5. Syntax highlighting. highlight.js is only present on pages that show code.
142 if (window.hljs) {
143 document.querySelectorAll('code[data-highlight]').forEach((block) => {
144 if (window.hljs.getLanguage(block.dataset.highlight)) {
145 window.hljs.highlightElement(block);
146 }
147 });
148 }
149
150 // 6. Line selection in the file view. The address ends in #L12 or #L12-L20; click a line number to
151 // select it, shift-click another to select the range between them.
152 const codeView = document.querySelector('.code-view');
153 if (codeView) {
154 const bar = document.createElement('div');
155 bar.className = 'line-highlight';
156 bar.hidden = true;
157 codeView.prepend(bar);
158 let anchorLine = null;
159
160 const selectedRange = () => {
161 const match = /^#L(\d+)(?:-L?(\d+))?$/.exec(location.hash);
162 if (!match) {
163 return null;
164 }
165
166 const a = Number(match[1]);
167 const b = match[2] ? Number(match[2]) : a;
168 return { from: Math.min(a, b), to: Math.max(a, b) };
169 };
170
171 const showSelection = (scroll) => {
172 codeView.querySelectorAll('.line-numbers a.selected').forEach((a) => a.classList.remove('selected'));
173 const range = selectedRange();
174 const first = range && document.getElementById('L' + range.from);
175 const last = range && document.getElementById('L' + range.to);
176 if (!first || !last) {
177 bar.hidden = true;
178 return;
179 }
180
181 for (let n = range.from; n <= range.to; n++) {
182 document.getElementById('L' + n).classList.add('selected');
183 }
184
185 // Positions set through the CSSOM are allowed by the CSP; only style attributes in markup are not.
186 bar.style.top = first.offsetTop + 'px';
187 bar.style.height = (last.offsetTop + last.offsetHeight - first.offsetTop) + 'px';
188 bar.style.width = codeView.scrollWidth + 'px';
189 bar.hidden = false;
190 if (scroll) {
191 first.scrollIntoView({ block: 'center' });
192 }
193 };
194
195 codeView.addEventListener('click', (event) => {
196 const link = event.target.closest('.line-numbers a');
197 if (!link) {
198 return;
199 }
200
201 event.preventDefault();
202 const line = Number(link.id.slice(1));
203 let hash = '#L' + line;
204 if (event.shiftKey && anchorLine !== null && anchorLine !== line) {
205 hash = '#L' + Math.min(anchorLine, line) + '-L' + Math.max(anchorLine, line);
206 } else {
207 anchorLine = line;
208 }
209
210 history.replaceState(null, '', hash);
211 showSelection(false);
212 });
213
214 window.addEventListener('hashchange', () => showSelection(true));
215 const initial = selectedRange();
216 if (initial) {
217 anchorLine = initial.from;
218 showSelection(true);
219 }
220 }
221
222 // 7. Syntax colours in diffs. Each line is highlighted on its own, one file at a time as it
223 // scrolls into view, so a large diff does not freeze the page.
224 function markRange(root, start, end) {
225 // Re-applies the "this part of the line changed" span after highlighting rebuilt the line.
226 const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
227 const nodes = [];
228 while (walker.nextNode()) {
229 nodes.push(walker.currentNode);
230 }
231
232 let offset = 0;
233 for (const node of nodes) {
234 const length = node.data.length;
235 const from = Math.max(start, offset) - offset;
236 const to = Math.min(end, offset + length) - offset;
237 offset += length;
238 if (from >= to) {
239 continue;
240 }
241
242 const middle = from > 0 ? node.splitText(from) : node;
243 if (to - from < middle.data.length) {
244 middle.splitText(to - from);
245 }
246
247 const mark = document.createElement('span');
248 mark.className = 'chg';
249 middle.replaceWith(mark);
250 mark.appendChild(middle);
251 }
252 }
253
254 function highlightDiffFile(file) {
255 file.querySelectorAll('.line[data-lang]').forEach((line) => {
256 const language = line.dataset.lang;
257 if (!window.hljs.getLanguage(language)) {
258 return;
259 }
260
261 line.innerHTML = window.hljs.highlight(line.textContent, { language, ignoreIllegals: true }).value;
262 if (line.dataset.cs !== undefined) {
263 markRange(line, Number(line.dataset.cs), Number(line.dataset.ce));
264 }
265 });
266 }
267
268 if (window.hljs && 'IntersectionObserver' in window) {
269 const observer = new IntersectionObserver((entries) => {
270 for (const entry of entries) {
271 if (entry.isIntersecting) {
272 observer.unobserve(entry.target);
273 highlightDiffFile(entry.target);
274 }
275 }
276 }, { rootMargin: '400px' });
277 document.querySelectorAll('.diff-file').forEach((file) => observer.observe(file));
278 }
added forge/wwwroot/favicon.png +0 −0View file

Binary file, diff not shown.

added forge/wwwroot/lib/highlight/github-dark.min.css +10 −0View file
@@ -0,0 +1,10 @@
1 pre code.hljs{display:block;overflow-x:auto;padding:1em}code.hljs{padding:3px 5px}/*!
2 Theme: GitHub Dark
3 Description: Dark theme as seen on github.com
4 Author: github.com
5 Maintainer: @Hirse
6 Updated: 2021-05-15
7
8 Outdated base version: https://github.com/primer/github-syntax-dark
9 Current colors taken from GitHub's CSS
10 */.hljs{color:#c9d1d9;background:#0d1117}.hljs-doctag,.hljs-keyword,.hljs-meta .hljs-keyword,.hljs-template-tag,.hljs-template-variable,.hljs-type,.hljs-variable.language_{color:#ff7b72}.hljs-title,.hljs-title.class_,.hljs-title.class_.inherited__,.hljs-title.function_{color:#d2a8ff}.hljs-attr,.hljs-attribute,.hljs-literal,.hljs-meta,.hljs-number,.hljs-operator,.hljs-selector-attr,.hljs-selector-class,.hljs-selector-id,.hljs-variable{color:#79c0ff}.hljs-meta .hljs-string,.hljs-regexp,.hljs-string{color:#a5d6ff}.hljs-built_in,.hljs-symbol{color:#ffa657}.hljs-code,.hljs-comment,.hljs-formula{color:#8b949e}.hljs-name,.hljs-quote,.hljs-selector-pseudo,.hljs-selector-tag{color:#7ee787}.hljs-subst{color:#c9d1d9}.hljs-section{color:#1f6feb;font-weight:700}.hljs-bullet{color:#f2cc60}.hljs-emphasis{color:#c9d1d9;font-style:italic}.hljs-strong{color:#c9d1d9;font-weight:700}.hljs-addition{color:#aff5b4;background-color:#033a16}.hljs-deletion{color:#ffdcd7;background-color:#67060c}
added forge/wwwroot/lib/highlight/github.min.css +10 −0View file
@@ -0,0 +1,10 @@
1 pre code.hljs{display:block;overflow-x:auto;padding:1em}code.hljs{padding:3px 5px}/*!
2 Theme: GitHub
3 Description: Light theme as seen on github.com
4 Author: github.com
5 Maintainer: @Hirse
6 Updated: 2021-05-15
7
8 Outdated base version: https://github.com/primer/github-syntax-light
9 Current colors taken from GitHub's CSS
10 */.hljs{color:#24292e;background:#fff}.hljs-doctag,.hljs-keyword,.hljs-meta .hljs-keyword,.hljs-template-tag,.hljs-template-variable,.hljs-type,.hljs-variable.language_{color:#d73a49}.hljs-title,.hljs-title.class_,.hljs-title.class_.inherited__,.hljs-title.function_{color:#6f42c1}.hljs-attr,.hljs-attribute,.hljs-literal,.hljs-meta,.hljs-number,.hljs-operator,.hljs-selector-attr,.hljs-selector-class,.hljs-selector-id,.hljs-variable{color:#005cc5}.hljs-meta .hljs-string,.hljs-regexp,.hljs-string{color:#032f62}.hljs-built_in,.hljs-symbol{color:#e36209}.hljs-code,.hljs-comment,.hljs-formula{color:#6a737d}.hljs-name,.hljs-quote,.hljs-selector-pseudo,.hljs-selector-tag{color:#22863a}.hljs-subst{color:#24292e}.hljs-section{color:#005cc5;font-weight:700}.hljs-bullet{color:#735c0f}.hljs-emphasis{color:#24292e;font-style:italic}.hljs-strong{color:#24292e;font-weight:700}.hljs-addition{color:#22863a;background-color:#f0fff4}.hljs-deletion{color:#b31d28;background-color:#ffeef0}
added forge/wwwroot/lib/highlight/highlight.min.js +1244 −0View file

The diff is too large (more than 1000 lines).

added forge/wwwroot/style.css +706 −0View file
@@ -0,0 +1,706 @@
1 /* Forge. One stylesheet, no framework.
2 Colours are tokens written as light-dark(light, dark). The page follows the system setting
3 unless the visitor picked a theme, which theme.js stores as <html data-theme="light|dark">. */
4
5 :root {
6 color-scheme: light dark;
7
8 --bg: light-dark(#ffffff, #0f1318);
9 --surface: light-dark(#f6f7f9, #161b22);
10 --surface-2: light-dark(#eceff3, #1f2630);
11 --border: light-dark(#d8dce3, #2b3440);
12 --border-strong: light-dark(#b4bcc8, #445061);
13 --text: light-dark(#171b22, #e3e8ee);
14 --muted: light-dark(#5b6472, #95a1b0);
15 --link: light-dark(#0b5fca, #74b0ff);
16 --accent: light-dark(#c2410c, #fb923c);
17 --accent-soft: light-dark(#fff1e8, #2e1d10);
18 --primary: light-dark(#c2410c, #c9480f);
19 --primary-hover: light-dark(#a3360a, #dd5514);
20 --primary-text: #ffffff;
21 --danger: light-dark(#b3261e, #ff7b72);
22 --add-bg: light-dark(#e3f6e8, #14321f);
23 --add-text: light-dark(#136c32, #7ee2a0);
24 --add-strong: light-dark(#abe7b9, #1f6b3a);
25 --del-bg: light-dark(#fde8e6, #3d1a1a);
26 --del-text: light-dark(#a4231c, #ffa198);
27 --del-strong: light-dark(#f8b8b3, #7d2a2a);
28 --hunk-bg: light-dark(#eaf1fb, #1b2a40);
29 --warn-bg: light-dark(#fff4d6, #3a3012);
30 --warn-text: light-dark(#6b4e00, #f2d27a);
31 --target-bg: light-dark(#fff3bf, #4a3f10);
32 --merged-bg: light-dark(#ebe2fb, #2e2350);
33 --merged-text: light-dark(#5b2fa6, #c9b2ff);
34 --shadow: 0 8px 28px light-dark(rgba(23, 27, 34, 0.14), rgba(0, 0, 0, 0.5));
35 --shadow-small: 0 1px 2px light-dark(rgba(23, 27, 34, 0.06), rgba(0, 0, 0, 0.3));
36 --focus: light-dark(#0b5fca, #74b0ff);
37
38 --radius: 8px;
39 --radius-small: 6px;
40 --mono: ui-monospace, "Cascadia Code", "SF Mono", Consolas, "Liberation Mono", monospace;
41 --sans: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
42 }
43
44 :root[data-theme="light"] { color-scheme: light; }
45 :root[data-theme="dark"] { color-scheme: dark; }
46
47 *, *::before, *::after { box-sizing: border-box; }
48
49 html { -webkit-text-size-adjust: 100%; }
50
51 body {
52 margin: 0;
53 min-height: 100vh;
54 display: flex;
55 flex-direction: column;
56 background: var(--bg);
57 color: var(--text);
58 font-family: var(--sans);
59 font-size: 15px;
60 line-height: 1.5;
61 }
62
63 a { color: var(--link); text-decoration: none; }
64 a:hover { text-decoration: underline; }
65
66 :focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; border-radius: 4px; }
67
68 h1 { font-size: 1.5rem; line-height: 1.25; margin: 0 0 0.5rem; letter-spacing: -0.01em; text-wrap: balance; }
69 h2 { font-size: 1.15rem; line-height: 1.3; margin: 0 0 0.75rem; }
70 h3 { font-size: 1rem; margin: 1.5rem 0 0.5rem; }
71
72 code, pre, kbd { font-family: var(--mono); font-size: 0.87rem; }
73 code { background: var(--surface-2); padding: 0.1em 0.35em; border-radius: 4px; }
74 pre code { background: none; padding: 0; }
75 kbd {
76 display: inline-block;
77 min-width: 1.5em;
78 padding: 0 5px;
79 border: 1px solid var(--border);
80 border-bottom-width: 2px;
81 border-radius: 4px;
82 background: var(--bg);
83 color: var(--muted);
84 font-size: 0.75rem;
85 line-height: 1.5;
86 text-align: center;
87 }
88
89 svg.icon {
90 flex: none;
91 fill: none;
92 stroke: currentColor;
93 stroke-width: 2;
94 stroke-linecap: round;
95 stroke-linejoin: round;
96 vertical-align: -0.15em;
97 }
98 svg.icon.logo-mark { fill: var(--accent); stroke: none; }
99
100 html:not(.js) .js-only { display: none !important; }
101
102 .wrap { width: 100%; max-width: 1180px; margin: 0 auto; padding: 0 20px; }
103 main.wrap { flex: 1; padding-top: 24px; padding-bottom: 56px; }
104 .narrow {
105 max-width: 440px;
106 margin: 40px auto;
107 padding: 28px;
108 border: 1px solid var(--border);
109 border-radius: 12px;
110 box-shadow: var(--shadow-small);
111 }
112 .auth-logo { margin-bottom: 12px; }
113
114 .skip-link { position: absolute; left: -999px; top: 8px; z-index: 100; padding: 6px 12px; background: var(--bg); border: 1px solid var(--border); border-radius: var(--radius-small); }
115 .skip-link:focus { left: 8px; }
116
117 .muted { color: var(--muted); }
118 .small { font-size: 0.85rem; }
119 .right { text-align: right; }
120 .break { overflow-wrap: anywhere; }
121 .danger-text { color: var(--danger); }
122 .added { color: var(--add-text); }
123 .deleted { color: var(--del-text); }
124 .sep { color: var(--muted); margin: 0 0.25rem; }
125
126 /* Top bar */
127 .topbar { border-bottom: 1px solid var(--border); background: var(--surface); }
128 .topbar-inner { display: flex; align-items: center; gap: 16px; min-height: 56px; }
129 .brand { display: inline-flex; align-items: center; gap: 8px; font-weight: 700; font-size: 1.1rem; letter-spacing: -0.01em; color: var(--text); }
130 .brand:hover { text-decoration: none; }
131 .topnav { display: flex; align-items: center; gap: 6px; margin-left: auto; }
132 .inline-form { display: inline; margin: 0; }
133 .link-button { background: none; border: 0; padding: 0; color: var(--link); font: inherit; cursor: pointer; }
134 .link-button:hover { text-decoration: underline; }
135
136 .icon-button {
137 display: inline-flex;
138 align-items: center;
139 justify-content: center;
140 width: 34px;
141 height: 34px;
142 border: 1px solid transparent;
143 border-radius: var(--radius-small);
144 background: none;
145 color: var(--muted);
146 cursor: pointer;
147 }
148 .icon-button:hover { background: var(--surface-2); color: var(--text); text-decoration: none; }
149 .theme-icon { display: none; }
150 :root:not([data-theme]) .theme-icon-auto,
151 :root[data-theme="light"] .theme-icon-light,
152 :root[data-theme="dark"] .theme-icon-dark { display: inline; }
153
154 /* Search box: an icon, the field, and an optional key hint, drawn as one control. */
155 .search {
156 display: flex;
157 align-items: center;
158 gap: 8px;
159 flex: 1;
160 max-width: 380px;
161 margin: 0;
162 padding: 0 10px;
163 border: 1px solid var(--border);
164 border-radius: var(--radius-small);
165 background: var(--bg);
166 color: var(--muted);
167 }
168 .search:focus-within { border-color: var(--focus); box-shadow: 0 0 0 3px color-mix(in srgb, var(--focus) 22%, transparent); }
169 .search input[type="search"] {
170 flex: 1;
171 min-width: 0;
172 padding: 6px 0;
173 border: 0;
174 outline: 0;
175 background: none;
176 color: var(--text);
177 font: inherit;
178 }
179
180 /* Dropdown menus are <details>; app.js closes them on outside click and Escape. */
181 .menu { position: relative; }
182 .menu > summary { list-style: none; cursor: pointer; }
183 .menu > summary::-webkit-details-marker { display: none; }
184 .menu-button { display: inline-flex; align-items: center; gap: 4px; padding: 3px 6px 3px 3px; border-radius: 999px; color: var(--muted); }
185 .menu-button:hover { background: var(--surface-2); }
186 .menu-panel {
187 position: absolute;
188 z-index: 30;
189 top: calc(100% + 6px);
190 left: 0;
191 min-width: 220px;
192 padding: 6px;
193 background: var(--bg);
194 border: 1px solid var(--border);
195 border-radius: var(--radius);
196 box-shadow: var(--shadow);
197 }
198 .menu-panel.menu-right { left: auto; right: 0; }
199 .menu-header { margin: 0 0 6px; padding: 6px 10px 8px; border-bottom: 1px solid var(--border); color: var(--muted); font-size: 0.85rem; }
200 .menu-header strong { color: var(--text); }
201 .menu-form { margin: 6px 0 0; padding-top: 6px; border-top: 1px solid var(--border); }
202 .menu-item {
203 display: flex;
204 align-items: center;
205 gap: 10px;
206 width: 100%;
207 padding: 6px 10px;
208 border: 0;
209 border-radius: var(--radius-small);
210 background: none;
211 color: var(--text);
212 font: inherit;
213 text-align: left;
214 cursor: pointer;
215 }
216 .menu-item:hover { background: var(--surface-2); text-decoration: none; }
217 .menu-item svg.icon { color: var(--muted); }
218
219 /* Avatars */
220 .avatar {
221 display: inline-flex;
222 align-items: center;
223 justify-content: center;
224 flex: none;
225 border-radius: 50%;
226 color: #ffffff;
227 font-weight: 700;
228 line-height: 1;
229 user-select: none;
230 }
231 .avatar-sm { width: 20px; height: 20px; font-size: 0.7rem; }
232 .avatar-md { width: 28px; height: 28px; font-size: 0.85rem; }
233 .avatar-lg { width: 72px; height: 72px; font-size: 2rem; }
234 .avatar-c0 { background: #c2410c; }
235 .avatar-c1 { background: #0f766e; }
236 .avatar-c2 { background: #1d4ed8; }
237 .avatar-c3 { background: #7c3aed; }
238 .avatar-c4 { background: #be185d; }
239 .avatar-c5 { background: #4d7c0f; }
240 .avatar-c6 { background: #a16207; }
241 .avatar-c7 { background: #475569; }
242
243 /* Footer */
244 .footer { border-top: 1px solid var(--border); font-size: 0.85rem; }
245 .footer-inner { display: flex; justify-content: space-between; align-items: center; gap: 12px 24px; flex-wrap: wrap; padding-top: 16px; padding-bottom: 20px; }
246 .footer-brand { display: inline-flex; align-items: center; gap: 6px; }
247 .language-form { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; margin: 0; }
248 .language-label { display: inline-flex; align-items: center; gap: 5px; }
249
250 /* Buttons and forms */
251 .button {
252 display: inline-flex;
253 align-items: center;
254 justify-content: center;
255 gap: 6px;
256 padding: 6px 12px;
257 border: 1px solid var(--border);
258 border-radius: var(--radius-small);
259 background: var(--surface);
260 color: var(--text);
261 font: inherit;
262 font-weight: 500;
263 line-height: 1.4;
264 cursor: pointer;
265 white-space: nowrap;
266 box-shadow: var(--shadow-small);
267 }
268 .button:hover { text-decoration: none; border-color: var(--border-strong); background: var(--surface-2); }
269 .button.primary { background: var(--primary); border-color: var(--primary); color: var(--primary-text); }
270 .button.primary:hover { background: var(--primary-hover); border-color: var(--primary-hover); }
271 .button.danger { color: var(--danger); border-color: color-mix(in srgb, var(--danger) 55%, var(--border)); background: transparent; }
272 .button.danger:hover { background: var(--del-bg); border-color: var(--danger); }
273 .button.small { padding: 2px 8px; font-size: 0.85rem; }
274 .button-row { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 12px; }
275
276 .form { display: grid; gap: 14px; }
277 .form label { display: grid; gap: 4px; font-weight: 600; }
278 .form label.choice { display: flex; gap: 8px; align-items: center; font-weight: 400; }
279 .form small { font-weight: 400; }
280 .form button { justify-self: start; }
281 input[type="text"], input[type="password"], input[type="url"], input:not([type]), select, textarea {
282 width: 100%;
283 padding: 7px 10px;
284 border: 1px solid var(--border);
285 border-radius: var(--radius-small);
286 background: var(--bg);
287 color: var(--text);
288 font: inherit;
289 }
290 input[type="text"]:focus, input[type="password"]:focus, input[type="url"]:focus, input:not([type]):focus, select:focus, textarea:focus {
291 outline: 0;
292 border-color: var(--focus);
293 box-shadow: 0 0 0 3px color-mix(in srgb, var(--focus) 22%, transparent);
294 }
295 input[type="checkbox"], input[type="radio"] { width: auto; accent-color: var(--accent); }
296 textarea { resize: vertical; }
297 textarea.code-input { font-family: var(--mono); font-size: 0.85rem; white-space: pre; overflow-x: auto; tab-size: 4; }
298 fieldset { border: 1px solid var(--border); border-radius: var(--radius-small); padding: 8px 12px; margin: 0; display: grid; gap: 6px; }
299 legend { font-weight: 600; padding: 0 4px; }
300
301 .card { border: 1px solid var(--border); border-radius: var(--radius); padding: 16px; margin: 16px 0; }
302 .card.empty, .empty { text-align: center; color: var(--muted); padding: 32px 16px; }
303 .danger-zone { border-color: color-mix(in srgb, var(--danger) 60%, var(--border)); }
304 details.card > summary { cursor: pointer; }
305 details.card[open] > summary { margin-bottom: 12px; }
306
307 .empty-state { padding: 56px 16px; border: 1px dashed var(--border-strong); border-radius: var(--radius); text-align: center; color: var(--muted); }
308 .empty-state h2 { margin: 12px 0 4px; color: var(--text); font-size: 1.05rem; }
309 .empty-state p { margin: 4px 0 0; }
310
311 .alert { padding: 10px 14px; border-radius: var(--radius-small); margin: 12px 0; border: 1px solid var(--border); }
312 .alert.error { background: var(--del-bg); color: var(--del-text); border-color: transparent; }
313 .alert.success { background: var(--add-bg); color: var(--add-text); border-color: transparent; }
314 .alert.warning { background: var(--warn-bg); color: var(--warn-text); border-color: transparent; }
315 .alert p { margin: 0 0 8px; }
316 .alert p:last-child { margin-bottom: 0; }
317 .alert ul { margin: 4px 0 0; padding-left: 20px; }
318
319 .badge {
320 display: inline-flex;
321 align-items: center;
322 gap: 4px;
323 padding: 0 8px;
324 border: 1px solid var(--border);
325 border-radius: 999px;
326 font-size: 0.75rem;
327 font-weight: 500;
328 line-height: 1.6;
329 color: var(--muted);
330 vertical-align: middle;
331 white-space: nowrap;
332 }
333 .badge-added { background: var(--add-bg); color: var(--add-text); border-color: transparent; }
334 .badge-deleted { background: var(--del-bg); color: var(--del-text); border-color: transparent; }
335 .badge-merged { background: var(--merged-bg); color: var(--merged-text); border-color: transparent; }
336 .counter { min-width: 20px; padding: 0 6px; border-radius: 999px; background: var(--surface-2); color: var(--muted); font-size: 0.75rem; font-weight: 600; line-height: 1.6; text-align: center; }
337
338 /* Tables */
339 .table { width: 100%; border-collapse: collapse; margin: 12px 0; }
340 .table th, .table td { padding: 8px 10px; border-bottom: 1px solid var(--border); text-align: left; vertical-align: top; }
341 .table th { font-size: 0.8rem; color: var(--muted); font-weight: 600; }
342 .table th.right, .table td.right { text-align: right; }
343 .table tbody tr:hover { background: var(--surface); }
344 .table td.actions { white-space: nowrap; }
345 .table td.actions .button { margin-left: 4px; }
346 .table.tree { border: 1px solid var(--border); border-radius: var(--radius); border-collapse: separate; border-spacing: 0; }
347 .table.tree tr:last-child td { border-bottom: 0; }
348 .table.tree td { vertical-align: middle; }
349 .table.tree td.icon { width: 28px; padding-right: 0; color: var(--muted); }
350 .table.tree .name { overflow-wrap: anywhere; }
351
352 /* Home and profile */
353 .page-head { display: flex; justify-content: space-between; align-items: center; gap: 12px; margin-bottom: 16px; }
354 .page-head h1, .page-head h2 { margin-bottom: 0; }
355 .page-sub { margin: 2px 0 0; }
356 .profile { display: flex; align-items: center; gap: 20px; margin-bottom: 28px; padding-bottom: 24px; border-bottom: 1px solid var(--border); }
357 .profile h1 { margin-bottom: 2px; }
358 .profile p { margin: 0; }
359 .filter-bar { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; margin-bottom: 12px; }
360 .filter-search { max-width: 420px; min-width: 200px; }
361 .repo-list { list-style: none; margin: 0; padding: 0; border: 1px solid var(--border); border-radius: var(--radius); }
362 .repo-row { display: flex; align-items: flex-start; gap: 12px; padding: 14px 16px; border-bottom: 1px solid var(--border); }
363 .repo-row:last-child { border-bottom: 0; }
364 .repo-row:hover { background: var(--surface); }
365 .repo-row:first-child { border-radius: var(--radius) var(--radius) 0 0; }
366 .repo-row:last-child { border-radius: 0 0 var(--radius) var(--radius); }
367 .repo-icon { display: inline-flex; padding-top: 3px; color: var(--muted); }
368 .repo-main { flex: 1; min-width: 0; }
369 .repo-link { font-size: 1.05rem; overflow-wrap: anywhere; }
370 .repo-row-description { margin: 2px 0 0; }
371 .repo-meta { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; padding-top: 3px; white-space: nowrap; }
372 .meta-item { display: inline-flex; align-items: center; gap: 5px; }
373
374 /* Repository header */
375 .repo-head { margin-bottom: 16px; }
376 .repo-title { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; font-size: 1.3rem; font-weight: 400; }
377 .repo-title > svg.icon { color: var(--muted); }
378 .repo-title .sep { margin: 0; }
379 .repo-name { font-weight: 700; }
380 .repo-description { margin: 0 0 8px; }
381 .repo-bar { display: flex; justify-content: space-between; align-items: flex-end; gap: 16px; flex-wrap: wrap; border-bottom: 1px solid var(--border); }
382 .tabs { display: flex; gap: 2px; flex-wrap: wrap; }
383 .tab { display: inline-flex; align-items: center; gap: 7px; padding: 8px 12px; color: var(--text); border-bottom: 2px solid transparent; margin-bottom: -1px; }
384 .tab svg.icon { color: var(--muted); }
385 .tab:hover { text-decoration: none; border-bottom-color: var(--border-strong); }
386 .tab.active { border-bottom-color: var(--accent); font-weight: 600; }
387 .tab.active svg.icon { color: var(--text); }
388 .subtabs { display: flex; gap: 4px; margin: 12px 0; }
389 .subtabs a { padding: 4px 12px; border-radius: 999px; color: var(--muted); }
390 .subtabs a:hover { background: var(--surface); text-decoration: none; color: var(--text); }
391 .subtabs .active { background: var(--surface-2); font-weight: 600; color: var(--text); }
392
393 .clone-menu { margin-bottom: 6px; }
394 .clone-panel { width: min(380px, calc(100vw - 28px)); padding: 12px; }
395 .clone-title { display: flex; align-items: center; gap: 6px; margin: 0 0 8px; font-weight: 600; }
396 .clone-hint { margin: 8px 0 0; }
397 .clone-box { display: flex; gap: 6px; min-width: 0; }
398 .clone-url { flex: 1; min-width: 0; font-family: var(--mono); font-size: 0.82rem; }
399 .copied, .copied svg.icon { color: var(--add-text); }
400
401 /* Repository home: files on the left, facts about the repository on the right. */
402 .repo-layout.with-side { display: grid; grid-template-columns: minmax(0, 1fr) 280px; gap: 32px; align-items: start; }
403 .repo-content { min-width: 0; }
404 .repo-side { margin-top: 12px; }
405 .side-section { padding-bottom: 16px; margin-bottom: 16px; border-bottom: 1px solid var(--border); }
406 .side-section:last-child { border-bottom: 0; }
407 .side-section h2 { font-size: 1rem; }
408 .side-section p { margin: 0 0 12px; overflow-wrap: anywhere; }
409 .side-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 6px; }
410 .side-list li { display: flex; align-items: center; gap: 8px; }
411 .side-list svg.icon { color: var(--muted); }
412 .side-list a { color: var(--text); }
413 .side-list a:hover { color: var(--link); }
414
415 .lang-bar { display: block; border-radius: 999px; overflow: hidden; background: var(--surface-2); }
416 .lang-bar rect { fill: var(--lang); }
417 .lang-legend { list-style: none; margin: 10px 0 0; padding: 0; display: flex; flex-wrap: wrap; gap: 4px 14px; font-size: 0.85rem; }
418 .lang-legend li { display: inline-flex; align-items: center; gap: 6px; }
419 .lang-dot { width: 9px; height: 9px; border-radius: 50%; background: var(--lang); }
420 .lang-csharp { --lang: #178600; }
421 .lang-javascript { --lang: #d4b830; }
422 .lang-typescript { --lang: #3178c6; }
423 .lang-html { --lang: #e34c26; }
424 .lang-css { --lang: #7e57c2; }
425 .lang-python { --lang: #3572a5; }
426 .lang-go { --lang: #00add8; }
427 .lang-rust { --lang: #dea584; }
428 .lang-java { --lang: #b07219; }
429 .lang-kotlin { --lang: #a97bff; }
430 .lang-swift { --lang: #f05138; }
431 .lang-c { --lang: #6e7681; }
432 .lang-cpp { --lang: #f34b7d; }
433 .lang-ruby { --lang: #a51d2d; }
434 .lang-php { --lang: #6e7bb8; }
435 .lang-lua { --lang: #3b4fc4; }
436 .lang-shell { --lang: #5fb233; }
437 .lang-powershell { --lang: #2b5797; }
438 .lang-sql { --lang: #e38c00; }
439 .lang-vb { --lang: #945db7; }
440 .lang-other { --lang: #8b949e; }
441
442 /* Toolbar: ref switcher, breadcrumbs */
443 .toolbar { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin: 12px 0; }
444 .toolbar-end { margin-left: auto; }
445 .breadcrumbs { overflow-wrap: anywhere; }
446
447 .ref-switcher { position: relative; }
448 .ref-switcher summary { list-style: none; }
449 .ref-switcher summary::-webkit-details-marker { display: none; }
450 .ref-menu {
451 position: absolute;
452 z-index: 10;
453 top: calc(100% + 4px);
454 left: 0;
455 min-width: 240px;
456 max-height: 360px;
457 overflow-y: auto;
458 background: var(--bg);
459 border: 1px solid var(--border);
460 border-radius: var(--radius);
461 padding: 6px;
462 box-shadow: var(--shadow);
463 }
464 .ref-menu-title { margin: 6px 8px 2px; font-size: 0.75rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.04em; }
465 .ref-item { display: block; padding: 4px 8px; border-radius: 4px; color: var(--text); overflow-wrap: anywhere; }
466 .ref-item:hover { background: var(--surface-2); text-decoration: none; }
467 .ref-item.active { font-weight: 700; }
468
469 /* The file list: the newest commit as its header, then one row per entry. */
470 .file-box { border: 1px solid var(--border); border-radius: var(--radius); overflow: hidden; }
471 .file-box .table.tree { margin: 0; border: 0; border-radius: 0; }
472 .latest-commit {
473 display: flex;
474 justify-content: space-between;
475 align-items: center;
476 gap: 12px;
477 padding: 10px 12px;
478 border-bottom: 1px solid var(--border);
479 background: var(--surface);
480 }
481 .latest-subject { display: flex; align-items: center; gap: 8px; min-width: 0; }
482 .latest-subject strong { white-space: nowrap; }
483 .latest-message { color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
484 .latest-meta { white-space: nowrap; }
485 .icon-folder { color: var(--link); fill: color-mix(in srgb, var(--link) 22%, transparent); }
486 .table.tree .tree-commit { width: 45%; max-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
487 .table.tree .tree-age { white-space: nowrap; }
488 .readme-name { display: flex; align-items: center; gap: 8px; margin: -16px -16px 16px; padding: 10px 16px; border-bottom: 1px solid var(--border); background: var(--surface); border-radius: var(--radius) var(--radius) 0 0; font-weight: 600; }
489 .sha { font-family: var(--mono); font-size: 0.85rem; }
490
491 /* Search inside a repository */
492 .repo-search { flex: 0 1 300px; min-width: 180px; }
493 form.toolbar .repo-search { flex: 1 1 300px; max-width: 520px; }
494 .result-heading { display: flex; align-items: center; gap: 8px; margin-top: 24px; }
495 .result-heading svg.icon { color: var(--muted); }
496 .result-files { list-style: none; margin: 8px 0; padding: 4px 0; border: 1px solid var(--border); border-radius: var(--radius); }
497 .result-files li { display: flex; align-items: center; gap: 8px; padding: 4px 12px; overflow-wrap: anywhere; }
498 .result-files svg.icon { color: var(--muted); }
499 .result-file { margin: 12px 0; border: 1px solid var(--border); border-radius: var(--radius); overflow: hidden; }
500 .result-file-head { display: flex; align-items: center; gap: 8px; padding: 8px 12px; background: var(--surface); border-bottom: 1px solid var(--border); font-family: var(--mono); font-size: 0.87rem; overflow-wrap: anywhere; }
501 .result-file-head svg.icon { color: var(--muted); }
502 .result-lines { display: block; overflow-x: auto; border-collapse: collapse; font-family: var(--mono); font-size: 0.85rem; padding: 4px 0; }
503 .result-lines td { padding: 1px 10px; vertical-align: top; }
504 .result-lines .ln { min-width: 52px; text-align: right; user-select: none; white-space: nowrap; }
505 .result-lines .ln a { color: var(--muted); }
506 .result-code { white-space: pre; tab-size: 4; }
507 mark { background: var(--target-bg); color: inherit; border-radius: 2px; }
508
509 /* README and markdown */
510 .markdown { overflow-wrap: anywhere; }
511 .markdown > :first-child { margin-top: 0; }
512 .markdown > :last-child { margin-bottom: 0; }
513 .markdown img { max-width: 100%; }
514 .markdown pre, .snippet, .plain, .commit-body {
515 background: var(--surface);
516 border-radius: var(--radius-small);
517 padding: 12px;
518 overflow-x: auto;
519 }
520 .plain, .commit-body { white-space: pre-wrap; overflow-wrap: anywhere; }
521 .markdown table { border-collapse: collapse; }
522 .markdown th, .markdown td { border: 1px solid var(--border); padding: 4px 10px; }
523 .markdown blockquote { margin: 0; padding-left: 12px; border-left: 3px solid var(--border); color: var(--muted); }
524 .markdown h1, .markdown h2 { border-bottom: 1px solid var(--border); padding-bottom: 4px; margin-top: 1.2em; }
525
526 /* File view */
527 .file-head {
528 display: flex;
529 justify-content: space-between;
530 align-items: center;
531 gap: 12px;
532 padding: 8px 12px;
533 border: 1px solid var(--border);
534 border-bottom: 0;
535 border-radius: var(--radius) var(--radius) 0 0;
536 background: var(--surface);
537 }
538 .file-info { display: flex; align-items: center; gap: 8px; min-width: 0; }
539 .file-info svg.icon { color: var(--muted); }
540 .file-name { overflow-wrap: anywhere; }
541 .file-actions { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; justify-content: flex-end; }
542 .file-actions .segmented { font-size: 0.85rem; margin-right: 6px; }
543 .file-actions .segmented a { padding: 2px 10px; }
544 .file-head + .card, .file-head + .code-view { margin-top: 0; border-radius: 0 0 var(--radius) var(--radius); }
545 .file-preview { padding: 24px 32px; }
546 .code-view { position: relative; display: flex; border: 1px solid var(--border); overflow-x: auto; }
547 .code-view pre { position: relative; margin: 0; padding: 10px 0; line-height: 1.45; }
548 .line-numbers { text-align: right; user-select: none; border-right: 1px solid var(--border); flex: none; }
549 .line-numbers a { display: block; padding: 0 10px; color: var(--muted); }
550 .line-numbers a:hover { color: var(--text); text-decoration: none; }
551 html:not(.js) .line-numbers a:target, .line-numbers a.selected { background: var(--target-bg); color: var(--text); font-weight: 700; }
552 .line-highlight { position: absolute; left: 0; background: var(--target-bg); pointer-events: none; }
553 .button-group { display: inline-flex; }
554 .button-group .button { border-radius: 0; }
555 .button-group .button + .button { margin-left: -1px; }
556 .button-group .button:first-child { border-radius: var(--radius-small) 0 0 var(--radius-small); }
557 .button-group .button:last-child { border-radius: 0 var(--radius-small) var(--radius-small) 0; }
558 .icon-button.inline { width: 24px; height: 24px; vertical-align: middle; }
559 .code-view .code { padding-left: 12px; padding-right: 12px; flex: 1; tab-size: 4; }
560 .code-view .code code.hljs { padding: 0; background: none; overflow: visible; }
561 .image-view { text-align: center; }
562 .image-view img { max-width: 100%; }
563
564 /* Commits */
565 .commit-list { list-style: none; margin: 12px 0; padding: 0; border: 1px solid var(--border); border-radius: var(--radius); }
566 .commit-row { display: flex; justify-content: space-between; align-items: center; gap: 16px; padding: 10px 14px; border-bottom: 1px solid var(--border); }
567 .commit-row:last-child { border-bottom: 0; }
568 .commit-row:hover { background: var(--surface); }
569 .commit-main { min-width: 0; }
570 .commit-day { display: flex; align-items: center; gap: 8px; margin: 20px 0 0; color: var(--muted); font-size: 0.9rem; font-weight: 600; }
571 .commit-day + .commit-list { margin-top: 8px; }
572 .commit-byline { display: flex; align-items: center; gap: 6px; margin-top: 3px; }
573 .commit-byline .sep { margin: 0; }
574 .commit-actions { display: flex; align-items: center; gap: 6px; flex: none; }
575 .meta dd .avatar { vertical-align: -4px; }
576 .commit-subject { font-weight: 600; color: var(--text); overflow-wrap: anywhere; }
577 .pager { display: flex; gap: 8px; justify-content: center; margin: 16px 0; }
578 .commit-title { overflow-wrap: anywhere; }
579 .meta { display: grid; grid-template-columns: max-content 1fr; gap: 4px 16px; margin: 12px 0; }
580 .meta dt { color: var(--muted); }
581 .meta dd { margin: 0; overflow-wrap: anywhere; }
582 .meta .sha { margin-right: 8px; }
583 .stat-list { list-style: none; margin: 8px 0 16px; padding: 0; }
584 .stat-list li { display: flex; gap: 12px; padding: 2px 0; overflow-wrap: anywhere; }
585 .stat-counts { flex: none; min-width: 90px; font-family: var(--mono); font-size: 0.85rem; }
586 .comment { margin: 8px 0; }
587 .comment p:first-child { margin-top: 0; }
588
589 /* Diff */
590 .diff-file { border: 1px solid var(--border); border-radius: var(--radius); margin: 16px 0; overflow: hidden; }
591 .diff-file-head { display: flex; gap: 10px; align-items: center; padding: 8px 12px; background: var(--surface); border-bottom: 1px solid var(--border); }
592 .diff-path { font-family: var(--mono); font-size: 0.87rem; overflow-wrap: anywhere; flex: 1; }
593 .diff-counts { font-family: var(--mono); font-size: 0.85rem; white-space: nowrap; }
594 .diff-note { margin: 0; padding: 12px; }
595 .diff { width: 100%; border-collapse: collapse; font-family: var(--mono); font-size: 0.85rem; display: block; overflow-x: auto; }
596 .diff td { padding: 0 8px; vertical-align: top; }
597 .diff .ln { width: 1%; min-width: 44px; text-align: right; color: var(--muted); user-select: none; white-space: nowrap; }
598 .diff .diff-code { white-space: pre; width: 100%; }
599 .diff .marker { display: inline-block; width: 1.2em; user-select: none; }
600 .diff tr.add { background: var(--add-bg); }
601 .diff tr.del { background: var(--del-bg); }
602 .diff tr.hunk { background: var(--hunk-bg); color: var(--muted); }
603 .diff tr.meta { color: var(--muted); font-style: italic; }
604
605 /* Diff: options, file index, collapsible files, side-by-side layout, within-line changes */
606 .diff-options { display: flex; gap: 16px; align-items: center; flex-wrap: wrap; margin: 8px 0 12px; font-size: 0.9rem; }
607 .segmented { display: inline-flex; border: 1px solid var(--border); border-radius: var(--radius-small); overflow: hidden; }
608 .segmented a { padding: 4px 12px; color: var(--text); }
609 .segmented a + a { border-left: 1px solid var(--border); }
610 .segmented a.active { background: var(--surface-2); font-weight: 600; }
611 .segmented a:hover { text-decoration: none; background: var(--surface); }
612 .diff-index { list-style: none; margin: 8px 0 16px; padding: 0; }
613 .diff-index li { display: flex; gap: 12px; padding: 2px 0; overflow-wrap: anywhere; }
614 details.diff-file > summary { cursor: pointer; list-style-position: inside; }
615 details.diff-file:not([open]) > summary { border-bottom: 0; }
616 .diff.split .diff-code { width: 50%; }
617 .diff.split td.add { background: var(--add-bg); }
618 .diff.split td.del { background: var(--del-bg); }
619 .diff.split td.blank { background: var(--surface); }
620 .diff.split td.ln + td.diff-code { border-right: 1px solid var(--border); }
621 .diff .chg { border-radius: 2px; }
622 .diff tr.add .chg, .diff td.add .chg { background: var(--add-strong); }
623 .diff tr.del .chg, .diff td.del .chg { background: var(--del-strong); }
624 .diff .line .hljs, .diff .line { background: none; }
625
626 /* Compare, conflicts and ref management */
627 .compare-form label { display: flex; align-items: center; gap: 6px; }
628 .compare-form select { width: auto; max-width: 260px; }
629 fieldset.conflict { margin-bottom: 12px; }
630 .apply-form { margin: 12px 0 0; }
631 .apply-form label { display: flex; align-items: center; gap: 6px; }
632 .apply-form select { width: auto; max-width: 260px; }
633
634 /* Pull requests */
635 .pull-icon { display: inline-flex; flex: none; }
636 .pull-open { color: var(--add-text); }
637 .pull-merged { color: var(--merged-text); }
638 .pull-closed { color: var(--del-text); }
639 .pull-main { flex: 1; }
640 .pull-title { font-size: 1.4rem; margin-bottom: 8px; }
641 .pull-summary { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin: 0 0 16px; }
642 .commit-byline { flex-wrap: wrap; }
643 .comment-head { margin: 0 0 8px; }
644 .cell-icon { color: var(--muted); margin-right: 4px; }
645
646 /* Activity: stat tiles, the weekly chart, contributors */
647 .activity-scope { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; margin: 12px 0; }
648 .stat-tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; margin: 0 0 16px; }
649 .stat-tile { padding: 14px 16px; border: 1px solid var(--border); border-radius: var(--radius); }
650 .stat-tile dt { color: var(--muted); font-size: 0.85rem; }
651 .stat-tile dd { margin: 4px 0 0; font-size: 1.7rem; font-weight: 700; line-height: 1.2; letter-spacing: -0.01em; font-variant-numeric: tabular-nums; }
652 .stat-tile dd.stat-date { font-size: 1.25rem; line-height: 1.65; }
653 .chart-sub { margin: -8px 0 12px; }
654 .chart-scroll { overflow-x: auto; }
655 .week-chart { display: block; width: 100%; min-width: 620px; height: auto; }
656 .chart-grid { stroke: var(--border); stroke-width: 1; stroke-dasharray: 2 3; }
657 .chart-axis { stroke: var(--border-strong); stroke-width: 1; }
658 .chart-label { fill: var(--muted); font-size: 10px; font-family: var(--sans); }
659 .week-hit { fill: transparent; }
660 .week-bar { fill: var(--accent); }
661 .week:hover .week-hit { fill: var(--surface-2); }
662 .section-title { display: flex; align-items: center; gap: 8px; margin-top: 28px; }
663 .contributor-list { list-style: none; margin: 0; padding: 0; border: 1px solid var(--border); border-radius: var(--radius); }
664 .contributor { display: flex; align-items: center; gap: 12px; padding: 10px 14px; border-bottom: 1px solid var(--border); }
665 .contributor:last-child { border-bottom: 0; }
666 .contributor-main { flex: 1; min-width: 0; overflow-wrap: anywhere; }
667 .contributor-share { width: 180px; flex: none; text-align: right; }
668 .share-bar { display: block; margin-top: 4px; border-radius: 999px; background: var(--surface-2); }
669 .share-bar rect { fill: var(--accent); }
670
671 /* Dialogs */
672 .dialog { width: min(420px, calc(100vw - 32px)); padding: 20px; border: 1px solid var(--border); border-radius: 12px; background: var(--bg); color: var(--text); box-shadow: var(--shadow); }
673 .dialog::backdrop { background: rgba(0, 0, 0, 0.45); }
674 .shortcut-list { display: grid; grid-template-columns: max-content 1fr; gap: 10px 16px; margin: 0 0 20px; align-items: center; }
675 .shortcut-list dd { margin: 0; }
676 .footer-link { margin-left: 12px; }
677
678 /* Status pages */
679 .status-action { margin-top: 24px; }
680 .status-page { text-align: center; padding: 72px 0; }
681 .status-code { font-size: 4rem; font-weight: 800; line-height: 1; letter-spacing: -0.03em; margin: 0 0 12px; color: var(--accent); }
682
683 @media (max-width: 900px) {
684 .repo-layout.with-side { grid-template-columns: minmax(0, 1fr); gap: 8px; }
685 }
686
687 @media (max-width: 720px) {
688 .wrap { padding: 0 14px; }
689 .table.tree .tree-commit, .latest-message { display: none; }
690 .file-head { flex-wrap: wrap; }
691 .file-preview { padding: 16px; }
692 .file-box .table.tree { display: table; }
693 .repo-row { flex-wrap: wrap; }
694 .repo-meta { width: 100%; padding-left: 30px; }
695 .commit-row { flex-direction: column; align-items: flex-start; gap: 4px; }
696 .clone-url { width: 100%; }
697 .clone-box { width: 100%; }
698 .table { display: block; overflow-x: auto; }
699 .search kbd { display: none; }
700 .narrow { margin: 16px auto; padding: 20px; }
701 .profile { gap: 14px; }
702 }
703
704 @media (prefers-reduced-motion: no-preference) {
705 .button, .icon-button, .menu-item, .tab { transition: background-color 0.12s, border-color 0.12s, color 0.12s; }
706 }
added forge/wwwroot/theme.js +15 −0View file
@@ -0,0 +1,15 @@
1 // Runs before the page paints, so a saved light/dark choice never flashes the other theme.
2 // Without a saved choice the page follows the system setting (see the media query in style.css).
3 (function () {
4 var root = document.documentElement;
5 // Controls that only work with script (theme switch, copy buttons) are hidden until this is set.
6 root.classList.add('js');
7 try {
8 var theme = localStorage.getItem('forge-theme');
9 if (theme === 'light' || theme === 'dark') {
10 root.dataset.theme = theme;
11 }
12 } catch (e) {
13 // Storage can be blocked; the system setting still applies.
14 }
15 })();

Keyboard shortcuts

/
Search repositories
s
Search file names and code
y
Open the permalink of the file being viewed
?
Show this help