Make most links typesafe

This commit is contained in:
Joscha 2023-08-13 20:24:37 +02:00
parent 30ddf1e9b2
commit e64ea7ac12
10 changed files with 82 additions and 100 deletions

View file

@ -12,7 +12,7 @@ mod worker;
use axum::{routing::get, Router}; use axum::{routing::get, Router};
use axum_extra::routing::RouterExt; use axum_extra::routing::RouterExt;
use crate::{config::Config, somehow}; use crate::somehow;
use self::{ use self::{
admin::queue::post_admin_queue_add, admin::queue::post_admin_queue_add,
@ -28,34 +28,6 @@ use self::{
use super::Server; use super::Server;
pub enum Tab {
None,
Index,
Queue,
}
#[derive(Clone)]
pub struct Base {
root: String,
repo_name: String,
current: &'static str,
}
impl Base {
pub fn new(config: &Config, tab: Tab) -> Self {
let current = match tab {
Tab::None => "",
Tab::Index => "index",
Tab::Queue => "queue",
};
Self {
root: config.web_base.clone(),
repo_name: config.repo_name.clone(),
current,
}
}
}
pub async fn run(server: Server) -> somehow::Result<()> { pub async fn run(server: Server) -> somehow::Result<()> {
// TODO Add text body to body-less status codes // TODO Add text body to body-less status codes

View file

@ -2,6 +2,8 @@ use std::fmt;
use crate::config::Config; use crate::config::Config;
use super::paths::{PathIndex, PathQueue};
pub enum Tab { pub enum Tab {
None, None,
Index, Index,
@ -10,9 +12,13 @@ pub enum Tab {
#[derive(Clone)] #[derive(Clone)]
pub struct Base { pub struct Base {
web_base: String, pub link_logo_svg: Link,
repo_name: String, pub link_base_css: Link,
tab: &'static str, pub link_index: Link,
pub link_queue: Link,
pub web_base: String,
pub repo_name: String,
pub tab: &'static str,
} }
impl Base { impl Base {
@ -23,20 +29,29 @@ impl Base {
Tab::Queue => "queue", Tab::Queue => "queue",
}; };
Self { Self {
link_logo_svg: Self::link_from_base(&config.web_base, "/logo.svg"), // TODO Static link
link_base_css: Self::link_from_base(&config.web_base, "/base.css"), // TODO Static link
link_index: Self::link_from_base(&config.web_base, PathIndex {}),
link_queue: Self::link_from_base(&config.web_base, PathQueue {}),
web_base: config.web_base.clone(), web_base: config.web_base.clone(),
repo_name: config.repo_name.clone(), repo_name: config.repo_name.clone(),
tab, tab,
} }
} }
pub fn link<P: fmt::Display>(&self, to: P) -> Link { fn link_from_base<P: fmt::Display>(base: &str, to: P) -> Link {
let to = format!("{to}"); let to = format!("{to}");
assert!(!self.web_base.ends_with('/')); assert!(!base.ends_with('/'));
assert!(to.starts_with('/')); assert!(to.starts_with('/'));
Link(format!("{}{to}", self.web_base)) Link(format!("{base}{to}"))
}
pub fn link<P: fmt::Display>(&self, to: P) -> Link {
Self::link_from_base(&self.web_base, to)
} }
} }
#[derive(Clone)]
pub struct Link(String); pub struct Link(String);
impl fmt::Display for Link { impl fmt::Display for Link {

View file

@ -10,26 +10,26 @@ use sqlx::SqlitePool;
use crate::{config::Config, server::util, somehow}; use crate::{config::Config, server::util, somehow};
use super::{ use super::{
link::CommitLink, base::{Base, Link, Tab},
link::LinkCommit,
paths::{PathAdminQueueAdd, PathCommitByHash}, paths::{PathAdminQueueAdd, PathCommitByHash},
Base, Tab,
}; };
#[derive(Template)] #[derive(Template)]
#[template(path = "commit.html")] #[template(path = "commit.html")]
struct CommitTemplate { struct CommitTemplate {
link_admin_queue_add: Link,
base: Base, base: Base,
hash: String, hash: String,
author: String, author: String,
author_date: String, author_date: String,
commit: String, commit: String,
commit_date: String, commit_date: String,
parents: Vec<CommitLink>, parents: Vec<LinkCommit>,
children: Vec<CommitLink>, children: Vec<LinkCommit>,
summary: String, summary: String,
message: String, message: String,
reachable: i64, reachable: i64,
link_admin_queue_add: PathAdminQueueAdd,
} }
pub async fn get_commit_by_hash( pub async fn get_commit_by_hash(
@ -70,7 +70,7 @@ pub async fn get_commit_by_hash(
path.hash, path.hash,
) )
.fetch(&db) .fetch(&db)
.map_ok(|r| CommitLink::new(&base, r.hash, &r.message, r.reachable)) .map_ok(|r| LinkCommit::new(&base, r.hash, &r.message, r.reachable))
.try_collect::<Vec<_>>() .try_collect::<Vec<_>>()
.await?; .await?;
@ -84,11 +84,12 @@ pub async fn get_commit_by_hash(
path.hash, path.hash,
) )
.fetch(&db) .fetch(&db)
.map_ok(|r| CommitLink::new(&base, r.hash, &r.message, r.reachable)) .map_ok(|r| LinkCommit::new(&base, r.hash, &r.message, r.reachable))
.try_collect::<Vec<_>>() .try_collect::<Vec<_>>()
.await?; .await?;
Ok(CommitTemplate { Ok(CommitTemplate {
link_admin_queue_add: base.link(PathAdminQueueAdd {}),
base, base,
hash: commit.hash, hash: commit.hash,
author: commit.author, author: commit.author,
@ -100,7 +101,6 @@ pub async fn get_commit_by_hash(
summary: util::format_commit_summary(&commit.message), summary: util::format_commit_summary(&commit.message),
message: commit.message.trim_end().to_string(), message: commit.message.trim_end().to_string(),
reachable: commit.reachable, reachable: commit.reachable,
link_admin_queue_add: PathAdminQueueAdd {},
} }
.into_response()) .into_response())
} }

View file

@ -5,11 +5,15 @@ use sqlx::SqlitePool;
use crate::{config::Config, somehow}; use crate::{config::Config, somehow};
use super::{link::CommitLink, paths::PathIndex, Base, Tab}; use super::{
base::{Base, Tab},
link::LinkCommit,
paths::PathIndex,
};
struct Ref { struct Ref {
name: String, name: String,
commit: CommitLink, commit: LinkCommit,
tracked: bool, tracked: bool,
} }
@ -39,7 +43,7 @@ pub async fn get_index(
.fetch(&db) .fetch(&db)
.map_ok(|r| Ref { .map_ok(|r| Ref {
name: r.name.clone(), name: r.name.clone(),
commit: CommitLink::new(&base, r.hash, &r.message, r.reachable), commit: LinkCommit::new(&base, r.hash, &r.message, r.reachable),
tracked: r.tracked != 0, tracked: r.tracked != 0,
}) })
.try_collect::<Vec<_>>() .try_collect::<Vec<_>>()

View file

@ -2,80 +2,66 @@ use askama::Template;
use crate::server::util; use crate::server::util;
use super::Base; use super::{
base::{Base, Link},
paths::{PathCommitByHash, PathRunById, PathWorkerByName},
};
#[derive(Template)] #[derive(Template)]
#[template( #[template(
ext = "html", ext = "html",
source = "\ source = "\
{% import \"util.html\" as util %} {% import \"util.html\" as util %}
<a href=\"{{ root }}/commit/{{ hash }}\" <a href=\"{{ link }}\" \
class=\"{% call util::commit_class(reachable) %}\" class=\"{% call util::commit_class(reachable) %}\" \
title=\"{% call util::commit_title(reachable) %}\"> title=\"{% call util::commit_title(reachable) %}\">
{{ short }} {{ short }}
</a> </a>
" "
)] )]
pub struct CommitLink { pub struct LinkCommit {
root: String, link: Link,
hash: String,
short: String, short: String,
reachable: i64, reachable: i64,
} }
impl CommitLink { impl LinkCommit {
pub fn new(base: &Base, hash: String, message: &str, reachable: i64) -> Self { pub fn new(base: &Base, hash: String, message: &str, reachable: i64) -> Self {
Self { Self {
root: base.root.clone(),
short: util::format_commit_short(&hash, message), short: util::format_commit_short(&hash, message),
hash, link: base.link(PathCommitByHash { hash }),
reachable, reachable,
} }
} }
} }
#[derive(Template)] #[derive(Template)]
#[template( #[template(ext = "html", source = "<a href=\"{{ link }}\">Run of {{ short }}</a>")]
ext = "html", pub struct LinkRunShort {
source = "\ link: Link,
<a href=\"{{ root }}/run/{{ id }}\">
Run of {{ short }}
</a>
"
)]
pub struct RunLink {
root: String,
id: String,
short: String, short: String,
} }
impl RunLink { impl LinkRunShort {
pub fn new(base: &Base, id: String, hash: &str, message: &str) -> Self { pub fn new(base: &Base, id: String, hash: &str, message: &str) -> Self {
Self { Self {
root: base.root.clone(), link: base.link(PathRunById { id }),
id,
short: util::format_commit_short(hash, message), short: util::format_commit_short(hash, message),
} }
} }
} }
#[derive(Template)] #[derive(Template)]
#[template( #[template(ext = "html", source = "<a href=\"{{ link }}\">{{ name }}</a>")]
ext = "html", pub struct LinkWorker {
source = "\ link: Link,
<a href=\"{{ root }}/worker/{{ name }}\">
{{ name }}
</a>
"
)]
pub struct WorkerLink {
root: String,
name: String, name: String,
} }
impl WorkerLink { impl LinkWorker {
pub fn new(base: &Base, name: String) -> Self { pub fn new(base: &Base, name: String) -> Self {
Self { Self {
root: base.root.clone(), link: base.link(PathWorkerByName { name: name.clone() }),
name, name,
} }
} }

View file

@ -19,27 +19,27 @@ use crate::{
}; };
use super::{ use super::{
link::{CommitLink, RunLink, WorkerLink}, base::{Base, Link, Tab},
link::{LinkCommit, LinkRunShort, LinkWorker},
paths::{PathQueue, PathQueueInner}, paths::{PathQueue, PathQueueInner},
Base, Tab,
}; };
enum Status { enum Status {
Idle, Idle,
Busy, Busy,
Working(RunLink), Working(LinkRunShort),
} }
struct Worker { struct Worker {
link: WorkerLink, link: LinkWorker,
status: Status, status: Status,
} }
struct Task { struct Task {
commit: CommitLink, commit: LinkCommit,
since: String, since: String,
priority: i64, priority: i64,
workers: Vec<WorkerLink>, workers: Vec<LinkWorker>,
odd: bool, odd: bool,
} }
@ -72,7 +72,7 @@ async fn get_workers(
) )
.fetch_one(db) .fetch_one(db)
.await?; .await?;
Status::Working(RunLink::new( Status::Working(LinkRunShort::new(
base, base,
unfinished.run.id.clone(), unfinished.run.id.clone(),
&unfinished.run.hash, &unfinished.run.hash,
@ -82,7 +82,7 @@ async fn get_workers(
}; };
result.push(Worker { result.push(Worker {
link: WorkerLink::new(base, name.clone()), link: LinkWorker::new(base, name.clone()),
status, status,
}) })
} }
@ -95,13 +95,13 @@ async fn get_queue_data(
base: &Base, base: &Base,
) -> somehow::Result<Vec<Task>> { ) -> somehow::Result<Vec<Task>> {
// Group workers by commit hash // Group workers by commit hash
let mut workers_by_commit: HashMap<String, Vec<WorkerLink>> = HashMap::new(); let mut workers_by_commit: HashMap<String, Vec<LinkWorker>> = HashMap::new();
for (name, info) in workers { for (name, info) in workers {
if let WorkerStatus::Working(unfinished) = &info.status { if let WorkerStatus::Working(unfinished) = &info.status {
workers_by_commit workers_by_commit
.entry(unfinished.run.hash.clone()) .entry(unfinished.run.hash.clone())
.or_default() .or_default()
.push(WorkerLink::new(base, name.clone())); .push(LinkWorker::new(base, name.clone()));
} }
} }
@ -121,7 +121,7 @@ async fn get_queue_data(
.fetch(db) .fetch(db)
.map_ok(|r| Task { .map_ok(|r| Task {
workers: workers_by_commit.remove(&r.hash).unwrap_or_default(), workers: workers_by_commit.remove(&r.hash).unwrap_or_default(),
commit: CommitLink::new(base, r.hash, &r.message, r.reachable), commit: LinkCommit::new(base, r.hash, &r.message, r.reachable),
since: util::format_delta_from_now(r.date), since: util::format_delta_from_now(r.date),
priority: r.priority, priority: r.priority,
odd: false, odd: false,
@ -164,6 +164,7 @@ pub async fn get_queue_inner(
#[derive(Template)] #[derive(Template)]
#[template(path = "queue.html")] #[template(path = "queue.html")]
struct QueueTemplate { struct QueueTemplate {
link_queue_js: Link,
base: Base, base: Base,
inner: QueueInnerTemplate, inner: QueueInnerTemplate,
} }
@ -179,6 +180,7 @@ pub async fn get_queue(
let workers = get_workers(&db, &sorted_workers, &base).await?; let workers = get_workers(&db, &sorted_workers, &base).await?;
let tasks = get_queue_data(&db, &sorted_workers, &base).await?; let tasks = get_queue_data(&db, &sorted_workers, &base).await?;
Ok(QueueTemplate { Ok(QueueTemplate {
link_queue_js: base.link("/queue.js"), // TODO Static link
base, base,
inner: QueueInnerTemplate { workers, tasks }, inner: QueueInnerTemplate { workers, tasks },
}) })

View file

@ -13,7 +13,10 @@ use crate::{
somehow, somehow,
}; };
use super::{paths::PathWorkerByName, Base, Tab}; use super::{
base::{Base, Tab},
paths::PathWorkerByName,
};
#[derive(Template)] #[derive(Template)]
#[template(path = "worker.html")] #[template(path = "worker.html")]

View file

@ -5,17 +5,17 @@
<meta charset="utf-8" /> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width" /> <meta name="viewport" content="width=device-width" />
<title>{% block title %}{% endblock %} - {{ base.repo_name }}</title> <title>{% block title %}{% endblock %} - {{ base.repo_name }}</title>
<link rel="icon" href="{{ base.root }}/logo.svg"> <link rel="icon" href="{{ base.link_logo_svg }}">
<link rel="stylesheet" href="{{ base.root }}/base.css" /> <link rel="stylesheet" href="{{ base.link_base_css }}" />
{% block head %}{% endblock %} {% block head %}{% endblock %}
</head> </head>
<body> <body>
<nav> <nav>
<a href="{{ base.root }}/" {% if base.current=="index" %} class="current" {% endif %}> <a href="{{ base.link_index }}" {% if base.tab=="index" %} class="current" {% endif %}>
<img src="{{ base.root }}/logo.svg" alt="">{{ base.repo_name }} <img src="{{ base.link_logo_svg }}" alt="">{{ base.repo_name }}
</a> </a>
<a href="{{ base.root }}/queue/" {% if base.current=="queue" %} class="current" {% endif %}> <a href="{{ base.link_queue }}" {% if base.tab=="queue" %} class="current" {% endif %}>
queue queue
</a> </a>
</nav> </nav>

View file

@ -34,7 +34,7 @@
title="{% call util::commit_title(reachable) %}">{{ message }}</pre> title="{% call util::commit_title(reachable) %}">{{ message }}</pre>
</div> </div>
<form method="post" action="{{ base.root }}{{ link_admin_queue_add }}"> <form method="post" action="{{ link_admin_queue_add }}">
<input type="hidden" name="hash" value="{{ hash }}"> <input type="hidden" name="hash" value="{{ hash }}">
<label>Priority: <input type="number" name="priority" value="0" min="-2147483648" max="2147483647"></label> <label>Priority: <input type="number" name="priority" value="0" min="-2147483648" max="2147483647"></label>
<button>Add to queue</button> <button>Add to queue</button>

View file

@ -3,7 +3,7 @@
{% block title %}queue ({{ inner.tasks.len() }}){% endblock %} {% block title %}queue ({{ inner.tasks.len() }}){% endblock %}
{% block head %} {% block head %}
<script type="module" src="{{ base.root }}/queue.js"></script> <script type="module" src="{{ link_queue_js }}"></script>
{% endblock %} {% endblock %}
{% block body %} {% block body %}