Line selection and permalinks, blame page, file finder and branches page
Browse files at this commiteeec00729f7c4fe5ce30d5fc0d895a0b9b70a1c1Parent: 4be0553- feat
- line selection and permalinks, blame page, file finder and branches page
13 changed files +2149 -27
- crates/forge-web/assets/nav.js +285 -0
- crates/forge-web/src/internal.rs +5 -1
- crates/forge-web/src/pages/blame.rs +282 -0
- crates/forge-web/src/pages/blob.rs +28 -3
- crates/forge-web/src/pages/branches.rs +461 -0
- crates/forge-web/src/pages/browse_tests.rs +504 -0
- crates/forge-web/src/pages/finder.rs +92 -0
- crates/forge-web/src/pages/mod.rs +5 -0
- crates/forge-web/src/pages/refs.rs +2 -23
- crates/forge-web/src/pages/repo.rs +3 -0
- crates/forge-web/src/pages/tree.rs +5 -0
- style/_browse.scss +476 -0
- style/main.scss +1 -0
crates/forge-web/assets/nav.jsmodified+285 -0
| @@ -1080,3 +1080,288 @@ | ||
| 1080 | 1080 | load({ target: withoutHash(url), dest: url, init: GET_INIT, how: 'query', keep: true, post: false, form: null }); |
| 1081 | 1081 | }; |
| 1082 | 1082 | })(); |
| 1083 | + | |
| 1084 | +// Code browsing: line selection on blobs and blame, the permalink copy and `y` shortcut, the file | |
| 1085 | +// finder (`t`) and the inline confirmations on the branches page. Everything is event driven: | |
| 1086 | +// delegated listeners, plus one observer that re-applies the line highlight after a soft swap. | |
| 1087 | +(function () { | |
| 1088 | + 'use strict'; | |
| 1089 | + if (window.__forgeBrowse) { return; } | |
| 1090 | + window.__forgeBrowse = true; | |
| 1091 | + | |
| 1092 | + var anchorLine = 0; // first line of the current selection (the shift-click anchor) | |
| 1093 | + var finderLists = {}; // finder source URL -> { paths, truncated } | |
| 1094 | + | |
| 1095 | + function typing(el) { | |
| 1096 | + if (!el || !el.tagName) { return false; } | |
| 1097 | + var tag = el.tagName; | |
| 1098 | + return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || el.isContentEditable; | |
| 1099 | + } | |
| 1100 | + | |
| 1101 | + // ---- line selection ------------------------------------------------------------------------- | |
| 1102 | + | |
| 1103 | + function parseRange(hash) { | |
| 1104 | + var m = /^#L(\d+)(?:-L?(\d+))?$/.exec(hash || ''); | |
| 1105 | + if (!m) { return null; } | |
| 1106 | + var a = parseInt(m[1], 10), b = m[2] ? parseInt(m[2], 10) : a; | |
| 1107 | + return a <= b ? [a, b] : [b, a]; | |
| 1108 | + } | |
| 1109 | + | |
| 1110 | + function applyLines(scroll) { | |
| 1111 | + var host = document.querySelector('[data-lines]'); | |
| 1112 | + if (!host) { return; } | |
| 1113 | + host.querySelectorAll('tr.line-hl').forEach(function (tr) { tr.classList.remove('line-hl'); }); | |
| 1114 | + var range = parseRange(location.hash); | |
| 1115 | + if (!range) { return; } | |
| 1116 | + var first = null; | |
| 1117 | + for (var n = range[0]; n <= range[1] && n - range[0] < 5000; n++) { | |
| 1118 | + var row = document.getElementById('L' + n); | |
| 1119 | + if (!row || !host.contains(row)) { continue; } | |
| 1120 | + row.classList.add('line-hl'); | |
| 1121 | + if (!first) { first = row; } | |
| 1122 | + } | |
| 1123 | + anchorLine = range[0]; | |
| 1124 | + if (first && scroll) { first.scrollIntoView({ block: 'center' }); } | |
| 1125 | + } | |
| 1126 | + | |
| 1127 | + function selectLine(n, extend) { | |
| 1128 | + var from = n, to = n; | |
| 1129 | + if (extend && anchorLine) { | |
| 1130 | + from = Math.min(anchorLine, n); | |
| 1131 | + to = Math.max(anchorLine, n); | |
| 1132 | + } | |
| 1133 | + var hash = from === to ? '#L' + from : '#L' + from + '-L' + to; | |
| 1134 | + history.replaceState(history.state, '', location.pathname + location.search + hash); | |
| 1135 | + applyLines(false); | |
| 1136 | + if (!extend) { anchorLine = n; } | |
| 1137 | + } | |
| 1138 | + | |
| 1139 | + document.addEventListener('click', function (e) { | |
| 1140 | + var a = e.target && e.target.closest ? e.target.closest('[data-lines] .ln a') : null; | |
| 1141 | + if (!a || e.button !== 0 || e.metaKey || e.ctrlKey || e.altKey) { return; } | |
| 1142 | + var tr = a.closest('tr'); | |
| 1143 | + var n = tr ? parseInt((tr.id || '').slice(1), 10) : NaN; | |
| 1144 | + if (!n) { return; } | |
| 1145 | + e.preventDefault(); | |
| 1146 | + selectLine(n, e.shiftKey); | |
| 1147 | + }, false); | |
| 1148 | + | |
| 1149 | + window.addEventListener('hashchange', function () { applyLines(true); }); | |
| 1150 | + | |
| 1151 | + // ---- permalink ------------------------------------------------------------------------------ | |
| 1152 | + | |
| 1153 | + function permalinkPath() { | |
| 1154 | + var host = document.querySelector('[data-permalink]'); | |
| 1155 | + return host ? host.getAttribute('data-permalink') : null; | |
| 1156 | + } | |
| 1157 | + | |
| 1158 | + function copyText(text) { | |
| 1159 | + if (navigator.clipboard && navigator.clipboard.writeText) { | |
| 1160 | + return navigator.clipboard.writeText(text); | |
| 1161 | + } | |
| 1162 | + return new Promise(function (resolve, reject) { | |
| 1163 | + var ta = document.createElement('textarea'); | |
| 1164 | + ta.value = text; | |
| 1165 | + ta.setAttribute('readonly', ''); | |
| 1166 | + document.body.appendChild(ta); | |
| 1167 | + ta.select(); | |
| 1168 | + var ok = false; | |
| 1169 | + try { ok = document.execCommand('copy'); } catch (err) { ok = false; } | |
| 1170 | + ta.remove(); | |
| 1171 | + if (ok) { resolve(); } else { reject(new Error('copy failed')); } | |
| 1172 | + }); | |
| 1173 | + } | |
| 1174 | + | |
| 1175 | + document.addEventListener('click', function (e) { | |
| 1176 | + var btn = e.target && e.target.closest ? e.target.closest('[data-copy-permalink]') : null; | |
| 1177 | + if (!btn) { return; } | |
| 1178 | + var path = permalinkPath(); | |
| 1179 | + if (!path) { return; } | |
| 1180 | + var label = btn.textContent; | |
| 1181 | + copyText(location.origin + path + location.hash).then(function () { | |
| 1182 | + btn.textContent = btn.getAttribute('data-copied') || label; | |
| 1183 | + setTimeout(function () { btn.textContent = label; }, 1500); | |
| 1184 | + }, function () { }); | |
| 1185 | + }, false); | |
| 1186 | + | |
| 1187 | + // ---- file finder ---------------------------------------------------------------------------- | |
| 1188 | + | |
| 1189 | + function finderEls(dlg) { | |
| 1190 | + return { | |
| 1191 | + input: dlg.querySelector('[data-finder-input]'), | |
| 1192 | + list: dlg.querySelector('[data-finder-list]'), | |
| 1193 | + note: dlg.querySelector('[data-finder-note]') | |
| 1194 | + }; | |
| 1195 | + } | |
| 1196 | + | |
| 1197 | + function fuzzy(q, p) { | |
| 1198 | + var pl = p.toLowerCase(); | |
| 1199 | + var base = pl.lastIndexOf('/') + 1; | |
| 1200 | + var sub = pl.indexOf(q, base); | |
| 1201 | + var idx = [], i; | |
| 1202 | + if (sub >= 0) { | |
| 1203 | + for (i = 0; i < q.length; i++) { idx.push(sub + i); } | |
| 1204 | + return { score: 200 - (pl.length - sub) * 0.1 - pl.length * 0.01, idx: idx }; | |
| 1205 | + } | |
| 1206 | + var qi = 0, score = 0, prev = -2; | |
| 1207 | + for (i = 0; i < pl.length && qi < q.length; i++) { | |
| 1208 | + if (pl.charCodeAt(i) === q.charCodeAt(qi)) { | |
| 1209 | + idx.push(i); | |
| 1210 | + var s = 1; | |
| 1211 | + if (i === prev + 1) { s += 5; } | |
| 1212 | + if (i === 0 || '/._-'.indexOf(pl.charAt(i - 1)) >= 0) { s += 4; } | |
| 1213 | + if (i >= base) { s += 2; } | |
| 1214 | + score += s; | |
| 1215 | + prev = i; | |
| 1216 | + qi++; | |
| 1217 | + } | |
| 1218 | + } | |
| 1219 | + if (qi < q.length) { return null; } | |
| 1220 | + return { score: score - pl.length * 0.05, idx: idx }; | |
| 1221 | + } | |
| 1222 | + | |
| 1223 | + function highlighted(path, idx) { | |
| 1224 | + var frag = document.createDocumentFragment(); | |
| 1225 | + var at = 0; | |
| 1226 | + idx.forEach(function (k) { | |
| 1227 | + if (k > at) { frag.appendChild(document.createTextNode(path.slice(at, k))); } | |
| 1228 | + var m = document.createElement('mark'); | |
| 1229 | + m.textContent = path.charAt(k); | |
| 1230 | + frag.appendChild(m); | |
| 1231 | + at = k + 1; | |
| 1232 | + }); | |
| 1233 | + if (at < path.length) { frag.appendChild(document.createTextNode(path.slice(at))); } | |
| 1234 | + return frag; | |
| 1235 | + } | |
| 1236 | + | |
| 1237 | + function fileHref(dlg, path) { | |
| 1238 | + var base = dlg.getAttribute('data-base') || ''; | |
| 1239 | + return base + path.split('/').map(encodeURIComponent).join('/'); | |
| 1240 | + } | |
| 1241 | + | |
| 1242 | + function setSelected(dlg, index) { | |
| 1243 | + var els = finderEls(dlg); | |
| 1244 | + var items = els.list.children; | |
| 1245 | + if (!items.length) { return; } | |
| 1246 | + index = Math.max(0, Math.min(items.length - 1, index)); | |
| 1247 | + for (var i = 0; i < items.length; i++) { | |
| 1248 | + items[i].setAttribute('aria-selected', i === index ? 'true' : 'false'); | |
| 1249 | + } | |
| 1250 | + els.input.setAttribute('aria-activedescendant', items[index].id); | |
| 1251 | + items[index].scrollIntoView({ block: 'nearest' }); | |
| 1252 | + dlg.__sel = index; | |
| 1253 | + } | |
| 1254 | + | |
| 1255 | + function renderFinder(dlg) { | |
| 1256 | + var els = finderEls(dlg); | |
| 1257 | + var data = finderLists[dlg.getAttribute('data-src')]; | |
| 1258 | + els.list.textContent = ''; | |
| 1259 | + if (!data) { return; } | |
| 1260 | + var q = els.input.value.trim().toLowerCase(); | |
| 1261 | + var hits = []; | |
| 1262 | + if (!q) { | |
| 1263 | + hits = data.paths.slice(0, 50).map(function (p) { return { path: p, idx: [] }; }); | |
| 1264 | + } else { | |
| 1265 | + for (var i = 0; i < data.paths.length; i++) { | |
| 1266 | + var m = fuzzy(q, data.paths[i]); | |
| 1267 | + if (m) { hits.push({ path: data.paths[i], score: m.score, idx: m.idx }); } | |
| 1268 | + } | |
| 1269 | + hits.sort(function (a, b) { return b.score - a.score; }); | |
| 1270 | + hits = hits.slice(0, 50); | |
| 1271 | + } | |
| 1272 | + hits.forEach(function (hit, n) { | |
| 1273 | + var li = document.createElement('li'); | |
| 1274 | + li.id = 'finder-opt-' + n; | |
| 1275 | + li.setAttribute('role', 'option'); | |
| 1276 | + var a = document.createElement('a'); | |
| 1277 | + a.href = fileHref(dlg, hit.path); | |
| 1278 | + a.appendChild(highlighted(hit.path, hit.idx)); | |
| 1279 | + li.appendChild(a); | |
| 1280 | + els.list.appendChild(li); | |
| 1281 | + }); | |
| 1282 | + if (hits.length) { | |
| 1283 | + els.note.textContent = data.truncated ? dlg.getAttribute('data-truncated') : els.note.getAttribute('data-hint'); | |
| 1284 | + setSelected(dlg, 0); | |
| 1285 | + } else { | |
| 1286 | + els.note.textContent = dlg.getAttribute('data-empty'); | |
| 1287 | + els.input.removeAttribute('aria-activedescendant'); | |
| 1288 | + } | |
| 1289 | + } | |
| 1290 | + | |
| 1291 | + function openFinder() { | |
| 1292 | + var dlg = document.querySelector('dialog[data-finder]'); | |
| 1293 | + if (!dlg || dlg.open || typeof dlg.showModal !== 'function') { return; } | |
| 1294 | + var els = finderEls(dlg); | |
| 1295 | + if (!els.note.getAttribute('data-hint')) { els.note.setAttribute('data-hint', els.note.textContent); } | |
| 1296 | + dlg.showModal(); | |
| 1297 | + els.input.value = ''; | |
| 1298 | + els.input.focus(); | |
| 1299 | + var src = dlg.getAttribute('data-src'); | |
| 1300 | + if (finderLists[src]) { renderFinder(dlg); return; } | |
| 1301 | + els.note.textContent = dlg.getAttribute('data-loading'); | |
| 1302 | + fetch(src, { headers: { accept: 'application/json' }, credentials: 'same-origin' }).then(function (r) { | |
| 1303 | + if (!r.ok) { throw new Error('status ' + r.status); } | |
| 1304 | + return r.json(); | |
| 1305 | + }).then(function (json) { | |
| 1306 | + finderLists[src] = { paths: json.paths || [], truncated: !!json.truncated }; | |
| 1307 | + if (dlg.isConnected) { renderFinder(dlg); } | |
| 1308 | + }).catch(function () { | |
| 1309 | + if (dlg.isConnected) { els.note.textContent = dlg.getAttribute('data-failed'); } | |
| 1310 | + }); | |
| 1311 | + } | |
| 1312 | + | |
| 1313 | + document.addEventListener('click', function (e) { | |
| 1314 | + var t = e.target; | |
| 1315 | + if (!t || !t.closest) { return; } | |
| 1316 | + if (t.closest('[data-finder-open]')) { e.preventDefault(); openFinder(); return; } | |
| 1317 | + // The backdrop is the dialog element itself; the box fills the rest. | |
| 1318 | + if (t.tagName === 'DIALOG' && t.hasAttribute('data-finder')) { t.close(); return; } | |
| 1319 | + var link = t.closest('dialog[data-finder] a'); | |
| 1320 | + if (link) { link.closest('dialog').close(); } | |
| 1321 | + var cancel = t.closest('[data-close-details]'); | |
| 1322 | + if (cancel) { | |
| 1323 | + var det = cancel.closest('details'); | |
| 1324 | + if (det) { det.open = false; } | |
| 1325 | + } | |
| 1326 | + }, false); | |
| 1327 | + | |
| 1328 | + document.addEventListener('input', function (e) { | |
| 1329 | + var input = e.target && e.target.closest ? e.target.closest('[data-finder-input]') : null; | |
| 1330 | + if (input) { renderFinder(input.closest('dialog')); } | |
| 1331 | + }, false); | |
| 1332 | + | |
| 1333 | + document.addEventListener('keydown', function (e) { | |
| 1334 | + var input = e.target && e.target.closest ? e.target.closest('[data-finder-input]') : null; | |
| 1335 | + if (input) { | |
| 1336 | + var dlg = input.closest('dialog'); | |
| 1337 | + var sel = dlg.__sel || 0; | |
| 1338 | + if (e.key === 'ArrowDown') { e.preventDefault(); setSelected(dlg, sel + 1); } | |
| 1339 | + else if (e.key === 'ArrowUp') { e.preventDefault(); setSelected(dlg, sel - 1); } | |
| 1340 | + else if (e.key === 'Enter') { | |
| 1341 | + e.preventDefault(); | |
| 1342 | + var item = dlg.querySelector('[data-finder-list] li[aria-selected="true"] a'); | |
| 1343 | + if (item) { dlg.close(); item.click(); } | |
| 1344 | + } | |
| 1345 | + return; | |
| 1346 | + } | |
| 1347 | + if (e.ctrlKey || e.metaKey || e.altKey || e.shiftKey || typing(e.target)) { return; } | |
| 1348 | + if (document.querySelector('dialog[open]')) { return; } | |
| 1349 | + if (e.key === 't' && document.querySelector('dialog[data-finder]')) { | |
| 1350 | + e.preventDefault(); | |
| 1351 | + openFinder(); | |
| 1352 | + } else if (e.key === 'y') { | |
| 1353 | + var path = permalinkPath(); | |
| 1354 | + if (path && location.pathname !== path && window.__forgeQuery) { | |
| 1355 | + e.preventDefault(); | |
| 1356 | + window.__forgeQuery(path + location.hash); | |
| 1357 | + } | |
| 1358 | + } | |
| 1359 | + }, false); | |
| 1360 | + | |
| 1361 | + // ---- soft swaps ----------------------------------------------------------------------------- | |
| 1362 | + | |
| 1363 | + // A soft swap replaces the body's children; the new page's highlight is applied once the URL has | |
| 1364 | + // been updated (observer callbacks run after the swap function returns). | |
| 1365 | + new MutationObserver(function () { applyLines(true); }).observe(document.body, { childList: true }); | |
| 1366 | + applyLines(true); | |
| 1367 | +})(); |
crates/forge-web/src/internal.rsmodified+5 -1
| @@ -606,7 +606,11 @@ pub async fn evaluate_pre_receive( | ||
| 606 | 606 | /// Whether `actor_id` may push straight to a `restrict_push` branch: an instance admin, the owner |
| 607 | 607 | /// of a person-owned repo, or someone whose effective role is Admin (a collaborator Admin, or an |
| 608 | 608 | /// org owner or admin team on an org-owned repo). Pull request merges do not go through here. |
| 609 | -async fn may_push_directly(store: &Store, repo: &Repo, actor_id: &str) -> forge_core::Result<bool> { | |
| 609 | +pub(crate) async fn may_push_directly( | |
| 610 | + store: &Store, | |
| 611 | + repo: &Repo, | |
| 612 | + actor_id: &str, | |
| 613 | +) -> forge_core::Result<bool> { | |
| 610 | 614 | let Some(actor) = store.user_by_id(actor_id).await? else { |
| 611 | 615 | return Ok(false); |
| 612 | 616 | }; |
crates/forge-web/src/pages/blame.rsadded+282 -0
| @@ -0,0 +1,282 @@ | ||
| 1 | +//! Page: blame at `/{owner}/{repo}/blame/{*rest}` (`ref/path`). Consecutive lines from the same | |
| 2 | +//! commit form a group showing the short oid, author, age and summary, with links to the commit | |
| 3 | +//! and to "blame prior to this commit". Large files and slow runs get a friendly message. | |
| 4 | + | |
| 5 | +use std::time::Duration; | |
| 6 | + | |
| 7 | +use forge_git::blame::{Blame, blame}; | |
| 8 | +use forge_git::browse::EntryKind; | |
| 9 | +use topcoat::Result; | |
| 10 | +use topcoat::context::{Cx, app_context}; | |
| 11 | +use topcoat::router::error::not_found; | |
| 12 | +use topcoat::router::{page, path_param}; | |
| 13 | +use topcoat::view::{Unescaped, View, component, view}; | |
| 14 | + | |
| 15 | +use crate::i18n::browse as b; | |
| 16 | +use crate::i18n::code::{self as g, K}; | |
| 17 | +use crate::i18n::{self, Lang}; | |
| 18 | +use crate::pages::blob::{Line, text_lines}; | |
| 19 | +use crate::pages::repo::repo_head; | |
| 20 | +use crate::pages::repo_ctx::load_repo; | |
| 21 | +use crate::pages::tree::{MAX_BLOB_BYTES, path_crumbs, read_file, resolve}; | |
| 22 | +use crate::render::emoji::emojify; | |
| 23 | +use crate::state::AppState; | |
| 24 | +use crate::views::{ | |
| 25 | + Crumb, breadcrumb, human_size, iso_time, now_unix, relative_time, repo_href, shell, short_oid, | |
| 26 | +}; | |
| 27 | + | |
| 28 | +path_param!(owner); | |
| 29 | +path_param!(repo); | |
| 30 | +path_param!(*rest); | |
| 31 | + | |
| 32 | +/// How long a blame may run before it is stopped. | |
| 33 | +const BLAME_TIMEOUT: Duration = Duration::from_secs(10); | |
| 34 | + | |
| 35 | +/// Why no blame is shown. | |
| 36 | +enum Problem { | |
| 37 | + TooLarge, | |
| 38 | + Timeout, | |
| 39 | + NotText, | |
| 40 | + Failed, | |
| 41 | +} | |
| 42 | + | |
| 43 | +/// The cell shown on the first row of a group. | |
| 44 | +struct Meta { | |
| 45 | + rows: usize, | |
| 46 | + short: String, | |
| 47 | + commit_href: String, | |
| 48 | + author: String, | |
| 49 | + summary: String, | |
| 50 | + iso: String, | |
| 51 | + age: String, | |
| 52 | + prior_href: Option<String>, | |
| 53 | +} | |
| 54 | + | |
| 55 | +/// One line of the blame table. `meta` is set on the first line of each group. | |
| 56 | +struct Row { | |
| 57 | + line: Line, | |
| 58 | + meta: Option<Meta>, | |
| 59 | + first: bool, | |
| 60 | +} | |
| 61 | + | |
| 62 | +fn build_rows( | |
| 63 | + lang: Lang, | |
| 64 | + owner: &str, | |
| 65 | + name: &str, | |
| 66 | + blame: &Blame, | |
| 67 | + lines: Vec<Line>, | |
| 68 | + now: i64, | |
| 69 | +) -> Vec<Row> { | |
| 70 | + let mut lines = lines.into_iter(); | |
| 71 | + let mut rows = Vec::with_capacity(blame.total as usize); | |
| 72 | + for group in &blame.groups { | |
| 73 | + let commit = blame.commits.get(&group.commit); | |
| 74 | + let mut meta = Some(Meta { | |
| 75 | + rows: group.lines as usize, | |
| 76 | + short: short_oid(&group.commit).to_owned(), | |
| 77 | + commit_href: repo_href(owner, name, "commit", &group.commit), | |
| 78 | + author: commit.map(|c| c.author.clone()).unwrap_or_default(), | |
| 79 | + summary: commit | |
| 80 | + .map(|c| emojify(&c.summary).into_owned()) | |
| 81 | + .unwrap_or_default(), | |
| 82 | + iso: commit.map(|c| iso_time(c.author_time)).unwrap_or_default(), | |
| 83 | + age: commit | |
| 84 | + .map(|c| relative_time(lang, c.author_time, now)) | |
| 85 | + .unwrap_or_default(), | |
| 86 | + prior_href: commit | |
| 87 | + .and_then(|c| c.previous.as_ref()) | |
| 88 | + .map(|(oid, file)| repo_href(owner, name, "blame", &format!("{oid}/{file}"))), | |
| 89 | + }); | |
| 90 | + for i in 0..group.lines { | |
| 91 | + let Some(line) = lines.next() else { | |
| 92 | + return rows; | |
| 93 | + }; | |
| 94 | + rows.push(Row { | |
| 95 | + line, | |
| 96 | + meta: meta.take(), | |
| 97 | + first: i == 0, | |
| 98 | + }); | |
| 99 | + } | |
| 100 | + } | |
| 101 | + rows | |
| 102 | +} | |
| 103 | + | |
| 104 | +#[component] | |
| 105 | +async fn blame_table(rows: Vec<Row>, lang: Lang) -> Result<impl View> { | |
| 106 | + Ok(view! { | |
| 107 | + <div class="file-view"> | |
| 108 | + <table class="file-table blame-table"> | |
| 109 | + <tbody> | |
| 110 | + for row in rows.into_iter() { | |
| 111 | + <tr id=(format!("L{}", row.line.num)) class=(if row.first { "blame-first" } else { "" })> | |
| 112 | + if let Some(meta) = row.meta { | |
| 113 | + <td class="blame-meta" rowspan=(meta.rows.to_string())> | |
| 114 | + <div class="blame-top"> | |
| 115 | + <a class="mono" href=(meta.commit_href.as_str())>(meta.short.as_str())</a> | |
| 116 | + <span class="blame-author">(meta.author.as_str())</span> | |
| 117 | + <time class="muted" datetime=(meta.iso.as_str())>(meta.age.as_str())</time> | |
| 118 | + </div> | |
| 119 | + <a class="blame-summary" href=(meta.commit_href.as_str()) title=(meta.summary.as_str())>(meta.summary.as_str())</a> | |
| 120 | + if let Some(prior) = meta.prior_href { | |
| 121 | + <a class="blame-prior small" href=(prior.as_str())>(b::t(lang, b::K::BlamePrior))</a> | |
| 122 | + } | |
| 123 | + </td> | |
| 124 | + } | |
| 125 | + <td class="ln"><a href=(format!("#L{}", row.line.num))>(row.line.num.as_str())</a></td> | |
| 126 | + <td class="code"> | |
| 127 | + if row.line.highlighted { | |
| 128 | + (Unescaped::new_unchecked(row.line.code)) | |
| 129 | + } else { | |
| 130 | + (row.line.code) | |
| 131 | + } | |
| 132 | + </td> | |
| 133 | + </tr> | |
| 134 | + } | |
| 135 | + </tbody> | |
| 136 | + </table> | |
| 137 | + </div> | |
| 138 | + }) | |
| 139 | +} | |
| 140 | + | |
| 141 | +#[page("/{owner}/{repo}/blame/{*rest}")] | |
| 142 | +async fn blame_page(cx: &Cx) -> Result<impl View> { | |
| 143 | + let owner = path_param::<Owner>(cx); | |
| 144 | + let name = path_param::<Repo>(cx); | |
| 145 | + let rest = path_param::<Rest>(cx).collect::<Vec<_>>().join("/"); | |
| 146 | + | |
| 147 | + let ctx = load_repo(cx, owner, name).await?; | |
| 148 | + let state = app_context::<AppState>(cx); | |
| 149 | + let lang = i18n::lang(cx, ctx.viewer.as_ref().map(|(user, _)| user)); | |
| 150 | + let repo = &ctx.repo; | |
| 151 | + | |
| 152 | + let Some((ref_name, commit, file)) = resolve(ctx.path.clone(), rest).await? else { | |
| 153 | + return Err(not_found().into()); | |
| 154 | + }; | |
| 155 | + let Some(blob) = read_file(ctx.path.clone(), commit.clone(), file.clone()).await? else { | |
| 156 | + return Err(not_found().into()); | |
| 157 | + }; | |
| 158 | + let file_name = file.rsplit('/').next().unwrap_or(&file).to_owned(); | |
| 159 | + | |
| 160 | + let mut rows: Vec<Row> = Vec::new(); | |
| 161 | + let mut problem = None; | |
| 162 | + let text_kind = matches!(blob.kind, EntryKind::Blob | EntryKind::Executable); | |
| 163 | + if !text_kind || blob.is_binary { | |
| 164 | + problem = Some(Problem::NotText); | |
| 165 | + } else if blob.truncated || blob.size > MAX_BLOB_BYTES as u64 { | |
| 166 | + problem = Some(Problem::TooLarge); | |
| 167 | + } else { | |
| 168 | + let run = blame(&state.git, &ctx.path, &commit, &file, false); | |
| 169 | + match tokio::time::timeout(BLAME_TIMEOUT, run).await { | |
| 170 | + Ok(Ok(result)) => { | |
| 171 | + let text = String::from_utf8_lossy(&blob.data).into_owned(); | |
| 172 | + let lines = text_lines(&text, &file_name); | |
| 173 | + rows = build_rows( | |
| 174 | + lang, | |
| 175 | + &repo.owner_name, | |
| 176 | + &repo.name, | |
| 177 | + &result, | |
| 178 | + lines, | |
| 179 | + now_unix(), | |
| 180 | + ); | |
| 181 | + } | |
| 182 | + Ok(Err(e)) => { | |
| 183 | + tracing::warn!(error = %e, "blame failed"); | |
| 184 | + problem = Some(Problem::Failed); | |
| 185 | + } | |
| 186 | + Err(_) => { | |
| 187 | + tracing::warn!("blame timed out"); | |
| 188 | + problem = Some(Problem::Timeout); | |
| 189 | + } | |
| 190 | + } | |
| 191 | + } | |
| 192 | + | |
| 193 | + let blob_href = repo_href( | |
| 194 | + &repo.owner_name, | |
| 195 | + &repo.name, | |
| 196 | + "blob", | |
| 197 | + &format!("{ref_name}/{file}"), | |
| 198 | + ); | |
| 199 | + let history = repo_href( | |
| 200 | + &repo.owner_name, | |
| 201 | + &repo.name, | |
| 202 | + "commits", | |
| 203 | + &format!("{ref_name}/{file}"), | |
| 204 | + ); | |
| 205 | + let crumbs: Vec<Crumb> = path_crumbs(repo, &ref_name, "blob", &file); | |
| 206 | + let title = format!( | |
| 207 | + "{}/{} \u{b7} {} \u{b7} {file}", | |
| 208 | + repo.owner_name, | |
| 209 | + repo.name, | |
| 210 | + b::t(lang, b::K::BlameTitle) | |
| 211 | + ); | |
| 212 | + let size = human_size(lang, blob.size); | |
| 213 | + let message = problem.map(|p| match p { | |
| 214 | + Problem::TooLarge => b::blame_limit(lang, &human_size(lang, MAX_BLOB_BYTES as u64)), | |
| 215 | + Problem::Timeout => b::t(lang, b::K::BlameTimeout).to_owned(), | |
| 216 | + Problem::NotText => b::t(lang, b::K::BlameNotText).to_owned(), | |
| 217 | + Problem::Failed => b::t(lang, b::K::BlameFailed).to_owned(), | |
| 218 | + }); | |
| 219 | + let has_rows = !rows.is_empty(); | |
| 220 | + | |
| 221 | + let header = ctx.head(state, "code").await?; | |
| 222 | + Ok(view! { | |
| 223 | + shell(title: title.as_str(), viewer: ctx.viewer.as_ref(), | |
| 224 | + repo_head(head: header) | |
| 225 | + <div class="browse-bar"> | |
| 226 | + breadcrumb(lang: lang, crumbs: crumbs) | |
| 227 | + </div> | |
| 228 | + <section class="file" data-lines=""> | |
| 229 | + <header class="file-head"> | |
| 230 | + <span class="muted small">(b::t(lang, b::K::BlameTitle)) " \u{b7} " (size)</span> | |
| 231 | + <nav class="file-actions" aria-label=(g::t(lang, K::FileNav))> | |
| 232 | + <a href=(blob_href.as_str())>(b::t(lang, b::K::BlameBackToFile))</a> | |
| 233 | + <a href=(history.as_str())>(g::t(lang, K::HistoryLink))</a> | |
| 234 | + </nav> | |
| 235 | + </header> | |
| 236 | + if let Some(text) = message { | |
| 237 | + <p class="notice">(text)</p> | |
| 238 | + } | |
| 239 | + if has_rows { | |
| 240 | + blame_table(rows: rows, lang: lang) | |
| 241 | + } | |
| 242 | + </section> | |
| 243 | + ) | |
| 244 | + }) | |
| 245 | +} | |
| 246 | + | |
| 247 | +#[cfg(test)] | |
| 248 | +mod tests { | |
| 249 | + use forge_core::Visibility; | |
| 250 | + | |
| 251 | + use crate::pages::commits::test_support::{Fixture, OWNER, REPO, get}; | |
| 252 | + | |
| 253 | + #[tokio::test] | |
| 254 | + async fn blame_groups_lines_by_commit() { | |
| 255 | + let fx = Fixture::new(Visibility::Public).await; | |
| 256 | + let (status, _, body) = get(&fx.router, &format!("/{OWNER}/{REPO}/blame/main/a.txt")).await; | |
| 257 | + assert_eq!(status, 200); | |
| 258 | + let html = String::from_utf8(body).unwrap(); | |
| 259 | + // Lines 1 and 3 came from the root commit, line 2 and 4 from the modifying commit. | |
| 260 | + assert!(html.contains("blame-meta")); | |
| 261 | + assert!(html.contains(&format!("/{OWNER}/{REPO}/commit/{}", fx.root))); | |
| 262 | + assert!(html.contains(&format!("/{OWNER}/{REPO}/commit/{}", fx.modified))); | |
| 263 | + assert!(html.contains("Modify a.txt and add new.txt")); | |
| 264 | + // The modifying commit has a parent, so it offers blame prior to it. | |
| 265 | + assert!(html.contains(&format!("/{OWNER}/{REPO}/blame/{}/a.txt", fx.root))); | |
| 266 | + assert!(html.contains("id=\"L4\"")); | |
| 267 | + } | |
| 268 | + | |
| 269 | + #[tokio::test] | |
| 270 | + async fn blame_of_a_missing_file_is_404() { | |
| 271 | + let fx = Fixture::new(Visibility::Public).await; | |
| 272 | + let (status, _, _) = get(&fx.router, &format!("/{OWNER}/{REPO}/blame/main/nope.txt")).await; | |
| 273 | + assert_eq!(status, 404); | |
| 274 | + } | |
| 275 | + | |
| 276 | + #[tokio::test] | |
| 277 | + async fn private_repo_blame_is_404_for_anonymous() { | |
| 278 | + let fx = Fixture::new(Visibility::Private).await; | |
| 279 | + let (status, _, _) = get(&fx.router, &format!("/{OWNER}/{REPO}/blame/main/a.txt")).await; | |
| 280 | + assert_eq!(status, 404); | |
| 281 | + } | |
| 282 | +} |
crates/forge-web/src/pages/blob.rsmodified+28 -3
| @@ -9,10 +9,12 @@ use topcoat::router::error::not_found; | ||
| 9 | 9 | use topcoat::router::{page, path_param, query_params}; |
| 10 | 10 | use topcoat::view::{Unescaped, View, component, view}; |
| 11 | 11 | |
| 12 | +use crate::i18n::browse as b; | |
| 12 | 13 | use crate::i18n::code::{self as g, K}; |
| 13 | 14 | use crate::i18n::{self}; |
| 14 | 15 | use crate::lfs::has_object; |
| 15 | 16 | use crate::lfs_pointer; |
| 17 | +use crate::pages::finder::file_finder; | |
| 16 | 18 | use crate::pages::media::media_url; |
| 17 | 19 | use crate::pages::repo::repo_head; |
| 18 | 20 | use crate::pages::repo_ctx::load_repo; |
| @@ -60,7 +62,7 @@ fn extension(name: &str) -> String { | ||
| 60 | 62 | .unwrap_or_default() |
| 61 | 63 | } |
| 62 | 64 | |
| 63 | -fn text_lines(text: &str, file_name: &str) -> Vec<Line> { | |
| 65 | +pub fn text_lines(text: &str, file_name: &str) -> Vec<Line> { | |
| 64 | 66 | let plain: Vec<&str> = text.lines().collect(); |
| 65 | 67 | let highlighted = highlight_lines(file_name, text).filter(|h| h.len() == plain.len()); |
| 66 | 68 | plain |
| @@ -120,7 +122,7 @@ async fn blob_page(cx: &Cx) -> Result<impl View> { | ||
| 120 | 122 | let Some((ref_name, commit, file)) = resolve(ctx.path.clone(), rest).await? else { |
| 121 | 123 | return Err(not_found().into()); |
| 122 | 124 | }; |
| 123 | - let Some(blob) = read_file(ctx.path.clone(), commit, file.clone()).await? else { | |
| 125 | + let Some(blob) = read_file(ctx.path.clone(), commit.clone(), file.clone()).await? else { | |
| 124 | 126 | return Err(not_found().into()); |
| 125 | 127 | }; |
| 126 | 128 | |
| @@ -235,11 +237,28 @@ async fn blob_page(cx: &Cx) -> Result<impl View> { | ||
| 235 | 237 | } else { |
| 236 | 238 | Some((g::t(lang, K::SourceToggle), format!("{base}?plain=1"))) |
| 237 | 239 | }; |
| 240 | + let blame = repo_href( | |
| 241 | + &repo.owner_name, | |
| 242 | + &repo.name, | |
| 243 | + "blame", | |
| 244 | + &format!("{ref_name}/{file}"), | |
| 245 | + ); | |
| 246 | + // The same file pinned to this exact commit, for sharing and for the `y` shortcut. | |
| 247 | + let permalink = repo_href( | |
| 248 | + &repo.owner_name, | |
| 249 | + &repo.name, | |
| 250 | + "blob", | |
| 251 | + &format!("{commit}/{file}"), | |
| 252 | + ); | |
| 253 | + let finder_owner = repo.owner_name.clone(); | |
| 254 | + let finder_repo = repo.name.clone(); | |
| 255 | + let finder_ref = ref_name.clone(); | |
| 238 | 256 | let crumbs: Vec<Crumb> = path_crumbs(repo, &ref_name, "blob", &file); |
| 239 | 257 | let title = format!("{}/{} \u{b7} {file}", repo.owner_name, repo.name); |
| 240 | 258 | let size = human_size(lang, blob.size); |
| 241 | 259 | |
| 242 | 260 | let kind = viewer.kind; |
| 261 | + let is_text = kind == "text"; | |
| 243 | 262 | let note = viewer.note; |
| 244 | 263 | let html = viewer.html; |
| 245 | 264 | let lines = viewer.lines; |
| @@ -254,14 +273,20 @@ async fn blob_page(cx: &Cx) -> Result<impl View> { | ||
| 254 | 273 | repo_head(head: header) |
| 255 | 274 | <div class="browse-bar"> |
| 256 | 275 | breadcrumb(lang: lang, crumbs: crumbs) |
| 276 | + file_finder(lang: lang, owner: finder_owner, repo: finder_repo, ref_name: finder_ref) | |
| 257 | 277 | </div> |
| 258 | - <section class="file"> | |
| 278 | + <section class="file" data-lines="" data-permalink=(permalink.as_str())> | |
| 259 | 279 | <header class="file-head"> |
| 260 | 280 | <span class="muted small">(size)</span> |
| 261 | 281 | <nav class="file-actions" aria-label=(g::t(lang, K::FileNav))> |
| 262 | 282 | if let Some((label, href)) = toggle { |
| 263 | 283 | <a href=(href)>(label)</a> |
| 264 | 284 | } |
| 285 | + if is_text { | |
| 286 | + <a href=(blame.as_str())>(b::t(lang, b::K::BlameLink))</a> | |
| 287 | + <button type="button" class="link-button" data-copy-permalink="" title=(b::t(lang, b::K::PermalinkHint)) | |
| 288 | + data-copied=(b::t(lang, b::K::PermalinkCopied))>(b::t(lang, b::K::CopyPermalink))</button> | |
| 289 | + } | |
| 265 | 290 | <a href=(history)>(g::t(lang, K::HistoryLink))</a> |
| 266 | 291 | <a href=(raw.clone())>(g::t(lang, K::RawLink))</a> |
| 267 | 292 | <a href=(download_href) download=(download_name)>(g::t(lang, K::DownloadLink))</a> |
crates/forge-web/src/pages/branches.rsadded+461 -0
| @@ -0,0 +1,461 @@ | ||
| 1 | +//! Branches page at `/{owner}/{repo}/branches`: every branch with its last commit, author and age, | |
| 2 | +//! ahead/behind counts against the default branch and a "New PR" link, plus creating a branch from | |
| 3 | +//! any ref and deleting one (both respect branch protection). The tags page stays in `refs`. | |
| 4 | + | |
| 5 | +use std::time::{Duration, Instant}; | |
| 6 | + | |
| 7 | +use forge_core::protection::effective; | |
| 8 | +use forge_git::branches; | |
| 9 | +use forge_git::browse::{self, RefKind}; | |
| 10 | +use serde::Deserialize; | |
| 11 | +use topcoat::Result; | |
| 12 | +use topcoat::context::{Cx, app_context}; | |
| 13 | +use topcoat::cookie::{Cookie, Cookies, SameSite, cookies}; | |
| 14 | +use topcoat::router::content::Form; | |
| 15 | +use topcoat::router::error::{SeeOther, forbidden, see_other}; | |
| 16 | +use topcoat::router::{page, path_param, route}; | |
| 17 | +use topcoat::view::{View, component, view}; | |
| 18 | + | |
| 19 | +use crate::auth::require_csrf; | |
| 20 | +use crate::i18n::browse as b; | |
| 21 | +use crate::i18n::code::{self as g, K}; | |
| 22 | +use crate::i18n::{self, Lang}; | |
| 23 | +use crate::internal::{is_zero_oid, may_push_directly}; | |
| 24 | +use crate::pages::commits::url_path; | |
| 25 | +use crate::pages::refs::ref_rows; | |
| 26 | +use crate::pages::repo::repo_head; | |
| 27 | +use crate::pages::repo_ctx::{RepoCtx, load_repo}; | |
| 28 | +use crate::pages::tree::{LastCommit, last_commit_view}; | |
| 29 | +use crate::post_update::after_ref_update; | |
| 30 | +use crate::state::AppState; | |
| 31 | +use crate::views::{alert, now_unix, relative_time, repo_href, shell}; | |
| 32 | + | |
| 33 | +path_param!(owner); | |
| 34 | +path_param!(repo); | |
| 35 | + | |
| 36 | +/// Branches that get an ahead/behind count. The rest show none. | |
| 37 | +const COUNT_LIMIT: usize = 100; | |
| 38 | +/// Time allowed for all the counts together; branches not reached show none. | |
| 39 | +const COUNT_BUDGET: Duration = Duration::from_secs(4); | |
| 40 | +/// One-shot notice cookie set by the create and delete routes. | |
| 41 | +const NOTICE_COOKIE: &str = "forge_branch_notice"; | |
| 42 | + | |
| 43 | +/// Fixed notice words: the text and whether it is an error. | |
| 44 | +const NOTICES: [(&str, b::K, bool); 11] = [ | |
| 45 | + ("created", b::K::BranchCreated, false), | |
| 46 | + ("deleted", b::K::BranchDeleted, false), | |
| 47 | + ("exists", b::K::BranchExists, true), | |
| 48 | + ("invalid", b::K::BranchInvalidName, true), | |
| 49 | + ("source", b::K::BranchSourceMissing, true), | |
| 50 | + ("default", b::K::BranchIsDefault, true), | |
| 51 | + ("protected", b::K::BranchProtectedDelete, true), | |
| 52 | + ("pull_only", b::K::BranchPullOnly, true), | |
| 53 | + ("gone", b::K::BranchGone, true), | |
| 54 | + ("failed", b::K::BranchFailed, true), | |
| 55 | + ("forbidden", b::K::BranchForbidden, true), | |
| 56 | +]; | |
| 57 | + | |
| 58 | +fn set_notice(cx: &Cx, word: &'static str) { | |
| 59 | + cookies(cx).add( | |
| 60 | + Cookie::build((NOTICE_COOKIE, word)) | |
| 61 | + .path("/") | |
| 62 | + .http_only(true) | |
| 63 | + .same_site(SameSite::Lax) | |
| 64 | + .build(), | |
| 65 | + ); | |
| 66 | +} | |
| 67 | + | |
| 68 | +/// Reads and clears the notice cookie. Only the fixed words are shown. | |
| 69 | +fn take_notice(cx: &Cx) -> Option<(b::K, bool)> { | |
| 70 | + let jar = cookies(cx); | |
| 71 | + let value = jar.get(NOTICE_COOKIE)?.value().to_owned(); | |
| 72 | + jar.remove(Cookie::build((NOTICE_COOKIE, "")).path("/")); | |
| 73 | + NOTICES | |
| 74 | + .iter() | |
| 75 | + .find(|(word, _, _)| *word == value) | |
| 76 | + .map(|(_, key, is_error)| (*key, *is_error)) | |
| 77 | +} | |
| 78 | + | |
| 79 | +fn branches_href(ctx: &RepoCtx) -> String { | |
| 80 | + repo_href(&ctx.repo.owner_name, &ctx.repo.name, "branches", "") | |
| 81 | +} | |
| 82 | + | |
| 83 | +/// One row of the branches table. | |
| 84 | +struct BranchRow { | |
| 85 | + name: String, | |
| 86 | + href: String, | |
| 87 | + oid: String, | |
| 88 | + is_default: bool, | |
| 89 | + last: Option<LastCommit>, | |
| 90 | + author: String, | |
| 91 | + age: String, | |
| 92 | + /// "3 ahead, 1 behind", or None when not counted. | |
| 93 | + counts: Option<String>, | |
| 94 | + up_to_date: bool, | |
| 95 | + pr_href: Option<String>, | |
| 96 | + delete_label: String, | |
| 97 | +} | |
| 98 | + | |
| 99 | +#[component] | |
| 100 | +async fn new_branch_form( | |
| 101 | + lang: Lang, | |
| 102 | + action: String, | |
| 103 | + csrf: String, | |
| 104 | + default_branch: String, | |
| 105 | + options: Vec<String>, | |
| 106 | +) -> Result<impl View> { | |
| 107 | + Ok(view! { | |
| 108 | + <details class="new-branch"> | |
| 109 | + <summary class="button">(b::t(lang, b::K::NewBranchTitle))</summary> | |
| 110 | + <form method="post" action=(action.as_str()) class="new-branch-form"> | |
| 111 | + <input type="hidden" name="csrf" value=(csrf.as_str())> | |
| 112 | + <label> | |
| 113 | + <span>(b::t(lang, b::K::BranchNameLabel))</span> | |
| 114 | + <input type="text" name="name" required=(true) autocomplete="off" spellcheck="false" maxlength="200"> | |
| 115 | + </label> | |
| 116 | + <label> | |
| 117 | + <span>(b::t(lang, b::K::BranchFromLabel))</span> | |
| 118 | + <input type="text" name="from" list="branch-sources" value=(default_branch.as_str()) | |
| 119 | + placeholder=(b::t(lang, b::K::BranchFromPlaceholder)) autocomplete="off" spellcheck="false"> | |
| 120 | + </label> | |
| 121 | + <datalist id="branch-sources"> | |
| 122 | + for option in options.iter() { | |
| 123 | + <option value=(option.as_str())></option> | |
| 124 | + } | |
| 125 | + </datalist> | |
| 126 | + <button type="submit" class="primary">(b::t(lang, b::K::CreateBranch))</button> | |
| 127 | + </form> | |
| 128 | + </details> | |
| 129 | + }) | |
| 130 | +} | |
| 131 | + | |
| 132 | +#[component] | |
| 133 | +async fn branch_table( | |
| 134 | + rows: Vec<BranchRow>, | |
| 135 | + lang: Lang, | |
| 136 | + csrf: String, | |
| 137 | + delete_action: String, | |
| 138 | + can_delete: bool, | |
| 139 | +) -> Result<impl View> { | |
| 140 | + Ok(view! { | |
| 141 | + <div class="table-wrap"> | |
| 142 | + <table class="table refs-table branch-table"> | |
| 143 | + <thead> | |
| 144 | + <tr> | |
| 145 | + <th>(g::t(lang, K::BranchLabel))</th> | |
| 146 | + <th>(g::t(lang, K::LastCommitHeader))</th> | |
| 147 | + <th>(b::t(lang, b::K::BranchAuthorHeader))</th> | |
| 148 | + <th>(b::t(lang, b::K::BranchAheadBehindHeader))</th> | |
| 149 | + <th class="branch-actions-col">(b::t(lang, b::K::BranchActionsHeader))</th> | |
| 150 | + </tr> | |
| 151 | + </thead> | |
| 152 | + <tbody> | |
| 153 | + for row in rows.into_iter() { | |
| 154 | + <tr> | |
| 155 | + <td class="tree-name"> | |
| 156 | + <span class="tree-label"> | |
| 157 | + <a href=(row.href.as_str())>(row.name.as_str())</a> | |
| 158 | + if row.is_default { | |
| 159 | + <span class="badge public">(g::t(lang, K::DefaultBadge))</span> | |
| 160 | + } | |
| 161 | + </span> | |
| 162 | + </td> | |
| 163 | + if let Some(last) = row.last { | |
| 164 | + <td class="tree-commit"><a href=(last.href.as_str())>(last.summary.as_str())</a></td> | |
| 165 | + } else { | |
| 166 | + <td class="tree-commit"></td> | |
| 167 | + } | |
| 168 | + <td class="branch-author"> | |
| 169 | + <span>(row.author.as_str())</span> | |
| 170 | + <span class="muted small">(row.age.as_str())</span> | |
| 171 | + </td> | |
| 172 | + <td class="branch-counts"> | |
| 173 | + if let Some(counts) = row.counts { | |
| 174 | + <span class="small">(counts.as_str())</span> | |
| 175 | + } else if row.up_to_date { | |
| 176 | + <span class="muted small">(b::t(lang, b::K::UpToDate))</span> | |
| 177 | + } | |
| 178 | + </td> | |
| 179 | + <td class="branch-actions"> | |
| 180 | + if let Some(pr) = row.pr_href { | |
| 181 | + <a class="button small" href=(pr.as_str())>(b::t(lang, b::K::NewPr))</a> | |
| 182 | + } | |
| 183 | + if can_delete && !row.is_default { | |
| 184 | + <details class="confirm-inline"> | |
| 185 | + <summary class="button small danger" aria-label=(row.delete_label.as_str())>(b::t(lang, b::K::DeleteBranch))</summary> | |
| 186 | + <div class="confirm-pop"> | |
| 187 | + <p>(b::t(lang, b::K::DeleteConfirm))</p> | |
| 188 | + <form method="post" action=(delete_action.as_str())> | |
| 189 | + <input type="hidden" name="csrf" value=(csrf.as_str())> | |
| 190 | + <input type="hidden" name="name" value=(row.name.as_str())> | |
| 191 | + <input type="hidden" name="oid" value=(row.oid.as_str())> | |
| 192 | + <button type="submit" class="danger">(b::t(lang, b::K::DeleteConfirmYes))</button> | |
| 193 | + <button type="button" data-close-details="">(b::t(lang, b::K::DeleteCancel))</button> | |
| 194 | + </form> | |
| 195 | + </div> | |
| 196 | + </details> | |
| 197 | + } | |
| 198 | + </td> | |
| 199 | + </tr> | |
| 200 | + } | |
| 201 | + </tbody> | |
| 202 | + </table> | |
| 203 | + </div> | |
| 204 | + }) | |
| 205 | +} | |
| 206 | + | |
| 207 | +#[page("/{owner}/{repo}/branches")] | |
| 208 | +async fn branches_page(cx: &Cx) -> Result<impl View> { | |
| 209 | + let owner = path_param::<Owner>(cx); | |
| 210 | + let name = path_param::<Repo>(cx); | |
| 211 | + let ctx = load_repo(cx, owner, name).await?; | |
| 212 | + let state = app_context::<AppState>(cx); | |
| 213 | + let lang = i18n::lang(cx, ctx.viewer.as_ref().map(|(user, _)| user)); | |
| 214 | + let repo = &ctx.repo; | |
| 215 | + let now = now_unix(); | |
| 216 | + | |
| 217 | + let raw = ref_rows(ctx.path.clone(), RefKind::Branch, repo).await?; | |
| 218 | + let default_tip = raw | |
| 219 | + .iter() | |
| 220 | + .find(|(r, _)| r.name == repo.default_branch) | |
| 221 | + .map(|(r, _)| r.target.clone()); | |
| 222 | + let signed_in = ctx.viewer.is_some(); | |
| 223 | + let can_write = ctx.can_write(); | |
| 224 | + | |
| 225 | + let started = Instant::now(); | |
| 226 | + let mut rows = Vec::with_capacity(raw.len()); | |
| 227 | + let mut options = Vec::new(); | |
| 228 | + for (index, (info, commit)) in raw.into_iter().enumerate() { | |
| 229 | + options.push(info.name.clone()); | |
| 230 | + let is_default = info.name == repo.default_branch; | |
| 231 | + let mut counts = None; | |
| 232 | + let mut up_to_date = false; | |
| 233 | + let mut pr_href = None; | |
| 234 | + if !is_default && let Some(base) = default_tip.as_deref() { | |
| 235 | + let counted = if index < COUNT_LIMIT && started.elapsed() < COUNT_BUDGET { | |
| 236 | + branches::ahead_behind(&state.git, &ctx.path, base, &info.target) | |
| 237 | + .await | |
| 238 | + .ok() | |
| 239 | + } else { | |
| 240 | + None | |
| 241 | + }; | |
| 242 | + match counted { | |
| 243 | + Some((0, 0)) => up_to_date = true, | |
| 244 | + Some((ahead, behind)) => counts = Some(b::ahead_behind(lang, ahead, behind)), | |
| 245 | + None => {} | |
| 246 | + } | |
| 247 | + let has_commits = counted.is_none_or(|(ahead, _)| ahead > 0); | |
| 248 | + if signed_in && !repo.archived && has_commits { | |
| 249 | + pr_href = Some(repo_href( | |
| 250 | + &repo.owner_name, | |
| 251 | + &repo.name, | |
| 252 | + "compare", | |
| 253 | + &url_path(&format!("{}...{}", repo.default_branch, info.name)), | |
| 254 | + )); | |
| 255 | + } | |
| 256 | + } | |
| 257 | + rows.push(BranchRow { | |
| 258 | + href: repo_href(&repo.owner_name, &repo.name, "tree", &info.name), | |
| 259 | + oid: info.target.clone(), | |
| 260 | + is_default, | |
| 261 | + last: commit | |
| 262 | + .as_ref() | |
| 263 | + .map(|c| last_commit_view(lang, repo, c, now, ctx.viewer_tz())), | |
| 264 | + author: commit | |
| 265 | + .as_ref() | |
| 266 | + .map(|c| c.author_name.clone()) | |
| 267 | + .unwrap_or_default(), | |
| 268 | + age: commit | |
| 269 | + .as_ref() | |
| 270 | + .map(|c| relative_time(lang, c.author_time, now)) | |
| 271 | + .unwrap_or_default(), | |
| 272 | + counts, | |
| 273 | + up_to_date, | |
| 274 | + pr_href, | |
| 275 | + delete_label: b::delete_aria(lang, &info.name), | |
| 276 | + name: info.name, | |
| 277 | + }); | |
| 278 | + } | |
| 279 | + | |
| 280 | + let notice = take_notice(cx); | |
| 281 | + let csrf = ctx | |
| 282 | + .viewer | |
| 283 | + .as_ref() | |
| 284 | + .map(|(_, session)| session.csrf_token.clone()) | |
| 285 | + .unwrap_or_default(); | |
| 286 | + let action = branches_href(&ctx); | |
| 287 | + let delete_action = format!("{action}/delete"); | |
| 288 | + let default_branch = repo.default_branch.clone(); | |
| 289 | + let title = format!( | |
| 290 | + "{}/{} \u{b7} {}", | |
| 291 | + repo.owner_name, | |
| 292 | + repo.name, | |
| 293 | + g::t(lang, K::BranchesTitle) | |
| 294 | + ); | |
| 295 | + let empty = rows.is_empty(); | |
| 296 | + let header = ctx.head(state, "branches").await?; | |
| 297 | + Ok(view! { | |
| 298 | + shell(title: title.as_str(), viewer: ctx.viewer.as_ref(), | |
| 299 | + repo_head(head: header) | |
| 300 | + if let Some((key, is_error)) = notice { | |
| 301 | + if is_error { | |
| 302 | + alert(message: b::t(lang, key)) | |
| 303 | + } else { | |
| 304 | + <p class="notice" role="status">(b::t(lang, key))</p> | |
| 305 | + } | |
| 306 | + } | |
| 307 | + if can_write { | |
| 308 | + new_branch_form(lang: lang, action: action.clone(), csrf: csrf.clone(), | |
| 309 | + default_branch: default_branch, options: options) | |
| 310 | + } | |
| 311 | + if empty { | |
| 312 | + <p class="muted">(g::t(lang, K::NothingHere))</p> | |
| 313 | + } else { | |
| 314 | + branch_table(rows: rows, lang: lang, csrf: csrf.clone(), delete_action: delete_action, can_delete: can_write) | |
| 315 | + } | |
| 316 | + ) | |
| 317 | + }) | |
| 318 | +} | |
| 319 | + | |
| 320 | +#[derive(Deserialize)] | |
| 321 | +struct CreateForm { | |
| 322 | + #[serde(default)] | |
| 323 | + csrf: String, | |
| 324 | + #[serde(default)] | |
| 325 | + name: String, | |
| 326 | + #[serde(default)] | |
| 327 | + from: String, | |
| 328 | +} | |
| 329 | + | |
| 330 | +#[derive(Deserialize)] | |
| 331 | +struct DeleteForm { | |
| 332 | + #[serde(default)] | |
| 333 | + csrf: String, | |
| 334 | + #[serde(default)] | |
| 335 | + name: String, | |
| 336 | + #[serde(default)] | |
| 337 | + oid: String, | |
| 338 | +} | |
| 339 | + | |
| 340 | +fn back(cx: &Cx, ctx: &RepoCtx, word: &'static str) -> SeeOther { | |
| 341 | + set_notice(cx, word); | |
| 342 | + see_other(branches_href(ctx)) | |
| 343 | +} | |
| 344 | + | |
| 345 | +/// Creates `name` at the tip of `from` (a branch, tag or commit; the default branch when empty). | |
| 346 | +/// A protection rule that only accepts pull requests keeps the name closed to direct creation. | |
| 347 | +#[route(POST "/{owner}/{repo}/branches")] | |
| 348 | +async fn branch_create(cx: &Cx, Form(form): Form<CreateForm>) -> Result<SeeOther> { | |
| 349 | + let owner = path_param::<Owner>(cx); | |
| 350 | + let name = path_param::<Repo>(cx); | |
| 351 | + let ctx = load_repo(cx, owner, name).await?; | |
| 352 | + let (user, _) = require_csrf(cx, &form.csrf).await?; | |
| 353 | + if !ctx.can_write() { | |
| 354 | + return Err(forbidden().into()); | |
| 355 | + } | |
| 356 | + let state = app_context::<AppState>(cx); | |
| 357 | + let branch = form.name.trim().to_owned(); | |
| 358 | + let from = match form.from.trim() { | |
| 359 | + "" => ctx.repo.default_branch.clone(), | |
| 360 | + other => other.to_owned(), | |
| 361 | + }; | |
| 362 | + | |
| 363 | + let rules = state.store.list_branch_rules(&ctx.repo.id).await?; | |
| 364 | + let protection = effective(&rules, &ctx.repo.default_branch, &branch); | |
| 365 | + if protection.restrict_push && !may_push_directly(&state.store, &ctx.repo, &user.id).await? { | |
| 366 | + return Ok(back(cx, &ctx, "pull_only")); | |
| 367 | + } | |
| 368 | + | |
| 369 | + let path = ctx.path.clone(); | |
| 370 | + let lookup = from.clone(); | |
| 371 | + let source = | |
| 372 | + tokio::task::spawn_blocking(move || browse::resolve_commit(&path, &lookup)).await??; | |
| 373 | + let Some(oid) = source else { | |
| 374 | + return Ok(back(cx, &ctx, "source")); | |
| 375 | + }; | |
| 376 | + let path = ctx.path.clone(); | |
| 377 | + let probe = branch.clone(); | |
| 378 | + let existing = | |
| 379 | + tokio::task::spawn_blocking(move || browse::default_branch_commit(&path, &probe)).await??; | |
| 380 | + if existing.is_some() { | |
| 381 | + return Ok(back(cx, &ctx, "exists")); | |
| 382 | + } | |
| 383 | + match branches::create_branch(&state.git, &ctx.path, &branch, &oid).await { | |
| 384 | + Ok(()) => {} | |
| 385 | + Err(forge_git::Error::InvalidInput(_)) => return Ok(back(cx, &ctx, "invalid")), | |
| 386 | + Err(e) => { | |
| 387 | + tracing::warn!(error = %e, repo_id = %ctx.repo.id, "branch create failed"); | |
| 388 | + return Ok(back(cx, &ctx, "failed")); | |
| 389 | + } | |
| 390 | + } | |
| 391 | + tracing::info!( | |
| 392 | + actor_id = %user.id, | |
| 393 | + repo_id = %ctx.repo.id, | |
| 394 | + branch = %branch, | |
| 395 | + "branch created from the branches page" | |
| 396 | + ); | |
| 397 | + let zero = "0".repeat(oid.len()); | |
| 398 | + let refname = format!("refs/heads/{branch}"); | |
| 399 | + if let Err(e) = after_ref_update(state, &ctx.repo, &user.id, &refname, &zero, &oid).await { | |
| 400 | + tracing::error!(error = %e, "post-update work after branch create failed"); | |
| 401 | + } | |
| 402 | + Ok(back(cx, &ctx, "created")) | |
| 403 | +} | |
| 404 | + | |
| 405 | +/// Deletes a branch if it still points at the commit the page showed. The default branch and | |
| 406 | +/// branches whose protection forbids deletion are refused. | |
| 407 | +#[route(POST "/{owner}/{repo}/branches/delete")] | |
| 408 | +async fn branch_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<SeeOther> { | |
| 409 | + let owner = path_param::<Owner>(cx); | |
| 410 | + let name = path_param::<Repo>(cx); | |
| 411 | + let ctx = load_repo(cx, owner, name).await?; | |
| 412 | + let (user, _) = require_csrf(cx, &form.csrf).await?; | |
| 413 | + if !ctx.can_write() { | |
| 414 | + return Err(forbidden().into()); | |
| 415 | + } | |
| 416 | + let state = app_context::<AppState>(cx); | |
| 417 | + let branch = form.name.trim().to_owned(); | |
| 418 | + if branch == ctx.repo.default_branch { | |
| 419 | + return Ok(back(cx, &ctx, "default")); | |
| 420 | + } | |
| 421 | + let rules = state.store.list_branch_rules(&ctx.repo.id).await?; | |
| 422 | + let protection = effective(&rules, &ctx.repo.default_branch, &branch); | |
| 423 | + if protection.restrict_push && !may_push_directly(&state.store, &ctx.repo, &user.id).await? { | |
| 424 | + return Ok(back(cx, &ctx, "pull_only")); | |
| 425 | + } | |
| 426 | + if !protection.allow_deletion { | |
| 427 | + return Ok(back(cx, &ctx, "protected")); | |
| 428 | + } | |
| 429 | + | |
| 430 | + let path = ctx.path.clone(); | |
| 431 | + let probe = branch.clone(); | |
| 432 | + let tip = | |
| 433 | + tokio::task::spawn_blocking(move || browse::default_branch_commit(&path, &probe)).await??; | |
| 434 | + let Some(tip) = tip else { | |
| 435 | + return Ok(back(cx, &ctx, "gone")); | |
| 436 | + }; | |
| 437 | + // The page named the commit it showed; a branch that moved since is left alone. | |
| 438 | + if form.oid != tip || is_zero_oid(&form.oid) { | |
| 439 | + return Ok(back(cx, &ctx, "gone")); | |
| 440 | + } | |
| 441 | + match branches::delete_branch(&state.git, &ctx.path, &branch, &tip).await { | |
| 442 | + Ok(()) => {} | |
| 443 | + Err(forge_git::Error::RefMoved(_)) => return Ok(back(cx, &ctx, "gone")), | |
| 444 | + Err(e) => { | |
| 445 | + tracing::warn!(error = %e, repo_id = %ctx.repo.id, "branch delete failed"); | |
| 446 | + return Ok(back(cx, &ctx, "failed")); | |
| 447 | + } | |
| 448 | + } | |
| 449 | + tracing::info!( | |
| 450 | + actor_id = %user.id, | |
| 451 | + repo_id = %ctx.repo.id, | |
| 452 | + branch = %branch, | |
| 453 | + "branch deleted from the branches page" | |
| 454 | + ); | |
| 455 | + let zero = "0".repeat(tip.len()); | |
| 456 | + let refname = format!("refs/heads/{branch}"); | |
| 457 | + if let Err(e) = after_ref_update(state, &ctx.repo, &user.id, &refname, &tip, &zero).await { | |
| 458 | + tracing::error!(error = %e, "post-update work after branch delete failed"); | |
| 459 | + } | |
| 460 | + Ok(back(cx, &ctx, "deleted")) | |
| 461 | +} |
crates/forge-web/src/pages/browse_tests.rsadded+504 -0
| @@ -0,0 +1,504 @@ | ||
| 1 | +//! Page tests for the code-browsing upgrades: diff toolbar, whitespace and split views, patch and | |
| 2 | +//! diff downloads, the file list endpoint, the branches page and the default-branch setting. | |
| 3 | + | |
| 4 | +use forge_core::Visibility; | |
| 5 | +use forge_core::protection::RuleFlags; | |
| 6 | +use topcoat::router::request::Request; | |
| 7 | +use topcoat::router::{Body, Router, to_bytes}; | |
| 8 | + | |
| 9 | +use crate::auth::SESSION_COOKIE; | |
| 10 | +use crate::pages::commits::test_support::{Fixture, OWNER, REPO, get, git}; | |
| 11 | +use crate::test_support::create_session; | |
| 12 | + | |
| 13 | +const CSRF: &str = "browse-csrf"; | |
| 14 | + | |
| 15 | +async fn sign_in_owner(fx: &Fixture) -> String { | |
| 16 | + let owner = fx.store.user_by_username(OWNER).await.unwrap().unwrap(); | |
| 17 | + create_session(&fx.store, &owner.id, "owner-token", CSRF).await; | |
| 18 | + format!("__Host-{SESSION_COOKIE}=owner-token") | |
| 19 | +} | |
| 20 | + | |
| 21 | +async fn send( | |
| 22 | + router: &Router, | |
| 23 | + method: &str, | |
| 24 | + uri: &str, | |
| 25 | + cookie: Option<&str>, | |
| 26 | + fields: &[(&str, &str)], | |
| 27 | +) -> (u16, http::HeaderMap, String) { | |
| 28 | + let mut form = form_urlencoded::Serializer::new(String::new()); | |
| 29 | + for (k, v) in fields { | |
| 30 | + form.append_pair(k, v); | |
| 31 | + } | |
| 32 | + let mut req = Request::builder().method(method).uri(uri); | |
| 33 | + if let Some(cookie) = cookie { | |
| 34 | + req = req.header("cookie", cookie); | |
| 35 | + } | |
| 36 | + if method == "POST" { | |
| 37 | + req = req.header("content-type", "application/x-www-form-urlencoded"); | |
| 38 | + } | |
| 39 | + let res = router | |
| 40 | + .handle(req.body(Body::from(form.finish())).unwrap()) | |
| 41 | + .await; | |
| 42 | + let status = res.status().as_u16(); | |
| 43 | + let headers = res.headers().clone(); | |
| 44 | + let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap(); | |
| 45 | + ( | |
| 46 | + status, | |
| 47 | + headers, | |
| 48 | + String::from_utf8_lossy(&bytes).into_owned(), | |
| 49 | + ) | |
| 50 | +} | |
| 51 | + | |
| 52 | +/// A commit whose changes are a whitespace-only edit of `a.txt` and a real edit of `ws.txt`. | |
| 53 | +fn whitespace_commit(fx: &Fixture) -> String { | |
| 54 | + std::fs::write(fx.work.join("ws.txt"), "x\ny\n").unwrap(); | |
| 55 | + git(&fx.work, &["add", "-A"]); | |
| 56 | + git(&fx.work, &["commit", "-q", "-m", "add ws"]); | |
| 57 | + std::fs::write(fx.work.join("ws.txt"), "x\ny\nz\n").unwrap(); | |
| 58 | + std::fs::write(fx.work.join("a.txt"), "one \nTWO\nthree\nfour\n").unwrap(); | |
| 59 | + git(&fx.work, &["add", "-A"]); | |
| 60 | + git(&fx.work, &["commit", "-q", "-m", "tabs and spaces"]); | |
| 61 | + let oid = git(&fx.work, &["rev-parse", "HEAD"]); | |
| 62 | + git( | |
| 63 | + &fx.work, | |
| 64 | + &[ | |
| 65 | + "push", | |
| 66 | + "-q", | |
| 67 | + &fx.bare.to_string_lossy(), | |
| 68 | + "HEAD:refs/heads/main", | |
| 69 | + ], | |
| 70 | + ); | |
| 71 | + oid | |
| 72 | +} | |
| 73 | + | |
| 74 | +#[tokio::test] | |
| 75 | +async fn commit_page_has_toolbar_and_ignores_whitespace() { | |
| 76 | + let fx = Fixture::new(Visibility::Public).await; | |
| 77 | + let oid = whitespace_commit(&fx); | |
| 78 | + let base = format!("/{OWNER}/{REPO}/commit/{oid}"); | |
| 79 | + | |
| 80 | + let (status, _, body) = get(&fx.router, &base).await; | |
| 81 | + assert_eq!(status, 200); | |
| 82 | + let html = String::from_utf8(body).unwrap(); | |
| 83 | + assert!(html.contains("diff-toolbar")); | |
| 84 | + assert!(html.contains(&format!("{base}.patch"))); | |
| 85 | + assert!(html.contains(&format!("{base}.diff"))); | |
| 86 | + assert!(html.contains("a.txt")); | |
| 87 | + assert!(html.contains("ws.txt")); | |
| 88 | + // The toggle links to the same page with w=1. | |
| 89 | + assert!(html.contains("w=1")); | |
| 90 | + | |
| 91 | + let (_, _, body) = get(&fx.router, &format!("{base}?w=1")).await; | |
| 92 | + let html = String::from_utf8(body).unwrap(); | |
| 93 | + let main = html.split_once("<main").unwrap().1; | |
| 94 | + assert!( | |
| 95 | + !main.contains("diff-path\">a.txt"), | |
| 96 | + "whitespace-only file is hidden" | |
| 97 | + ); | |
| 98 | + assert!(main.contains("ws.txt")); | |
| 99 | + assert!(main.contains("aria-pressed=\"true\"")); | |
| 100 | +} | |
| 101 | + | |
| 102 | +#[tokio::test] | |
| 103 | +async fn split_view_renders_two_sides_and_is_remembered() { | |
| 104 | + let fx = Fixture::new(Visibility::Public).await; | |
| 105 | + let uri = format!("/{OWNER}/{REPO}/commit/{}?view=split", fx.modified); | |
| 106 | + | |
| 107 | + let (status, headers, body) = get(&fx.router, &uri).await; | |
| 108 | + assert_eq!(status, 200); | |
| 109 | + let html = String::from_utf8(body).unwrap(); | |
| 110 | + assert!(html.contains("diff-split")); | |
| 111 | + assert!(html.contains("diff-split-row")); | |
| 112 | + // The deleted "two" and the added "TWO" sit in one row. | |
| 113 | + let row = html | |
| 114 | + .split("diff-split-row") | |
| 115 | + .find(|r| r.contains("-two") && r.contains("+TWO")) | |
| 116 | + .expect("paired row"); | |
| 117 | + assert!(row.contains("side-del") && row.contains("side-add")); | |
| 118 | + let cookie = headers | |
| 119 | + .get_all("set-cookie") | |
| 120 | + .iter() | |
| 121 | + .filter_map(|v| v.to_str().ok()) | |
| 122 | + .find(|v| v.starts_with("forge_diff=")) | |
| 123 | + .expect("view cookie"); | |
| 124 | + assert!(cookie.starts_with("forge_diff=split")); | |
| 125 | + | |
| 126 | + // With the cookie and no query, the page is split; ?view=unified switches back. | |
| 127 | + let plain = format!("/{OWNER}/{REPO}/commit/{}", fx.modified); | |
| 128 | + let req = Request::builder() | |
| 129 | + .method("GET") | |
| 130 | + .uri(&plain) | |
| 131 | + .header("cookie", "forge_diff=split") | |
| 132 | + .body(Body::empty()) | |
| 133 | + .unwrap(); | |
| 134 | + let res = fx.router.handle(req).await; | |
| 135 | + let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap(); | |
| 136 | + assert!(String::from_utf8_lossy(&bytes).contains("diff-split-row")); | |
| 137 | + let (_, _, body) = get(&fx.router, &format!("{plain}?view=unified")).await; | |
| 138 | + assert!(!String::from_utf8(body).unwrap().contains("diff-split-row")); | |
| 139 | +} | |
| 140 | + | |
| 141 | +#[tokio::test] | |
| 142 | +async fn patch_and_diff_downloads() { | |
| 143 | + let fx = Fixture::new(Visibility::Public).await; | |
| 144 | + let base = format!("/{OWNER}/{REPO}/commit/{}", fx.modified); | |
| 145 | + | |
| 146 | + let (status, headers, body) = get(&fx.router, &format!("{base}.patch")).await; | |
| 147 | + assert_eq!(status, 200); | |
| 148 | + assert!( | |
| 149 | + headers["content-type"] | |
| 150 | + .to_str() | |
| 151 | + .unwrap() | |
| 152 | + .starts_with("text/plain") | |
| 153 | + ); | |
| 154 | + let text = String::from_utf8(body).unwrap(); | |
| 155 | + assert!(text.starts_with(&format!("From {} ", fx.modified))); | |
| 156 | + assert!(text.contains("Subject: [PATCH] Modify a.txt and add new.txt")); | |
| 157 | + assert!(text.contains("+TWO")); | |
| 158 | + | |
| 159 | + let (status, _, body) = get(&fx.router, &format!("{base}.diff")).await; | |
| 160 | + assert_eq!(status, 200); | |
| 161 | + let text = String::from_utf8(body).unwrap(); | |
| 162 | + assert!(text.starts_with("diff --git a/a.txt b/a.txt")); | |
| 163 | + assert!(!text.contains("Subject:")); | |
| 164 | + | |
| 165 | + // Root commits work, and a private repo hides both downloads. | |
| 166 | + let (status, _, _) = get( | |
| 167 | + &fx.router, | |
| 168 | + &format!("/{OWNER}/{REPO}/commit/{}.patch", fx.root), | |
| 169 | + ) | |
| 170 | + .await; | |
| 171 | + assert_eq!(status, 200); | |
| 172 | + let (status, _, _) = get(&fx.router, &format!("/{OWNER}/{REPO}/commit/zzzz.patch")).await; | |
| 173 | + assert_eq!(status, 404); | |
| 174 | + let private = Fixture::new(Visibility::Private).await; | |
| 175 | + let (status, _, _) = get( | |
| 176 | + &private.router, | |
| 177 | + &format!("/{OWNER}/{REPO}/commit/{}.patch", private.root), | |
| 178 | + ) | |
| 179 | + .await; | |
| 180 | + assert_eq!(status, 404); | |
| 181 | +} | |
| 182 | + | |
| 183 | +#[tokio::test] | |
| 184 | +async fn compare_patch_lists_commits_of_the_head_side() { | |
| 185 | + let fx = Fixture::new(Visibility::Public).await; | |
| 186 | + git(&fx.work, &["checkout", "-q", "-b", "topic", &fx.root]); | |
| 187 | + std::fs::write(fx.work.join("topic.txt"), "topic\n").unwrap(); | |
| 188 | + git(&fx.work, &["add", "-A"]); | |
| 189 | + git(&fx.work, &["commit", "-q", "-m", "topic work"]); | |
| 190 | + git( | |
| 191 | + &fx.work, | |
| 192 | + &[ | |
| 193 | + "push", | |
| 194 | + "-q", | |
| 195 | + &fx.bare.to_string_lossy(), | |
| 196 | + "HEAD:refs/heads/topic", | |
| 197 | + ], | |
| 198 | + ); | |
| 199 | + let spec = format!("/{OWNER}/{REPO}/compare/main...topic"); | |
| 200 | + | |
| 201 | + let (status, _, body) = get(&fx.router, &spec).await; | |
| 202 | + assert_eq!(status, 200); | |
| 203 | + let html = String::from_utf8(body).unwrap(); | |
| 204 | + assert!(html.contains(&format!("{spec}.patch"))); | |
| 205 | + | |
| 206 | + let (status, _, body) = get(&fx.router, &format!("{spec}.patch")).await; | |
| 207 | + assert_eq!(status, 200); | |
| 208 | + let text = String::from_utf8(body).unwrap(); | |
| 209 | + assert!(text.contains("Subject: [PATCH] topic work")); | |
| 210 | + assert!(!text.contains("Modify a.txt")); | |
| 211 | + | |
| 212 | + let (status, _, body) = get(&fx.router, &format!("{spec}.diff")).await; | |
| 213 | + assert_eq!(status, 200); | |
| 214 | + let text = String::from_utf8(body).unwrap(); | |
| 215 | + assert!(text.contains("+++ b/topic.txt")); | |
| 216 | +} | |
| 217 | + | |
| 218 | +#[tokio::test] | |
| 219 | +async fn blob_page_offers_blame_permalink_and_finder() { | |
| 220 | + let fx = Fixture::new(Visibility::Public).await; | |
| 221 | + let (status, _, body) = get(&fx.router, &format!("/{OWNER}/{REPO}/blob/main/a.txt")).await; | |
| 222 | + assert_eq!(status, 200); | |
| 223 | + let html = String::from_utf8(body).unwrap(); | |
| 224 | + assert!(html.contains(&format!("/{OWNER}/{REPO}/blame/main/a.txt"))); | |
| 225 | + assert!(html.contains("data-copy-permalink")); | |
| 226 | + // The permalink is pinned to a full commit oid, not the branch. | |
| 227 | + let permalink = html | |
| 228 | + .split("data-permalink=\"") | |
| 229 | + .nth(1) | |
| 230 | + .and_then(|rest| rest.split('"').next()) | |
| 231 | + .expect("permalink attribute"); | |
| 232 | + let oid = permalink | |
| 233 | + .strip_prefix(&format!("/{OWNER}/{REPO}/blob/")) | |
| 234 | + .and_then(|rest| rest.strip_suffix("/a.txt")) | |
| 235 | + .expect("permalink shape"); | |
| 236 | + assert_eq!(oid.len(), 40); | |
| 237 | + assert!(oid.bytes().all(|b| b.is_ascii_hexdigit())); | |
| 238 | + assert!(html.contains("data-finder")); | |
| 239 | + assert!(html.contains(&format!("/{OWNER}/{REPO}/paths/main"))); | |
| 240 | + | |
| 241 | + // The tree page has the finder too. | |
| 242 | + let (_, _, body) = get(&fx.router, &format!("/{OWNER}/{REPO}/tree/main")).await; | |
| 243 | + assert!(String::from_utf8(body).unwrap().contains("data-finder")); | |
| 244 | +} | |
| 245 | + | |
| 246 | +#[tokio::test] | |
| 247 | +async fn paths_endpoint_lists_every_file() { | |
| 248 | + let fx = Fixture::new(Visibility::Public).await; | |
| 249 | + let (status, headers, body) = get(&fx.router, &format!("/{OWNER}/{REPO}/paths/main")).await; | |
| 250 | + assert_eq!(status, 200); | |
| 251 | + assert!( | |
| 252 | + headers["content-type"] | |
| 253 | + .to_str() | |
| 254 | + .unwrap() | |
| 255 | + .starts_with("application/json") | |
| 256 | + ); | |
| 257 | + let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); | |
| 258 | + let paths: Vec<&str> = json["paths"] | |
| 259 | + .as_array() | |
| 260 | + .unwrap() | |
| 261 | + .iter() | |
| 262 | + .map(|p| p.as_str().unwrap()) | |
| 263 | + .collect(); | |
| 264 | + assert_eq!(paths, ["a.txt", "dir/b.txt", "new.txt"]); | |
| 265 | + assert_eq!(json["truncated"], false); | |
| 266 | + assert_eq!(json["ref"], "main"); | |
| 267 | + | |
| 268 | + let (status, _, _) = get(&fx.router, &format!("/{OWNER}/{REPO}/paths/nope")).await; | |
| 269 | + assert_eq!(status, 404); | |
| 270 | + let (status, _, _) = get(&fx.router, &format!("/{OWNER}/{REPO}/paths/main/dir")).await; | |
| 271 | + assert_eq!(status, 404); | |
| 272 | + let private = Fixture::new(Visibility::Private).await; | |
| 273 | + let (status, _, _) = get(&private.router, &format!("/{OWNER}/{REPO}/paths/main")).await; | |
| 274 | + assert_eq!(status, 404); | |
| 275 | +} | |
| 276 | + | |
| 277 | +#[tokio::test] | |
| 278 | +async fn branches_page_shows_counts_and_creates_and_deletes() { | |
| 279 | + let fx = Fixture::new(Visibility::Public).await; | |
| 280 | + git(&fx.work, &["checkout", "-q", "-b", "feature", &fx.root]); | |
| 281 | + std::fs::write(fx.work.join("f.txt"), "f\n").unwrap(); | |
| 282 | + git(&fx.work, &["add", "-A"]); | |
| 283 | + git(&fx.work, &["commit", "-q", "-m", "feature work"]); | |
| 284 | + git( | |
| 285 | + &fx.work, | |
| 286 | + &[ | |
| 287 | + "push", | |
| 288 | + "-q", | |
| 289 | + &fx.bare.to_string_lossy(), | |
| 290 | + "HEAD:refs/heads/feature", | |
| 291 | + ], | |
| 292 | + ); | |
| 293 | + let cookie = sign_in_owner(&fx).await; | |
| 294 | + let page = format!("/{OWNER}/{REPO}/branches"); | |
| 295 | + | |
| 296 | + let (status, _, html) = send(&fx.router, "GET", &page, Some(&cookie), &[]).await; | |
| 297 | + assert_eq!(status, 200); | |
| 298 | + // feature is 1 ahead of and 54 behind main (the root is its base, main has 54 more commits). | |
| 299 | + assert!(html.contains("1 ahead, 54 behind"), "{html}"); | |
| 300 | + assert!(html.contains(&format!("/{OWNER}/{REPO}/compare/main...feature"))); | |
| 301 | + assert!(html.contains("tahinli")); | |
| 302 | + assert!(html.contains("confirm-inline")); | |
| 303 | + // Anonymous viewers get no create or delete controls. | |
| 304 | + let (_, _, anon) = send(&fx.router, "GET", &page, None, &[]).await; | |
| 305 | + assert!(!anon.contains("confirm-inline")); | |
| 306 | + assert!(!anon.contains("new-branch")); | |
| 307 | + | |
| 308 | + // Create from a ref. | |
| 309 | + let (status, headers, _) = send( | |
| 310 | + &fx.router, | |
| 311 | + "POST", | |
| 312 | + &page, | |
| 313 | + Some(&cookie), | |
| 314 | + &[("csrf", CSRF), ("name", "topic/one"), ("from", "feature")], | |
| 315 | + ) | |
| 316 | + .await; | |
| 317 | + assert_eq!(status, 303); | |
| 318 | + assert_eq!(headers["location"], page); | |
| 319 | + let feature_tip = git(&fx.bare, &["rev-parse", "refs/heads/feature"]); | |
| 320 | + assert_eq!( | |
| 321 | + git(&fx.bare, &["rev-parse", "refs/heads/topic/one"]), | |
| 322 | + feature_tip | |
| 323 | + ); | |
| 324 | + | |
| 325 | + // Existing name, bad name and missing source change nothing and report why. | |
| 326 | + for (name, from, word) in [ | |
| 327 | + ("topic/one", "feature", "exists"), | |
| 328 | + ("bad..name", "feature", "invalid"), | |
| 329 | + ("other", "no-such-ref", "source"), | |
| 330 | + ] { | |
| 331 | + let (status, _, _) = send( | |
| 332 | + &fx.router, | |
| 333 | + "POST", | |
| 334 | + &page, | |
| 335 | + Some(&cookie), | |
| 336 | + &[("csrf", CSRF), ("name", name), ("from", from)], | |
| 337 | + ) | |
| 338 | + .await; | |
| 339 | + assert_eq!(status, 303); | |
| 340 | + let (_, _, html) = send( | |
| 341 | + &fx.router, | |
| 342 | + "GET", | |
| 343 | + &page, | |
| 344 | + Some(&format!("{cookie}; forge_branch_notice={word}")), | |
| 345 | + &[], | |
| 346 | + ) | |
| 347 | + .await; | |
| 348 | + assert!( | |
| 349 | + html.contains("role=\"alert\"") || html.contains("alert"), | |
| 350 | + "{word}" | |
| 351 | + ); | |
| 352 | + } | |
| 353 | + | |
| 354 | + // A bad CSRF token is refused. | |
| 355 | + let (status, _, _) = send( | |
| 356 | + &fx.router, | |
| 357 | + "POST", | |
| 358 | + &page, | |
| 359 | + Some(&cookie), | |
| 360 | + &[("csrf", "wrong"), ("name", "x"), ("from", "main")], | |
| 361 | + ) | |
| 362 | + .await; | |
| 363 | + assert_eq!(status, 403); | |
| 364 | + | |
| 365 | + // Delete: a moved branch is left alone, the right oid deletes it. | |
| 366 | + let delete = format!("{page}/delete"); | |
| 367 | + let (status, _, _) = send( | |
| 368 | + &fx.router, | |
| 369 | + "POST", | |
| 370 | + &delete, | |
| 371 | + Some(&cookie), | |
| 372 | + &[("csrf", CSRF), ("name", "topic/one"), ("oid", &fx.root)], | |
| 373 | + ) | |
| 374 | + .await; | |
| 375 | + assert_eq!(status, 303); | |
| 376 | + git(&fx.bare, &["rev-parse", "--verify", "refs/heads/topic/one"]); | |
| 377 | + let (status, _, _) = send( | |
| 378 | + &fx.router, | |
| 379 | + "POST", | |
| 380 | + &delete, | |
| 381 | + Some(&cookie), | |
| 382 | + &[("csrf", CSRF), ("name", "topic/one"), ("oid", &feature_tip)], | |
| 383 | + ) | |
| 384 | + .await; | |
| 385 | + assert_eq!(status, 303); | |
| 386 | + let listing = git(&fx.bare, &["branch", "--list", "topic/one"]); | |
| 387 | + assert!(listing.is_empty(), "branch should be gone: {listing}"); | |
| 388 | + | |
| 389 | + // The default branch can never be deleted. | |
| 390 | + let main_tip = git(&fx.bare, &["rev-parse", "refs/heads/main"]); | |
| 391 | + send( | |
| 392 | + &fx.router, | |
| 393 | + "POST", | |
| 394 | + &delete, | |
| 395 | + Some(&cookie), | |
| 396 | + &[("csrf", CSRF), ("name", "main"), ("oid", &main_tip)], | |
| 397 | + ) | |
| 398 | + .await; | |
| 399 | + git(&fx.bare, &["rev-parse", "--verify", "refs/heads/main"]); | |
| 400 | +} | |
| 401 | + | |
| 402 | +#[tokio::test] | |
| 403 | +async fn protection_rules_block_branch_deletion() { | |
| 404 | + let fx = Fixture::new(Visibility::Public).await; | |
| 405 | + git(&fx.bare, &["branch", "release/1", "main"]); | |
| 406 | + git(&fx.bare, &["branch", "scratch", "main"]); | |
| 407 | + let repo = fx | |
| 408 | + .store | |
| 409 | + .repo_by_owner_and_name(OWNER, REPO) | |
| 410 | + .await | |
| 411 | + .unwrap() | |
| 412 | + .unwrap(); | |
| 413 | + fx.store | |
| 414 | + .upsert_branch_rule(&repo.id, "release/*", RuleFlags::basic(false, false)) | |
| 415 | + .await | |
| 416 | + .unwrap(); | |
| 417 | + let cookie = sign_in_owner(&fx).await; | |
| 418 | + let delete = format!("/{OWNER}/{REPO}/branches/delete"); | |
| 419 | + let tip = git(&fx.bare, &["rev-parse", "refs/heads/main"]); | |
| 420 | + | |
| 421 | + send( | |
| 422 | + &fx.router, | |
| 423 | + "POST", | |
| 424 | + &delete, | |
| 425 | + Some(&cookie), | |
| 426 | + &[("csrf", CSRF), ("name", "release/1"), ("oid", &tip)], | |
| 427 | + ) | |
| 428 | + .await; | |
| 429 | + git(&fx.bare, &["rev-parse", "--verify", "refs/heads/release/1"]); | |
| 430 | + | |
| 431 | + send( | |
| 432 | + &fx.router, | |
| 433 | + "POST", | |
| 434 | + &delete, | |
| 435 | + Some(&cookie), | |
| 436 | + &[("csrf", CSRF), ("name", "scratch"), ("oid", &tip)], | |
| 437 | + ) | |
| 438 | + .await; | |
| 439 | + assert!(git(&fx.bare, &["branch", "--list", "scratch"]).is_empty()); | |
| 440 | +} | |
| 441 | + | |
| 442 | +#[tokio::test] | |
| 443 | +async fn default_branch_setting_updates_head_and_the_record() { | |
| 444 | + let fx = Fixture::new(Visibility::Public).await; | |
| 445 | + git(&fx.bare, &["branch", "trunk", "main"]); | |
| 446 | + let cookie = sign_in_owner(&fx).await; | |
| 447 | + let settings = format!("/{OWNER}/{REPO}/settings/general"); | |
| 448 | + | |
| 449 | + let (status, _, _) = send( | |
| 450 | + &fx.router, | |
| 451 | + "POST", | |
| 452 | + &settings, | |
| 453 | + Some(&cookie), | |
| 454 | + &[ | |
| 455 | + ("csrf", CSRF), | |
| 456 | + ("description", "demo"), | |
| 457 | + ("default_branch", "trunk"), | |
| 458 | + ], | |
| 459 | + ) | |
| 460 | + .await; | |
| 461 | + assert_eq!(status, 303); | |
| 462 | + assert_eq!(git(&fx.bare, &["symbolic-ref", "HEAD"]), "refs/heads/trunk"); | |
| 463 | + let repo = fx | |
| 464 | + .store | |
| 465 | + .repo_by_owner_and_name(OWNER, REPO) | |
| 466 | + .await | |
| 467 | + .unwrap() | |
| 468 | + .unwrap(); | |
| 469 | + assert_eq!(repo.default_branch, "trunk"); | |
| 470 | + assert_eq!(repo.description, "demo"); | |
| 471 | + | |
| 472 | + // A branch that does not exist changes nothing. | |
| 473 | + send( | |
| 474 | + &fx.router, | |
| 475 | + "POST", | |
| 476 | + &settings, | |
| 477 | + Some(&cookie), | |
| 478 | + &[ | |
| 479 | + ("csrf", CSRF), | |
| 480 | + ("description", "demo"), | |
| 481 | + ("default_branch", "ghost"), | |
| 482 | + ], | |
| 483 | + ) | |
| 484 | + .await; | |
| 485 | + assert_eq!(git(&fx.bare, &["symbolic-ref", "HEAD"]), "refs/heads/trunk"); | |
| 486 | + let repo = fx | |
| 487 | + .store | |
| 488 | + .repo_by_owner_and_name(OWNER, REPO) | |
| 489 | + .await | |
| 490 | + .unwrap() | |
| 491 | + .unwrap(); | |
| 492 | + assert_eq!(repo.default_branch, "trunk"); | |
| 493 | + | |
| 494 | + // The settings page offers the branches and marks the current one. | |
| 495 | + let (_, _, html) = send( | |
| 496 | + &fx.router, | |
| 497 | + "GET", | |
| 498 | + &format!("/{OWNER}/{REPO}/settings"), | |
| 499 | + Some(&cookie), | |
| 500 | + &[], | |
| 501 | + ) | |
| 502 | + .await; | |
| 503 | + assert!(html.contains("name=\"default_branch\"")); | |
| 504 | +} |
crates/forge-web/src/pages/finder.rsadded+92 -0
| @@ -0,0 +1,92 @@ | ||
| 1 | +//! The file finder: a "Go to file" button and dialog (opened with `t`) and the JSON route that | |
| 2 | +//! lists every path of the tree at a ref, `GET /{owner}/{repo}/paths/{*ref}`. The fuzzy matching | |
| 3 | +//! and keyboard handling live in `assets/nav.js`. | |
| 4 | + | |
| 5 | +use forge_git::history; | |
| 6 | +use http::header::{CACHE_CONTROL, CONTENT_TYPE}; | |
| 7 | +use topcoat::Result; | |
| 8 | +use topcoat::context::{Cx, app_context}; | |
| 9 | +use topcoat::router::error::not_found; | |
| 10 | +use topcoat::router::response::Response; | |
| 11 | +use topcoat::router::{Body, HeaderValue, path_param, route}; | |
| 12 | +use topcoat::view::{View, component, view}; | |
| 13 | + | |
| 14 | +use crate::i18n::Lang; | |
| 15 | +use crate::i18n::browse as b; | |
| 16 | +use crate::pages::repo_ctx::load_repo; | |
| 17 | +use crate::pages::tree::resolve; | |
| 18 | +use crate::state::AppState; | |
| 19 | +use crate::views::repo_href; | |
| 20 | + | |
| 21 | +path_param!(owner); | |
| 22 | +path_param!(repo); | |
| 23 | +path_param!(*rest); | |
| 24 | + | |
| 25 | +/// Paths returned at most. A larger tree is cut and the dialog says so. | |
| 26 | +pub const MAX_PATHS: usize = 20_000; | |
| 27 | + | |
| 28 | +/// The "Go to file" button and its dialog for the tree at `ref_name`. | |
| 29 | +#[component] | |
| 30 | +pub async fn file_finder( | |
| 31 | + lang: Lang, | |
| 32 | + owner: String, | |
| 33 | + repo: String, | |
| 34 | + ref_name: String, | |
| 35 | +) -> Result<impl View> { | |
| 36 | + let src = repo_href(&owner, &repo, "paths", &ref_name); | |
| 37 | + let base = format!("{}/", repo_href(&owner, &repo, "blob", &ref_name)); | |
| 38 | + Ok(view! { | |
| 39 | + <button type="button" class="button finder-open" data-finder-open="" title=(b::t(lang, b::K::FinderHint))> | |
| 40 | + (b::t(lang, b::K::GoToFile)) | |
| 41 | + <kbd>"t"</kbd> | |
| 42 | + </button> | |
| 43 | + <dialog class="finder" data-finder="" data-src=(src.as_str()) data-base=(base.as_str()) | |
| 44 | + data-loading=(b::t(lang, b::K::FinderLoading)) data-empty=(b::t(lang, b::K::FinderEmpty)) | |
| 45 | + data-failed=(b::t(lang, b::K::FinderFailed)) data-truncated=(b::t(lang, b::K::FinderTruncated)) | |
| 46 | + aria-label=(b::t(lang, b::K::FinderTitle))> | |
| 47 | + <div class="finder-box"> | |
| 48 | + <input type="text" class="finder-input" data-finder-input="" autocomplete="off" spellcheck="false" | |
| 49 | + placeholder=(b::t(lang, b::K::FinderPlaceholder)) aria-label=(b::t(lang, b::K::FinderPlaceholder)) | |
| 50 | + role="combobox" aria-expanded="true" aria-controls="finder-list" aria-autocomplete="list"> | |
| 51 | + <ul id="finder-list" class="finder-list" role="listbox" data-finder-list=""></ul> | |
| 52 | + <p class="finder-note muted small" data-finder-note="">(b::t(lang, b::K::FinderHint))</p> | |
| 53 | + </div> | |
| 54 | + </dialog> | |
| 55 | + }) | |
| 56 | +} | |
| 57 | + | |
| 58 | +/// `{"ref": ..., "commit": ..., "paths": [...], "truncated": bool}` for the tree at the ref. | |
| 59 | +#[route(GET "/{owner}/{repo}/paths/{*rest}")] | |
| 60 | +async fn tree_paths(cx: &Cx) -> Result<Response> { | |
| 61 | + let owner = path_param::<Owner>(cx); | |
| 62 | + let name = path_param::<Repo>(cx); | |
| 63 | + let rest = path_param::<Rest>(cx).collect::<Vec<_>>().join("/"); | |
| 64 | + let ctx = load_repo(cx, owner, name).await?; | |
| 65 | + let state = app_context::<AppState>(cx); | |
| 66 | + | |
| 67 | + let Some((ref_name, commit, path)) = resolve(ctx.path.clone(), rest).await? else { | |
| 68 | + return Err(not_found().into()); | |
| 69 | + }; | |
| 70 | + if !path.is_empty() { | |
| 71 | + return Err(not_found().into()); | |
| 72 | + } | |
| 73 | + let (paths, truncated) = history::list_files(&state.git, &ctx.path, &commit, MAX_PATHS).await?; | |
| 74 | + let body = serde_json::json!({ | |
| 75 | + "ref": ref_name, | |
| 76 | + "commit": commit, | |
| 77 | + "paths": paths, | |
| 78 | + "truncated": truncated, | |
| 79 | + }); | |
| 80 | + let mut response = Response::new(Body::from(body.to_string().into_bytes())); | |
| 81 | + let headers = response.headers_mut(); | |
| 82 | + headers.insert( | |
| 83 | + CONTENT_TYPE, | |
| 84 | + HeaderValue::from_static("application/json; charset=utf-8"), | |
| 85 | + ); | |
| 86 | + headers.insert(CACHE_CONTROL, HeaderValue::from_static("private, no-cache")); | |
| 87 | + headers.insert( | |
| 88 | + http::header::X_CONTENT_TYPE_OPTIONS, | |
| 89 | + HeaderValue::from_static("nosniff"), | |
| 90 | + ); | |
| 91 | + Ok(response) | |
| 92 | +} |
crates/forge-web/src/pages/mod.rsmodified+5 -0
| @@ -10,7 +10,11 @@ pub mod archive; | ||
| 10 | 10 | pub mod assets; |
| 11 | 11 | pub mod audit_log; |
| 12 | 12 | pub mod avatars; |
| 13 | +pub mod blame; | |
| 13 | 14 | pub mod blob; |
| 15 | +pub mod branches; | |
| 16 | +#[cfg(test)] | |
| 17 | +mod browse_tests; | |
| 14 | 18 | pub mod ci_badge; |
| 15 | 19 | pub mod ci_job; |
| 16 | 20 | pub mod ci_runs; |
| @@ -27,6 +31,7 @@ pub mod discussion_view; | ||
| 27 | 31 | pub mod discussions; |
| 28 | 32 | pub mod edit_history; |
| 29 | 33 | pub mod explore; |
| 34 | +pub mod finder; | |
| 30 | 35 | pub mod forgot; |
| 31 | 36 | pub mod fork; |
| 32 | 37 | pub mod invites; |
crates/forge-web/src/pages/refs.rsmodified+2 -23
| @@ -1,4 +1,4 @@ | ||
| 1 | -//! Pages: branch and tag lists at `/{owner}/{repo}/branches` and `/{owner}/{repo}/tags`. | |
| 1 | +//! Page: the tag list at `/{owner}/{repo}/tags` (branches are in `branches`). | |
| 2 | 2 | //! Also the ref helpers shared with the tree page (the ref selector). |
| 3 | 3 | |
| 4 | 4 | use std::path::PathBuf; |
| @@ -69,7 +69,7 @@ pub struct RefRow { | ||
| 69 | 69 | } |
| 70 | 70 | |
| 71 | 71 | /// Refs of `kind` with the commit each points at, in table order. |
| 72 | -async fn ref_rows( | |
| 72 | +pub(crate) async fn ref_rows( | |
| 73 | 73 | path: PathBuf, |
| 74 | 74 | kind: RefKind, |
| 75 | 75 | repo: &RepoRow, |
| @@ -166,27 +166,6 @@ async fn refs_data(cx: &Cx, kind: RefKind) -> Result<RefsPage> { | ||
| 166 | 166 | Ok(RefsPage { ctx, rows }) |
| 167 | 167 | } |
| 168 | 168 | |
| 169 | -#[page("/{owner}/{repo}/branches")] | |
| 170 | -async fn branches_page(cx: &Cx) -> Result<impl View> { | |
| 171 | - let page = refs_data(cx, RefKind::Branch).await?; | |
| 172 | - let ctx = page.ctx; | |
| 173 | - let rows = page.rows; | |
| 174 | - let lang = i18n::lang(cx, ctx.viewer.as_ref().map(|(user, _)| user)); | |
| 175 | - let title = format!( | |
| 176 | - "{}/{} \u{b7} {}", | |
| 177 | - ctx.repo.owner_name, | |
| 178 | - ctx.repo.name, | |
| 179 | - g::t(lang, K::BranchesTitle) | |
| 180 | - ); | |
| 181 | - let header = ctx.head(app_context::<AppState>(cx), "branches").await?; | |
| 182 | - Ok(view! { | |
| 183 | - shell(title: title.as_str(), viewer: ctx.viewer.as_ref(), | |
| 184 | - repo_head(head: header) | |
| 185 | - refs_table(rows: rows, kind_label: g::t(lang, K::BranchLabel), lang: lang) | |
| 186 | - ) | |
| 187 | - }) | |
| 188 | -} | |
| 189 | - | |
| 190 | 169 | #[page("/{owner}/{repo}/tags")] |
| 191 | 170 | async fn tags_page(cx: &Cx) -> Result<impl View> { |
| 192 | 171 | let page = refs_data(cx, RefKind::Tag).await?; |
crates/forge-web/src/pages/repo.rsmodified+3 -0
| @@ -21,6 +21,7 @@ use topcoat::view::{View, component, view}; | ||
| 21 | 21 | use crate::i18n::code::{self as g, K}; |
| 22 | 22 | use crate::i18n::{self, Lang}; |
| 23 | 23 | use crate::pages::dashboard::badge_class; |
| 24 | +use crate::pages::finder::file_finder; | |
| 24 | 25 | use crate::pages::issue_parts::stamp_unix; |
| 25 | 26 | use crate::pages::notifications::watch_form; |
| 26 | 27 | use crate::pages::refs::load_refs; |
| @@ -458,6 +459,8 @@ async fn repo_page(cx: &Cx) -> Result<impl View> { | ||
| 458 | 459 | <div class="browse-bar"> |
| 459 | 460 | <span class="muted small">(g::t(lang, K::BranchLabel))</span> |
| 460 | 461 | <code>(branch.clone())</code> |
| 462 | + file_finder(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), | |
| 463 | + ref_name: branch.clone()) | |
| 461 | 464 | archive_links(owner: owner_name, repo: repo_name, |
| 462 | 465 | ref_name: branch.clone(), lang: lang) |
| 463 | 466 | clone_popover(https: https, ssh: ssh, lang: lang) |
crates/forge-web/src/pages/tree.rsmodified+5 -0
| @@ -17,6 +17,7 @@ use topcoat::view::{Unescaped, View, component, view}; | ||
| 17 | 17 | |
| 18 | 18 | use crate::i18n::code::{self as g, K}; |
| 19 | 19 | use crate::i18n::{self, Lang}; |
| 20 | +use crate::pages::finder::file_finder; | |
| 20 | 21 | use crate::pages::refs::{load_refs, ref_links}; |
| 21 | 22 | use crate::pages::repo::repo_head; |
| 22 | 23 | use crate::pages::repo_ctx::load_repo; |
| @@ -388,6 +389,9 @@ async fn tree_page(cx: &Cx) -> Result<impl View> { | ||
| 388 | 389 | |
| 389 | 390 | let title = format!("{}/{}", repo.owner_name, repo.name); |
| 390 | 391 | let crumbs = path_crumbs(repo, &ref_name, "tree", &dir); |
| 392 | + let finder_owner = repo.owner_name.clone(); | |
| 393 | + let finder_repo = repo.name.clone(); | |
| 394 | + let finder_ref = ref_name.clone(); | |
| 391 | 395 | let header = ctx.head(state, "code").await?; |
| 392 | 396 | Ok(view! { |
| 393 | 397 | shell(title: title.as_str(), viewer: ctx.viewer.as_ref(), |
| @@ -395,6 +399,7 @@ async fn tree_page(cx: &Cx) -> Result<impl View> { | ||
| 395 | 399 | <div class="browse-bar"> |
| 396 | 400 | ref_selector(lang: lang, current: ref_name.clone(), branches: branches, tags: tags) |
| 397 | 401 | breadcrumb(lang: lang, crumbs: crumbs) |
| 402 | + file_finder(lang: lang, owner: finder_owner, repo: finder_repo, ref_name: finder_ref) | |
| 398 | 403 | </div> |
| 399 | 404 | tree_table(rows: rows, lang: lang) |
| 400 | 405 | if let Some(readme) = readme { |
style/_browse.scssadded+476 -0
| @@ -0,0 +1,476 @@ | ||
| 1 | +// Code browsing: the diff toolbar and split view, blob line selection, blame, the file finder and | |
| 2 | +// the branches page. | |
| 3 | + | |
| 4 | +// Diff toolbar: unified/split segment, ignore whitespace, patch downloads. | |
| 5 | +.diff-toolbar { | |
| 6 | + display: flex; | |
| 7 | + align-items: center; | |
| 8 | + flex-wrap: wrap; | |
| 9 | + gap: 8px 12px; | |
| 10 | + margin: 0 0 12px; | |
| 11 | +} | |
| 12 | + | |
| 13 | +.seg { | |
| 14 | + display: inline-flex; | |
| 15 | + border: 1px solid var(--border-strong); | |
| 16 | + border-radius: var(--radius-md); | |
| 17 | + overflow: hidden; | |
| 18 | + background: var(--surface); | |
| 19 | + | |
| 20 | + .seg-item { | |
| 21 | + border: 0; | |
| 22 | + border-radius: 0; | |
| 23 | + border-right: 1px solid var(--border-strong); | |
| 24 | + | |
| 25 | + &:last-child { | |
| 26 | + border-right: 0; | |
| 27 | + } | |
| 28 | + } | |
| 29 | +} | |
| 30 | + | |
| 31 | +.seg-item { | |
| 32 | + display: inline-flex; | |
| 33 | + align-items: center; | |
| 34 | + height: calc(var(--control-h) - 4px); | |
| 35 | + padding: 0 12px; | |
| 36 | + font-size: 0.8125rem; | |
| 37 | + font-weight: 500; | |
| 38 | + color: var(--text-2); | |
| 39 | + text-decoration: none; | |
| 40 | + background: var(--surface); | |
| 41 | + | |
| 42 | + &:hover { | |
| 43 | + text-decoration: none; | |
| 44 | + background: var(--surface-2); | |
| 45 | + color: var(--text); | |
| 46 | + } | |
| 47 | + | |
| 48 | + &[aria-pressed="true"] { | |
| 49 | + background: var(--accent-soft); | |
| 50 | + color: var(--text); | |
| 51 | + } | |
| 52 | + | |
| 53 | + &.toggle { | |
| 54 | + border: 1px solid var(--border-strong); | |
| 55 | + border-radius: var(--radius-md); | |
| 56 | + } | |
| 57 | +} | |
| 58 | + | |
| 59 | +.diff-downloads { | |
| 60 | + display: inline-flex; | |
| 61 | + gap: 12px; | |
| 62 | + margin-left: auto; | |
| 63 | + font-family: var(--mono); | |
| 64 | + font-size: 0.8125rem; | |
| 65 | +} | |
| 66 | + | |
| 67 | +// Split view: two sides per row, code wraps instead of scrolling sideways. | |
| 68 | +.diff-table.diff-split { | |
| 69 | + width: 100%; | |
| 70 | + table-layout: fixed; | |
| 71 | + | |
| 72 | + .diff-ln { | |
| 73 | + position: static; | |
| 74 | + width: 3.5em; | |
| 75 | + min-width: 0; | |
| 76 | + } | |
| 77 | + | |
| 78 | + .diff-plus { | |
| 79 | + width: 24px; | |
| 80 | + padding: 0 2px; | |
| 81 | + } | |
| 82 | + | |
| 83 | + .diff-code { | |
| 84 | + white-space: pre-wrap; | |
| 85 | + overflow-wrap: anywhere; | |
| 86 | + word-break: break-all; | |
| 87 | + min-width: 0; | |
| 88 | + } | |
| 89 | + | |
| 90 | + .diff-line.hunk td { | |
| 91 | + white-space: pre-wrap; | |
| 92 | + } | |
| 93 | + | |
| 94 | + .side-add { | |
| 95 | + background: var(--add-bg); | |
| 96 | + } | |
| 97 | + | |
| 98 | + .diff-code.side-add { | |
| 99 | + color: var(--add-text); | |
| 100 | + } | |
| 101 | + | |
| 102 | + .side-del { | |
| 103 | + background: var(--del-bg); | |
| 104 | + } | |
| 105 | + | |
| 106 | + .diff-code.side-del { | |
| 107 | + color: var(--del-text); | |
| 108 | + } | |
| 109 | + | |
| 110 | + .side-empty { | |
| 111 | + background: var(--surface-2); | |
| 112 | + } | |
| 113 | + | |
| 114 | + .diff-code.side-dup, | |
| 115 | + .diff-code.side-ctx { | |
| 116 | + color: var(--text); | |
| 117 | + } | |
| 118 | + | |
| 119 | + // The right half starts with a divider. | |
| 120 | + .diff-code + .diff-plus, | |
| 121 | + .diff-code + .diff-ln { | |
| 122 | + border-left: 1px solid var(--border-strong); | |
| 123 | + } | |
| 124 | + | |
| 125 | + .diff-code:target { | |
| 126 | + background: var(--row-target); | |
| 127 | + } | |
| 128 | +} | |
| 129 | + | |
| 130 | +// Phones: each split row stacks its old half over its new half; empty halves and the repeat of a | |
| 131 | +// context line disappear, so nothing scrolls sideways. | |
| 132 | +@media (max-width: 720px) { | |
| 133 | + .diff-table.diff-split { | |
| 134 | + display: block; | |
| 135 | + width: 100%; | |
| 136 | + | |
| 137 | + tbody { | |
| 138 | + display: block; | |
| 139 | + } | |
| 140 | + | |
| 141 | + tr.diff-split-row { | |
| 142 | + display: grid; | |
| 143 | + grid-template-columns: 3.5em minmax(0, 1fr); | |
| 144 | + } | |
| 145 | + | |
| 146 | + &.anchored tr.diff-split-row { | |
| 147 | + grid-template-columns: 24px 3.5em minmax(0, 1fr); | |
| 148 | + } | |
| 149 | + | |
| 150 | + .side-empty, | |
| 151 | + .side-dup { | |
| 152 | + display: none; | |
| 153 | + } | |
| 154 | + | |
| 155 | + td.diff-ln, | |
| 156 | + td.diff-plus { | |
| 157 | + width: auto; | |
| 158 | + min-width: 0; | |
| 159 | + } | |
| 160 | + | |
| 161 | + .diff-code + .diff-plus, | |
| 162 | + .diff-code + .diff-ln { | |
| 163 | + border-left: 0; | |
| 164 | + } | |
| 165 | + | |
| 166 | + tr.diff-line.hunk, | |
| 167 | + tr.review-row { | |
| 168 | + display: block; | |
| 169 | + } | |
| 170 | + | |
| 171 | + tr.diff-line.hunk td, | |
| 172 | + tr.review-row td { | |
| 173 | + display: block; | |
| 174 | + } | |
| 175 | + } | |
| 176 | +} | |
| 177 | + | |
| 178 | +// Blob line selection. | |
| 179 | +.file-table tr.line-hl td { | |
| 180 | + background: var(--row-target); | |
| 181 | +} | |
| 182 | + | |
| 183 | +.file-table tr.line-hl .ln { | |
| 184 | + color: var(--text); | |
| 185 | + font-weight: 600; | |
| 186 | +} | |
| 187 | + | |
| 188 | +.file-table .ln a { | |
| 189 | + display: block; | |
| 190 | + cursor: pointer; | |
| 191 | +} | |
| 192 | + | |
| 193 | +.file-actions .link-button { | |
| 194 | + font-size: inherit; | |
| 195 | + color: var(--link, var(--accent)); | |
| 196 | + cursor: pointer; | |
| 197 | +} | |
| 198 | + | |
| 199 | +// Blame. | |
| 200 | +.blame-table { | |
| 201 | + .blame-meta { | |
| 202 | + position: sticky; | |
| 203 | + left: 0; | |
| 204 | + z-index: 2; | |
| 205 | + width: 22rem; | |
| 206 | + min-width: 16rem; | |
| 207 | + max-width: 22rem; | |
| 208 | + padding: 6px 12px; | |
| 209 | + font-family: var(--font); | |
| 210 | + font-size: 0.8125rem; | |
| 211 | + line-height: 1.35; | |
| 212 | + white-space: normal; | |
| 213 | + vertical-align: top; | |
| 214 | + background: var(--surface); | |
| 215 | + border-right: 1px solid var(--border); | |
| 216 | + border-top: 1px solid var(--border); | |
| 217 | + } | |
| 218 | + | |
| 219 | + .blame-top { | |
| 220 | + display: flex; | |
| 221 | + align-items: baseline; | |
| 222 | + gap: 8px; | |
| 223 | + min-width: 0; | |
| 224 | + } | |
| 225 | + | |
| 226 | + .blame-author { | |
| 227 | + min-width: 0; | |
| 228 | + overflow: hidden; | |
| 229 | + text-overflow: ellipsis; | |
| 230 | + white-space: nowrap; | |
| 231 | + font-weight: 500; | |
| 232 | + } | |
| 233 | + | |
| 234 | + .blame-summary { | |
| 235 | + display: block; | |
| 236 | + overflow: hidden; | |
| 237 | + text-overflow: ellipsis; | |
| 238 | + white-space: nowrap; | |
| 239 | + color: var(--text-2); | |
| 240 | + } | |
| 241 | + | |
| 242 | + .blame-prior { | |
| 243 | + display: inline-block; | |
| 244 | + margin-top: 2px; | |
| 245 | + } | |
| 246 | + | |
| 247 | + tr.blame-first td:not(.blame-meta) { | |
| 248 | + border-top: 1px solid var(--border); | |
| 249 | + } | |
| 250 | + | |
| 251 | + .ln { | |
| 252 | + left: 22rem; | |
| 253 | + } | |
| 254 | +} | |
| 255 | + | |
| 256 | +@media (max-width: 720px) { | |
| 257 | + .blame-table { | |
| 258 | + .blame-meta { | |
| 259 | + position: static; | |
| 260 | + width: 12rem; | |
| 261 | + min-width: 12rem; | |
| 262 | + } | |
| 263 | + | |
| 264 | + .ln { | |
| 265 | + left: 0; | |
| 266 | + position: static; | |
| 267 | + } | |
| 268 | + } | |
| 269 | +} | |
| 270 | + | |
| 271 | +// File finder. | |
| 272 | +.finder-open kbd, | |
| 273 | +.finder-note kbd { | |
| 274 | + padding: 0 6px; | |
| 275 | + font-family: var(--mono); | |
| 276 | + font-size: 0.75rem; | |
| 277 | + color: var(--text-2); | |
| 278 | + background: var(--surface-2); | |
| 279 | + border: 1px solid var(--border-strong); | |
| 280 | + border-radius: var(--radius-sm); | |
| 281 | +} | |
| 282 | + | |
| 283 | +.finder-open { | |
| 284 | + margin-left: auto; | |
| 285 | +} | |
| 286 | + | |
| 287 | +dialog.finder { | |
| 288 | + width: min(640px, calc(100vw - 32px)); | |
| 289 | + max-height: min(70vh, 560px); | |
| 290 | + margin: 10vh auto 0; | |
| 291 | + padding: 0; | |
| 292 | + color: var(--text); | |
| 293 | + background: var(--surface); | |
| 294 | + border: 1px solid var(--border-strong); | |
| 295 | + border-radius: var(--radius-lg); | |
| 296 | + box-shadow: var(--shadow); | |
| 297 | + | |
| 298 | + &::backdrop { | |
| 299 | + background: rgba(20, 24, 22, 0.45); | |
| 300 | + } | |
| 301 | + | |
| 302 | + &[open] { | |
| 303 | + display: flex; | |
| 304 | + flex-direction: column; | |
| 305 | + } | |
| 306 | +} | |
| 307 | + | |
| 308 | +.finder-box { | |
| 309 | + display: flex; | |
| 310 | + flex-direction: column; | |
| 311 | + min-height: 0; | |
| 312 | + padding: 12px; | |
| 313 | + gap: 8px; | |
| 314 | +} | |
| 315 | + | |
| 316 | +.finder-input { | |
| 317 | + width: 100%; | |
| 318 | + height: var(--control-h); | |
| 319 | + box-sizing: border-box; | |
| 320 | + font-size: 0.9375rem; | |
| 321 | +} | |
| 322 | + | |
| 323 | +.finder-list { | |
| 324 | + margin: 0; | |
| 325 | + padding: 0; | |
| 326 | + list-style: none; | |
| 327 | + overflow-y: auto; | |
| 328 | + max-height: 50vh; | |
| 329 | + font-family: var(--mono); | |
| 330 | + font-size: 0.8125rem; | |
| 331 | + | |
| 332 | + li { | |
| 333 | + margin: 0; | |
| 334 | + } | |
| 335 | + | |
| 336 | + a { | |
| 337 | + display: block; | |
| 338 | + padding: 6px 10px; | |
| 339 | + color: var(--text); | |
| 340 | + text-decoration: none; | |
| 341 | + border-radius: var(--radius-sm); | |
| 342 | + overflow-wrap: anywhere; | |
| 343 | + } | |
| 344 | + | |
| 345 | + li[aria-selected="true"] a, | |
| 346 | + a:hover { | |
| 347 | + background: var(--accent-soft); | |
| 348 | + } | |
| 349 | + | |
| 350 | + mark { | |
| 351 | + background: none; | |
| 352 | + color: var(--accent-ink); | |
| 353 | + font-weight: 700; | |
| 354 | + } | |
| 355 | +} | |
| 356 | + | |
| 357 | +.finder-note { | |
| 358 | + margin: 0; | |
| 359 | +} | |
| 360 | + | |
| 361 | +// Branches page. | |
| 362 | +.new-branch { | |
| 363 | + margin: 0 0 12px; | |
| 364 | + | |
| 365 | + > summary { | |
| 366 | + list-style: none; | |
| 367 | + cursor: pointer; | |
| 368 | + | |
| 369 | + &::-webkit-details-marker { | |
| 370 | + display: none; | |
| 371 | + } | |
| 372 | + } | |
| 373 | +} | |
| 374 | + | |
| 375 | +.new-branch-form { | |
| 376 | + display: flex; | |
| 377 | + flex-wrap: wrap; | |
| 378 | + align-items: flex-end; | |
| 379 | + gap: 10px 12px; | |
| 380 | + margin-top: 10px; | |
| 381 | + padding: 12px; | |
| 382 | + background: var(--surface); | |
| 383 | + border: 1px solid var(--border); | |
| 384 | + border-radius: var(--radius-lg); | |
| 385 | + | |
| 386 | + label { | |
| 387 | + display: flex; | |
| 388 | + flex-direction: column; | |
| 389 | + gap: 4px; | |
| 390 | + font-size: 0.8125rem; | |
| 391 | + color: var(--text-2); | |
| 392 | + } | |
| 393 | + | |
| 394 | + input[type="text"] { | |
| 395 | + min-width: 14rem; | |
| 396 | + } | |
| 397 | +} | |
| 398 | + | |
| 399 | +.button.small { | |
| 400 | + height: 28px; | |
| 401 | + padding: 0 10px; | |
| 402 | + font-size: 0.8125rem; | |
| 403 | +} | |
| 404 | + | |
| 405 | +.branch-table { | |
| 406 | + .branch-author { | |
| 407 | + white-space: nowrap; | |
| 408 | + | |
| 409 | + > span + span { | |
| 410 | + margin-left: 8px; | |
| 411 | + } | |
| 412 | + } | |
| 413 | + | |
| 414 | + .branch-counts { | |
| 415 | + white-space: nowrap; | |
| 416 | + } | |
| 417 | + | |
| 418 | + .branch-actions { | |
| 419 | + white-space: nowrap; | |
| 420 | + text-align: right; | |
| 421 | + | |
| 422 | + > * { | |
| 423 | + margin-left: 6px; | |
| 424 | + vertical-align: middle; | |
| 425 | + } | |
| 426 | + } | |
| 427 | +} | |
| 428 | + | |
| 429 | +.confirm-inline { | |
| 430 | + display: inline-block; | |
| 431 | + position: relative; | |
| 432 | + | |
| 433 | + > summary { | |
| 434 | + list-style: none; | |
| 435 | + cursor: pointer; | |
| 436 | + | |
| 437 | + &::-webkit-details-marker { | |
| 438 | + display: none; | |
| 439 | + } | |
| 440 | + } | |
| 441 | + | |
| 442 | + .confirm-pop { | |
| 443 | + // Fixed so the table's scroll container cannot clip it. | |
| 444 | + position: fixed; | |
| 445 | + top: 30vh; | |
| 446 | + left: 50%; | |
| 447 | + z-index: 50; | |
| 448 | + width: 22rem; | |
| 449 | + max-width: calc(100vw - 32px); | |
| 450 | + transform: translateX(-50%); | |
| 451 | + padding: 12px; | |
| 452 | + text-align: left; | |
| 453 | + white-space: normal; | |
| 454 | + background: var(--surface); | |
| 455 | + border: 1px solid var(--border-strong); | |
| 456 | + border-radius: var(--radius-lg); | |
| 457 | + box-shadow: var(--shadow); | |
| 458 | + | |
| 459 | + p { | |
| 460 | + margin: 0 0 10px; | |
| 461 | + font-size: 0.875rem; | |
| 462 | + } | |
| 463 | + | |
| 464 | + form { | |
| 465 | + display: flex; | |
| 466 | + gap: 8px; | |
| 467 | + flex-wrap: wrap; | |
| 468 | + } | |
| 469 | + } | |
| 470 | +} | |
| 471 | + | |
| 472 | +@media (max-width: 720px) { | |
| 473 | + .branch-table .branch-actions { | |
| 474 | + text-align: left; | |
| 475 | + } | |
| 476 | +} |
style/main.scssmodified+1 -0
| @@ -5572,6 +5572,7 @@ button.ci-job-last { | ||
| 5572 | 5572 | @import "pull"; |
| 5573 | 5573 | @import "dashboard"; |
| 5574 | 5574 | @import "wiki"; |
| 5575 | +@import "browse"; | |
| 5575 | 5576 | |
| 5576 | 5577 | // Code inside cards, notices and settings panels must stay inside the card. Long tokens and |
| 5577 | 5578 | // commands wrap instead of running past the right edge. The rendered README card (.readme) and |