steid

@jamesgill /

1//! Atom feeds — commits, issues, and an owner's activity.
2//!
3//! Routes rather than pages: the response is an XML document, so no layout wraps it and
4//! nothing here builds a view.
5//!
6//! **The XML is written by hand, and the escaping is the whole of the safety.** Every
7//! dynamic value in a feed is somebody else's text — a commit message, an issue title,
8//! a branch name — and an unescaped `<` does not produce a visible mistake, it produces
9//! a document a reader refuses to parse or, worse, parses as markup that was never
10//! written. So there is exactly one way text reaches the output, [`escape`], and it is
11//! used on every value without exception. A crate was not added for this: three
12//! documents with a fixed shape is less code than the dependency, and the escaping is
13//! the part worth being able to read.
14//!
15//! Issue bodies are the one thing that arrives already-marked-up, from
16//! [`markdown`](super::markdown) — which never passes raw HTML through, so what comes
17//! back is a known set of tags. That still goes through `escape`, because Atom's
18//! `type="html"` means "escaped HTML in a text node": a reader unescapes it once and
19//! renders the result.
20//!
21//! Visibility is the use cases' answer and is never re-decided here. A private
22//! repository's feed 404s for a stranger exactly as its landing page does, and the
23//! profile feed carries only repositories the requester may see. No authentication is
24//! asked for: an anonymous reader is the point of a feed.
25
26use std::time::{SystemTime, UNIX_EPOCH};
27
28use topcoat::{
29 Result,
30 context::Cx,
31 icon::{icon, iconify::iconify_icon},
32 router::{
33 Body, Response,
34 error::{RouterErrorExt, not_found},
35 header::CONTENT_TYPE,
36 path_param, query_params, route,
37 },
38 view::{attributes, component, view},
39};
40
41use crate::{
42 application::{
43 ActivityEntry, IssueEntry, activity_feed, commit_feed, issue_feed, port::GitQueryError,
44 },
45 domain::{CommitEntry, OrgName, RefName, RepoName},
46};
47
48use super::{
49 browse::encode,
50 commit::{commit_url, compare_url},
51 context::{
52 current_actor, issues, memberships, orgs, public_origin, push_events, queries, repos,
53 server_error, users,
54 },
55 markdown,
56 profile::handle_param,
57};
58
59/// `{name}` from the path, raw — validation is [`RepoName`]'s job.
60#[path_param]
61struct Name(str);
62
63/// `?rev=` on the commit feed: which revision to follow, defaulting to `HEAD`.
64#[query_params(error = bad_request)]
65struct Query {
66 rev: Option<String>,
67}
68
69/// The media type every feed is served as.
70const ATOM: &str = "application/atom+xml; charset=utf-8";
71
72/// The same type without its charset, for a `<link type=…>`.
73///
74/// A link's `type` is a hint about the resource, and a parameter there is noise a
75/// reader has to strip. The response's own `Content-Type` is where the charset belongs.
76const ATOM_LINK: &str = "application/atom+xml";
77
78// --- Routes ---------------------------------------------------------------------------
79
80/// The last [`FEED_LIMIT`](crate::application::FEED_LIMIT) commits of a revision.
81///
82/// **One `git` process**, or two when `?rev=` is absent and the default branch has to be
83/// resolved first — the same cost the log page pays, with the message bodies included.
84#[route(GET "/{handle}/repos/{name}/commits.atom")]
85async fn commits_feed(cx: &Cx) -> Result<Response<Body>> {
86 let handle = handle_param(cx)?;
87 let name = repo_param(cx)?;
88 let rev = requested_rev(cx)?;
89
90 let entries = commit_feed(
91 &handle,
92 &name,
93 rev.as_ref(),
94 &current_actor(cx).await?,
95 &orgs(cx),
96 &memberships(cx),
97 &repos(cx),
98 &queries(cx),
99 )
100 .await
101 // A revision that git could not read is a feed that does not exist, not a 500: a
102 // reader polls a URL it was given, and `?rev=` is part of that URL.
103 .map_err(unreadable)?
104 .ok_or_not_found()?;
105
106 let origin = public_origin(cx);
107 let handle = handle.as_str();
108 let name = name.as_str();
109 let path = commits_feed_path(handle, name);
110 let alternate = match &rev {
111 Some(rev) => super::browse::log_url(handle, name, rev.as_str()),
112 None => format!("/{handle}/repos/{name}"),
113 };
114
115 let feed = Feed {
116 id: absolute(&origin, &path),
117 title: match &rev {
118 Some(rev) => format!("{handle}/{name} commits on {}", rev.as_str()),
119 None => format!("{handle}/{name} commits"),
120 },
121 self_url: absolute(&origin, &path),
122 alternate: absolute(&origin, &alternate),
123 author: handle.to_owned(),
124 updated: entries.first().map(|entry| entry.commit.committed_at),
125 entries: entries
126 .iter()
127 .map(|entry| commit_entry(&origin, handle, name, entry))
128 .collect(),
129 };
130
131 served(feed.render())
132}
133
134/// The last [`FEED_LIMIT`](crate::application::FEED_LIMIT) issues, open and closed.
135///
136/// **No `git` processes**: two queries for the issues and one per distinct author for
137/// their handle.
138#[route(GET "/{handle}/repos/{name}/issues.atom")]
139async fn issues_feed(cx: &Cx) -> Result<Response<Body>> {
140 let handle = handle_param(cx)?;
141 let name = repo_param(cx)?;
142
143 let entries = issue_feed(
144 &current_actor(cx).await?,
145 &handle,
146 &name,
147 &orgs(cx),
148 &memberships(cx),
149 &repos(cx),
150 &issues(cx),
151 &users(cx),
152 )
153 .await
154 .map_err(server_error)?
155 .ok_or_not_found()?;
156
157 let origin = public_origin(cx);
158 let handle = handle.as_str();
159 let name = name.as_str();
160 let path = issues_feed_path(handle, name);
161
162 let feed = Feed {
163 id: absolute(&origin, &path),
164 title: format!("{handle}/{name} issues"),
165 self_url: absolute(&origin, &path),
166 alternate: absolute(&origin, &format!("/{handle}/repos/{name}/issues")),
167 author: handle.to_owned(),
168 // The newest issue's own timestamp, not `now`: a feed whose `updated` moves on
169 // every poll tells a reader to re-fetch everything, every time.
170 updated: entries.first().map(|entry| entry.updated_at),
171 entries: entries
172 .iter()
173 .map(|entry| issue_entry(&origin, handle, name, entry))
174 .collect(),
175 };
176
177 served(feed.render())
178}
179
180/// One owner's recent pushes across the repositories the reader may see.
181///
182/// **The URL is `/{handle}/feed.atom`, not `/{handle}.atom`.** Topcoat's router matches
183/// whole segments — `{handle}.atom` is neither a parameter nor a literal and is refused
184/// when the route is registered — so the extension has to be a segment of its own. It
185/// also happens to be the scoped shape the rest of Steid's URLs use.
186///
187/// **No `git` processes and no subprocesses at all.** An entry names what moved and
188/// links to the page that can say what changed; counting the commits in a push would be
189/// a `git` process per entry, which is fifty per poll on an endpoint nobody has to be
190/// logged in to reach.
191#[route(GET "/{handle}/feed.atom")]
192async fn profile_feed(cx: &Cx) -> Result<Response<Body>> {
193 let handle = handle_param(cx)?;
194
195 let entries = activity_feed(
196 &handle,
197 &current_actor(cx).await?,
198 &orgs(cx),
199 &memberships(cx),
200 &repos(cx),
201 &push_events(cx),
202 &users(cx),
203 )
204 .await
205 .map_err(server_error)?
206 .ok_or_not_found()?;
207
208 let origin = public_origin(cx);
209 let handle = handle.as_str();
210 let path = profile_feed_path(handle);
211
212 let feed = Feed {
213 id: absolute(&origin, &path),
214 title: format!("@{handle}"),
215 self_url: absolute(&origin, &path),
216 alternate: absolute(&origin, &format!("/{handle}")),
217 author: handle.to_owned(),
218 updated: entries.first().map(|entry| entry.event.created_at),
219 entries: entries
220 .iter()
221 .map(|entry| activity_item(&origin, handle, entry))
222 .collect(),
223 };
224
225 served(feed.render())
226}
227
228/// `{name}` from the path, or 404 — the same answer a malformed name gets everywhere.
229fn repo_param(cx: &Cx) -> Result<RepoName> {
230 Ok(RepoName::new(path_param::<Name>(cx)).map_err(|_| not_found())?)
231}
232
233/// `?rev=`, or 404 for one that is not a revision at all.
234fn requested_rev(cx: &Cx) -> Result<Option<RefName>> {
235 query_params::<Query>(cx)?
236 .rev
237 .as_deref()
238 .filter(|rev| !rev.is_empty())
239 .map(|rev| RefName::new(rev).map_err(|_| not_found().into()))
240 .transpose()
241}
242
243/// A git read that failed is a feed that is not there, unless it is a real fault.
244///
245/// A `?rev=` naming something git cannot resolve reaches the adapter, and the adapter's
246/// rule is that a non-zero exit is a fault — true of the pages, and still true here, but
247/// a feed reader following a stale URL deserves a 404 rather than a 500 in the log.
248fn unreadable(error: crate::application::Error) -> topcoat::Error {
249 match &error {
250 crate::application::Error::GitQuery(GitQueryError { .. }) => not_found().into(),
251 _ => server_error(error),
252 }
253}
254
255/// A rendered feed, as the response a reader gets.
256fn served(body: String) -> Result<Response<Body>> {
257 Response::builder()
258 .header(CONTENT_TYPE, ATOM)
259 .body(Body::from(body))
260 .map_err(server_error)
261}
262
263// --- Entries --------------------------------------------------------------------------
264
265/// One commit: the subject as the title, the message body as the content.
266fn commit_entry(origin: &str, handle: &str, name: &str, entry: &CommitEntry) -> Entry {
267 let link = absolute(origin, &commit_url(handle, name, entry.commit.id.as_str()));
268
269 Entry {
270 // The commit page's URL, which is permanent and unique by construction — a sha
271 // names one commit in one repository forever.
272 id: link.clone(),
273 title: entry.commit.summary.clone(),
274 link,
275 updated: entry.commit.committed_at,
276 author: Some(entry.commit.author_name.clone()),
277 content: (!entry.body.is_empty()).then(|| Content::Text(entry.body.clone())),
278 }
279}
280
281/// One issue: the title, and the rendered body as escaped HTML.
282fn issue_entry(origin: &str, handle: &str, name: &str, entry: &IssueEntry) -> Entry {
283 let link = absolute(
284 origin,
285 &format!("/{handle}/repos/{name}/issues/{}", entry.number),
286 );
287
288 Entry {
289 id: link.clone(),
290 // The state is in the title because that is all a reader's list shows. "#4" is
291 // there for the same reason the list page has it: it is how the issue is named
292 // in conversation.
293 title: format!(
294 "#{} {}{}",
295 entry.number,
296 entry.title,
297 if entry.state.is_open() {
298 ""
299 } else {
300 " (closed)"
301 }
302 ),
303 link,
304 // The issue's own last change, so a comment or a close republishes the entry
305 // rather than leaving a reader with the version they first saw.
306 updated: entry.updated_at,
307 author: Some(
308 entry
309 .author
310 .as_ref()
311 .map(|handle| handle.as_str().to_owned())
312 .unwrap_or_else(|| "someone".to_owned()),
313 ),
314 content: (!entry.body.is_empty()).then(|| {
315 // The same cross-links the issue page draws, so `#12` in a reader is
316 // still a link to the issue it names — **absolute**, unlike the page's,
317 // because this content is read outside the site and a bare path there
318 // resolves against the reader, not against us.
319 Content::Html(
320 markdown::render(
321 &entry.body,
322 Some(markdown::Crossref {
323 handle,
324 name,
325 origin: Some(origin),
326 }),
327 )
328 .to_string(),
329 )
330 }),
331 }
332}
333
334/// One push: what moved, where, and the page that can say what changed.
335fn activity_item(origin: &str, handle: &str, entry: &ActivityEntry) -> Entry {
336 let name = entry.repo.as_str();
337 let event = &entry.event;
338 let short = event.short_ref();
339 let kind = event.ref_kind();
340
341 let (title, path) = if event.is_delete() {
342 (
343 format!("deleted {kind} {short} in {name}"),
344 format!("/{handle}/repos/{name}"),
345 )
346 } else if event.is_create() {
347 (
348 format!("created {kind} {short} in {name}"),
349 format!("/{handle}/repos/{name}/tree/{}", encode(short, false)),
350 )
351 } else if kind == "tag" {
352 (
353 format!("moved tag {short} in {name}"),
354 format!("/{handle}/repos/{name}/tree/{}", encode(short, false)),
355 )
356 } else {
357 (
358 format!("pushed to {name}/{short}"),
359 compare_url(handle, name, event.before.as_str(), event.after.as_str()),
360 )
361 };
362
363 Entry {
364 // The event's own id. A URL would not do: two pushes can land the same
365 // comparison, and an id that repeats makes a reader drop the second one.
366 id: format!("urn:uuid:{}", event.id),
367 title,
368 link: absolute(origin, &path),
369 updated: event.created_at,
370 author: entry
371 .pusher
372 .as_ref()
373 .map(|handle| handle.as_str().to_owned()),
374 // The two ends, so a reader with the feed open already knows what to compare
375 // without following the link. Free — both are on the row.
376 content: Some(Content::Text(if event.is_delete() {
377 format!("{} was deleted", event.before.short())
378 } else if event.is_create() {
379 format!("created at {}", event.after.short())
380 } else {
381 format!("{} \u{2192} {}", event.before.short(), event.after.short())
382 })),
383 }
384}
385
386// --- The document ---------------------------------------------------------------------
387
388/// What an entry carries as its body.
389///
390/// `Text` is written as-is inside a text node; `Html` is markup a reader unescapes and
391/// renders. Both are escaped identically on the way out — the type says what the reader
392/// should do with the result, not how it is written.
393enum Content {
394 Text(String),
395 Html(String),
396}
397
398/// One entry of a feed.
399struct Entry {
400 /// A permanent, unique identifier. Not a display value — a reader uses it to decide
401 /// whether it has seen this before.
402 id: String,
403 title: String,
404 link: String,
405 updated: SystemTime,
406 author: Option<String>,
407 content: Option<Content>,
408}
409
410/// A whole feed, ready to render.
411struct Feed {
412 id: String,
413 title: String,
414 /// Where this document lives, so a reader that was handed it can re-fetch it.
415 self_url: String,
416 /// The page this feed is a feed *of*.
417 alternate: String,
418 /// The handle the feed belongs to. Feed-level, so an entry whose own author is
419 /// unknown still leaves the document valid.
420 author: String,
421 /// The newest entry's timestamp, or `None` for an empty feed.
422 updated: Option<SystemTime>,
423 entries: Vec<Entry>,
424}
425
426impl Feed {
427 fn render(&self) -> String {
428 let mut out = String::with_capacity(2048 + self.entries.len() * 512);
429
430 out.push_str("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
431 out.push_str("<feed xmlns=\"http://www.w3.org/2005/Atom\">\n");
432 element(&mut out, 1, "id", &self.id);
433 element(&mut out, 1, "title", &self.title);
434 // An empty feed still needs an `updated`, and the epoch is the honest answer:
435 // nothing has happened yet.
436 element(
437 &mut out,
438 1,
439 "updated",
440 &rfc3339(self.updated.unwrap_or(UNIX_EPOCH)),
441 );
442 link(&mut out, 1, "self", ATOM_LINK, &self.self_url);
443 link(&mut out, 1, "alternate", "text/html", &self.alternate);
444 out.push_str(" <author><name>");
445 out.push_str(&escape(&self.author));
446 out.push_str("</name></author>\n");
447
448 for entry in &self.entries {
449 out.push_str(" <entry>\n");
450 element(&mut out, 2, "id", &entry.id);
451 element(&mut out, 2, "title", &entry.title);
452 element(&mut out, 2, "updated", &rfc3339(entry.updated));
453 link(&mut out, 2, "alternate", "text/html", &entry.link);
454
455 if let Some(author) = &entry.author {
456 out.push_str(" <author><name>");
457 out.push_str(&escape(author));
458 out.push_str("</name></author>\n");
459 }
460
461 match &entry.content {
462 Some(Content::Text(text)) => {
463 out.push_str(" <content type=\"text\">");
464 out.push_str(&escape(text));
465 out.push_str("</content>\n");
466 }
467 Some(Content::Html(html)) => {
468 out.push_str(" <content type=\"html\">");
469 out.push_str(&escape(html));
470 out.push_str("</content>\n");
471 }
472 None => {}
473 }
474
475 out.push_str(" </entry>\n");
476 }
477
478 out.push_str("</feed>\n");
479 out
480 }
481}
482
483/// One element on one line, its text escaped.
484fn element(out: &mut String, depth: usize, name: &str, text: &str) {
485 for _ in 0..depth {
486 out.push_str(" ");
487 }
488 out.push('<');
489 out.push_str(name);
490 out.push('>');
491 out.push_str(&escape(text));
492 out.push_str("</");
493 out.push_str(name);
494 out.push_str(">\n");
495}
496
497/// One `<link>`. The href is escaped like everything else — a repository name reaches
498/// it, and an attribute is exactly where an unescaped quote does damage.
499fn link(out: &mut String, depth: usize, rel: &str, kind: &str, href: &str) {
500 for _ in 0..depth {
501 out.push_str(" ");
502 }
503 out.push_str("<link rel=\"");
504 out.push_str(rel);
505 out.push_str("\" type=\"");
506 out.push_str(kind);
507 out.push_str("\" href=\"");
508 out.push_str(&escape(href));
509 out.push_str("\" />\n");
510}
511
512/// The one way text reaches a feed.
513///
514/// The five predefined entities, in text nodes and attribute values alike: writing one
515/// escaper rather than two removes the chance of picking the wrong one, and escaping
516/// `"` inside a text node is legal and harmless.
517///
518/// Characters XML 1.0 does not allow *at all* — most of the C0 controls — are dropped
519/// rather than escaped, because there is no escape for them: `&#x1;` is as illegal as
520/// the byte. A commit message can genuinely contain one, and a single stray byte would
521/// otherwise make the whole document unparseable.
522pub(super) fn escape(value: &str) -> String {
523 let mut out = String::with_capacity(value.len() + value.len() / 8);
524
525 for character in value.chars() {
526 match character {
527 '&' => out.push_str("&amp;"),
528 '<' => out.push_str("&lt;"),
529 '>' => out.push_str("&gt;"),
530 '"' => out.push_str("&quot;"),
531 '\'' => out.push_str("&apos;"),
532 '\t' | '\n' | '\r' => out.push(character),
533 // Legal: everything from the space up, plus the surrogate-free ranges the
534 // `char` type already guarantees.
535 character if character >= ' ' => out.push(character),
536 _ => {}
537 }
538 }
539
540 out
541}
542
543/// A timestamp as Atom writes it: RFC 3339, UTC, seconds.
544///
545/// The date maths is [`browse`](super::browse)'s, which is Steid's whole date library.
546fn rfc3339(time: SystemTime) -> String {
547 let seconds = time
548 .duration_since(UNIX_EPOCH)
549 .map(|since| since.as_secs() as i64)
550 .unwrap_or(0);
551
552 let (year, month, day) = super::browse::civil_from_days(seconds.div_euclid(86_400));
553 let rest = seconds.rem_euclid(86_400);
554
555 format!(
556 "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
557 rest / 3600,
558 (rest % 3600) / 60,
559 rest % 60
560 )
561}
562
563/// A path made absolute against the origin this request arrived on.
564///
565/// Atom wants absolute IRIs: a feed is read somewhere other than the site it came from,
566/// so a relative link has nothing to resolve against.
567fn absolute(origin: &str, path: &str) -> String {
568 format!("{origin}{path}")
569}
570
571// --- URLs and discovery -----------------------------------------------------------------
572
573pub(super) fn commits_feed_path(handle: &str, name: &str) -> String {
574 format!("/{handle}/repos/{name}/commits.atom")
575}
576
577pub(super) fn issues_feed_path(handle: &str, name: &str) -> String {
578 format!("/{handle}/repos/{name}/issues.atom")
579}
580
581pub(super) fn profile_feed_path(handle: &str) -> String {
582 format!("/{handle}/feed.atom")
583}
584
585/// The feed a page at `path` is the page for, if it has one.
586///
587/// **Autodiscovery is decided from the URL rather than contributed by the page**, and
588/// that is a constraint rather than a preference: the layout writes `<head>` and only a
589/// *layer* may put a value on the request context, so a page has nowhere to leave one.
590/// Deriving it here keeps the knowledge of which URLs have feeds in the module that
591/// serves them, with tests, instead of spreading it across three pages.
592///
593/// Only exact shapes match, so a tree, a blob or a settings page advertises nothing.
594/// A handle or a name the domain would refuse is not a page either — `RepoName` reserves
595/// `new`, which is what keeps `/{handle}/repos/new` out.
596pub(super) fn discovered(path: &str) -> Option<(String, String)> {
597 let segments: Vec<&str> = path.trim_matches('/').split('/').collect();
598
599 match segments[..] {
600 [handle] if OrgName::new(handle).is_ok() => {
601 Some((profile_feed_path(handle), format!("@{handle} activity")))
602 }
603 [handle, "repos", name] if OrgName::new(handle).is_ok() && RepoName::new(name).is_ok() => {
604 Some((
605 commits_feed_path(handle, name),
606 format!("{handle}/{name} commits"),
607 ))
608 }
609 [handle, "repos", name, "issues"]
610 if OrgName::new(handle).is_ok() && RepoName::new(name).is_ok() =>
611 {
612 Some((
613 issues_feed_path(handle, name),
614 format!("{handle}/{name} issues"),
615 ))
616 }
617 _ => None,
618 }
619}
620
621/// The muted "Feed" link a toolbar carries.
622///
623/// Muted on purpose: a feed is a way out of the page, not the thing the page is about,
624/// and `ui.md` reserves the primary colour for position and the one live thing.
625#[component]
626pub(super) async fn feed_link(href: &str) -> Result {
627 view! {
628 <a
629 href=(href)
630 title="Atom feed"
631 class="inline-flex shrink-0 items-center gap-1 text-xs text-muted-foreground hover:text-foreground"
632 >
633 icon(data: iconify_icon!("feather:rss"), attrs: attributes! { class="size-3.5" })
634 "Feed"
635 </a>
636 }
637}
638
639#[cfg(test)]
640mod tests {
641 use super::*;
642
643 #[test]
644 fn the_five_predefined_entities_are_escaped() {
645 assert_eq!(
646 escape("a < b & c > d \"quoted\" 'single'"),
647 "a &lt; b &amp; c &gt; d &quot;quoted&quot; &apos;single&apos;"
648 );
649 }
650
651 #[test]
652 fn markup_cannot_be_smuggled_through_a_title() {
653 assert_eq!(
654 escape("</title><script>alert(1)</script>"),
655 "&lt;/title&gt;&lt;script&gt;alert(1)&lt;/script&gt;"
656 );
657 }
658
659 #[test]
660 fn a_non_ascii_title_passes_through_unchanged() {
661 // The document says UTF-8, so there is nothing to escape here — a feed that
662 // turned these into entities would be correct and unreadable in a diff.
663 assert_eq!(
664 escape("Übergrößenträger — 日本語 · café"),
665 "Übergrößenträger — 日本語 · café"
666 );
667 }
668
669 #[test]
670 fn characters_xml_cannot_carry_are_dropped_rather_than_escaped() {
671 // A commit message really can contain a NUL or a bell, and there is no escape
672 // for either: `&#x0;` is as illegal as the byte itself.
673 assert_eq!(escape("before\u{0}\u{7}after"), "beforeafter");
674 assert_eq!(
675 escape("keep\tthe\nreal\rwhitespace"),
676 "keep\tthe\nreal\rwhitespace"
677 );
678 }
679
680 #[test]
681 fn timestamps_are_rfc_3339_in_utc() {
682 assert_eq!(
683 rfc3339(UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_000)),
684 "2023-11-14T22:13:20Z"
685 );
686 assert_eq!(rfc3339(UNIX_EPOCH), "1970-01-01T00:00:00Z");
687 }
688
689 fn feed_with(entries: Vec<Entry>) -> Feed {
690 Feed {
691 id: "https://example.com/ada/repos/steid/commits.atom".to_owned(),
692 title: "ada/steid commits".to_owned(),
693 self_url: "https://example.com/ada/repos/steid/commits.atom".to_owned(),
694 alternate: "https://example.com/ada/repos/steid".to_owned(),
695 author: "ada".to_owned(),
696 updated: entries.first().map(|entry| entry.updated),
697 entries,
698 }
699 }
700
701 #[test]
702 fn an_empty_feed_is_still_a_document_with_an_updated() {
703 let rendered = feed_with(Vec::new()).render();
704
705 assert!(rendered.starts_with("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<feed"));
706 assert!(rendered.contains("<updated>1970-01-01T00:00:00Z</updated>"));
707 assert!(rendered.ends_with("</feed>\n"));
708 assert!(!rendered.contains("<entry>"));
709 }
710
711 #[test]
712 fn every_value_in_an_entry_is_escaped() {
713 let rendered = feed_with(vec![Entry {
714 id: "https://example.com/x?a=1&b=2".to_owned(),
715 title: "fix <T> & co".to_owned(),
716 link: "https://example.com/ada/repos/steid/tree/feat%2F<x>".to_owned(),
717 updated: UNIX_EPOCH + std::time::Duration::from_secs(86_400),
718 author: Some("Ada & Co".to_owned()),
719 content: Some(Content::Html("<p>a &amp; b</p>".to_owned())),
720 }])
721 .render();
722
723 assert!(rendered.contains("<title>fix &lt;T&gt; &amp; co</title>"));
724 assert!(rendered.contains("<id>https://example.com/x?a=1&amp;b=2</id>"));
725 assert!(
726 rendered.contains("href=\"https://example.com/ada/repos/steid/tree/feat%2F&lt;x&gt;\"")
727 );
728 assert!(rendered.contains("<name>Ada &amp; Co</name>"));
729 assert!(
730 rendered.contains("<content type=\"html\">&lt;p&gt;a &amp;amp; b&lt;/p&gt;</content>"),
731 "rendered markdown is escaped once more, which is what type=\"html\" means"
732 );
733 assert!(rendered.contains("<updated>1970-01-02T00:00:00Z</updated>"));
734 }
735
736 #[test]
737 fn only_the_three_page_shapes_advertise_a_feed() {
738 assert_eq!(
739 discovered("/ada"),
740 Some(("/ada/feed.atom".to_owned(), "@ada activity".to_owned()))
741 );
742 assert_eq!(
743 discovered("/ada/repos/steid"),
744 Some((
745 "/ada/repos/steid/commits.atom".to_owned(),
746 "ada/steid commits".to_owned()
747 ))
748 );
749 assert_eq!(
750 discovered("/ada/repos/steid/issues"),
751 Some((
752 "/ada/repos/steid/issues.atom".to_owned(),
753 "ada/steid issues".to_owned()
754 ))
755 );
756 }
757
758 #[test]
759 fn nothing_else_advertises_one() {
760 for path in [
761 "/",
762 "/ada/repos",
763 "/ada/settings",
764 "/ada/repos/new",
765 "/ada/repos/steid/log",
766 "/ada/repos/steid/issues/4",
767 "/ada/repos/steid/tree/main",
768 "/not a handle",
769 ] {
770 assert_eq!(discovered(path), None, "{path} should advertise no feed");
771 }
772 }
773}