Skip to content

Commit

Permalink
Replace tera with rinja
Browse files Browse the repository at this point in the history
  • Loading branch information
GuillaumeGomez committed Jul 5, 2024
1 parent 55314a2 commit 0683a5d
Show file tree
Hide file tree
Showing 56 changed files with 1,574 additions and 1,320 deletions.
455 changes: 147 additions & 308 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ tempfile = "3.1.0"
fn-error-context = "0.2.0"

# Templating
tera = { version = "1.5.0", features = ["builtins"] }
rinja = { git = "https://github.com/rinja-rs/rinja" }
walkdir = "2"

# Date and Time utilities
Expand Down
10 changes: 10 additions & 0 deletions src/db/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,16 @@ impl sqlx::postgres::PgHasArrayType for BuildStatus {
}
}

impl<'a> PartialEq<&'a str> for BuildStatus {
fn eq(&self, other: &&str) -> bool {
match self {
Self::Success => *other == "success",
Self::Failure => *other == "failure",
Self::InProgress => *other == "in_progress",
}
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
10 changes: 5 additions & 5 deletions src/docbuilder/limits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ const GB: usize = 1024 * 1024 * 1024;

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub(crate) struct Limits {
memory: usize,
targets: usize,
timeout: Duration,
networking: bool,
max_log_size: usize,
pub memory: usize,
pub targets: usize,
pub timeout: Duration,
pub networking: bool,
pub max_log_size: usize,
}

impl Limits {
Expand Down
10 changes: 10 additions & 0 deletions src/registry_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use chrono::{DateTime, Utc};
use reqwest::header::{HeaderValue, ACCEPT, USER_AGENT};
use semver::Version;
use serde::{Deserialize, Serialize};
use std::fmt;
use tracing::instrument;
use url::Url;

Expand Down Expand Up @@ -59,6 +60,15 @@ pub enum OwnerKind {
Team,
}

impl fmt::Display for OwnerKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::User => f.write_str("user"),
Self::Team => f.write_str("team"),
}
}
}

impl RegistryApi {
pub fn new(api_base: Url, max_retries: u32) -> Result<Self> {
let headers = vec![
Expand Down
27 changes: 13 additions & 14 deletions src/utils/html.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use crate::web::page::TemplateData;
use crate::web::page::templates::{Body, Head, Topbar, Vendored};
use crate::web::rustdoc::RustdocPage;
use lol_html::element;
use lol_html::errors::RewritingError;
use tera::Context;
use rinja::Template;

/// Rewrite a rustdoc page to have the docs.rs topbar
///
Expand All @@ -12,17 +13,15 @@ use tera::Context;
pub(crate) fn rewrite_lol(
html: &[u8],
max_allowed_memory_usage: usize,
ctx: Context,
templates: &TemplateData,
data: &RustdocPage,
) -> Result<Vec<u8>, RewritingError> {
use lol_html::html_content::{ContentType, Element};
use lol_html::{HtmlRewriter, MemorySettings, Settings};

let templates = &templates.templates;
let tera_head = templates.render("rustdoc/head.html", &ctx).unwrap();
let tera_vendored_css = templates.render("rustdoc/vendored.html", &ctx).unwrap();
let tera_body = templates.render("rustdoc/body.html", &ctx).unwrap();
let tera_rustdoc_topbar = templates.render("rustdoc/topbar.html", &ctx).unwrap();
let head_html = Head::new(data).render().unwrap();
let vendored_html = Vendored::new(data).render().unwrap();
let body_html = Body::new(data).render().unwrap();
let topbar_html = Topbar::new(data).render().unwrap();

// Before: <body> ... rustdoc content ... </body>
// After:
Expand All @@ -46,12 +45,12 @@ pub(crate) fn rewrite_lol(
rustdoc_body_class.set_attribute("tabindex", "-1")?;
// Change the `body` to a `div`
rustdoc_body_class.set_tag_name("div")?;
// Prepend the tera content
rustdoc_body_class.prepend(&tera_body, ContentType::Html);
// Prepend the rinja content
rustdoc_body_class.prepend(&body_html, ContentType::Html);
// Wrap the transformed body and topbar into a <body> element
rustdoc_body_class.before(r#"<body class="rustdoc-page">"#, ContentType::Html);
// Insert the topbar outside of the rustdoc div
rustdoc_body_class.before(&tera_rustdoc_topbar, ContentType::Html);
rustdoc_body_class.before(&topbar_html, ContentType::Html);
// Finalize body with </body>
rustdoc_body_class.after("</body>", ContentType::Html);

Expand All @@ -62,7 +61,7 @@ pub(crate) fn rewrite_lol(
element_content_handlers: vec![
// Append `style.css` stylesheet after all head elements.
element!("head", |head: &mut Element| {
head.append(&tera_head, ContentType::Html);
head.append(&head_html, ContentType::Html);
Ok(())
}),
element!("body", body_handler),
Expand All @@ -81,7 +80,7 @@ pub(crate) fn rewrite_lol(
element!(
"link[rel='stylesheet'][href*='rustdoc-']",
|rustdoc_css: &mut Element| {
rustdoc_css.before(&tera_vendored_css, ContentType::Html);
rustdoc_css.before(&vendored_html, ContentType::Html);
Ok(())
}
),
Expand Down
25 changes: 22 additions & 3 deletions src/web/build_details.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,19 @@ use crate::{
db::types::BuildStatus,
impl_axum_webpage,
web::{
crate_details::CrateDetails,
error::{AxumNope, AxumResult},
extractors::{DbConnection, Path},
file::File,
MetaData,
filters, MetaData,
},
AsyncStorage, Config,
};
use anyhow::Context as _;
use axum::{extract::Extension, response::IntoResponse};
use chrono::{DateTime, Utc};
use futures_util::TryStreamExt;
use rinja::Template;
use semver::Version;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
Expand All @@ -28,17 +30,33 @@ pub(crate) struct BuildDetails {
errors: Option<String>,
}

#[derive(Template)]
#[template(path = "crate/build_details.html")]
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
struct BuildDetailsPage {
metadata: MetaData,
build_details: BuildDetails,
use_direct_platform_links: bool,
all_log_filenames: Vec<String>,
current_filename: Option<String>,
csp_nonce: String,
}

impl_axum_webpage! {
BuildDetailsPage = "crate/build_details.html",
impl_axum_webpage! { BuildDetailsPage }

// Used for template rendering.
impl BuildDetailsPage {
pub(crate) fn krate(&self) -> Option<&CrateDetails> {
None
}

pub(crate) fn permalink_path(&self) -> &str {
""
}

pub(crate) fn get_metadata(&self) -> Option<&MetaData> {
Some(&self.metadata)
}
}

#[derive(Clone, Deserialize, Debug)]
Expand Down Expand Up @@ -126,6 +144,7 @@ pub(crate) async fn build_details_handler(
use_direct_platform_links: true,
all_log_filenames,
current_filename,
csp_nonce: String::new(),
}
.into_response())
}
Expand Down
24 changes: 21 additions & 3 deletions src/web/builds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ use crate::{
docbuilder::Limits,
impl_axum_webpage,
web::{
crate_details::CrateDetails,
error::AxumResult,
extractors::{DbConnection, Path},
match_version, MetaData, ReqVersion,
filters, match_version, MetaData, ReqVersion,
},
Config,
};
Expand All @@ -15,6 +16,7 @@ use axum::{
extract::Extension, http::header::ACCESS_CONTROL_ALLOW_ORIGIN, response::IntoResponse, Json,
};
use chrono::{DateTime, Utc};
use rinja::Template;
use semver::Version;
use serde::Serialize;
use std::sync::Arc;
Expand All @@ -29,17 +31,32 @@ pub(crate) struct Build {
errors: Option<String>,
}

#[derive(Template)]
#[template(path = "crate/builds.html")]
#[derive(Debug, Clone, Serialize)]
struct BuildsPage {
metadata: MetaData,
builds: Vec<Build>,
limits: Limits,
canonical_url: CanonicalUrl,
use_direct_platform_links: bool,
csp_nonce: String,
}

impl_axum_webpage! {
BuildsPage = "crate/builds.html",
impl_axum_webpage! { BuildsPage }

impl BuildsPage {
pub(crate) fn krate(&self) -> Option<&CrateDetails> {
None
}

pub(crate) fn permalink_path(&self) -> &str {
""
}

pub(crate) fn get_metadata(&self) -> Option<&MetaData> {
Some(&self.metadata)
}
}

pub(crate) async fn build_list_handler(
Expand All @@ -64,6 +81,7 @@ pub(crate) async fn build_list_handler(
limits: Limits::for_crate(&config, &mut conn, &name).await?,
canonical_url: CanonicalUrl::from_path(format!("/crate/{name}/latest/builds")),
use_direct_platform_links: true,
csp_nonce: String::new(),
}
.into_response())
}
Expand Down
Loading

0 comments on commit 0683a5d

Please sign in to comment.