Implement endpoint for cache deletion
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Valentin Brandl 2020-05-15 13:15:54 +02:00
parent 1d0eca90a7
commit 349640acc5
No known key found for this signature in database
GPG Key ID: 30D341DD34118D7D
2 changed files with 64 additions and 9 deletions

View File

@ -28,8 +28,8 @@ use crate::{
template::RepoInfo, template::RepoInfo,
}; };
use actix_web::{ use actix_web::{
http::header::{CacheControl, CacheDirective, Expires}, http::header::{CacheControl, CacheDirective, Expires, LOCATION},
middleware, web, App, HttpResponse, HttpServer, middleware, web, App, HttpResponse, HttpServer, Responder,
}; };
use badge::{Badge, BadgeOptions}; use badge::{Badge, BadgeOptions};
use git2::Repository; use git2::Repository;
@ -37,6 +37,7 @@ use number_prefix::NumberPrefix;
use std::{ use std::{
borrow::Cow, borrow::Cow,
fs::create_dir_all, fs::create_dir_all,
io,
path::Path, path::Path,
process::Command, process::Command,
sync::atomic::Ordering, sync::atomic::Ordering,
@ -148,9 +149,6 @@ fn hoc(repo: &str, repo_dir: &str, cache_dir: &str) -> Result<(u64, String, u64)
async fn remote_exists(url: &str) -> Result<bool> { async fn remote_exists(url: &str) -> Result<bool> {
let resp = CLIENT.head(url).send().await?; let resp = CLIENT.head(url).send().await?;
Ok(resp.status() == reqwest::StatusCode::OK) Ok(resp.status() == reqwest::StatusCode::OK)
// .map(|resp| resp.status() == reqwest::StatusCode::OK)
// .from_err()
} }
enum HocResult { enum HocResult {
@ -166,6 +164,45 @@ enum HocResult {
NotFound, NotFound,
} }
async fn delete_repo_and_cache<T>(
state: web::Data<Arc<State>>,
data: web::Path<(String, String)>,
) -> Result<impl Responder>
where
T: Service,
{
let repo = format!(
"{}/{}/{}",
T::domain(),
data.0.to_lowercase(),
data.1.to_lowercase()
);
info!("Deleting cache and repository for {}", repo);
let cache_dir = dbg!(format!("{}/{}.json", &state.cache, repo));
let repo_dir = dbg!(format!("{}/{}", &state.repos, repo));
std::fs::remove_file(&cache_dir).or_else(|e| {
if e.kind() == io::ErrorKind::NotFound {
Ok(())
} else {
Err(e)
}
})?;
std::fs::remove_dir_all(&repo_dir).or_else(|e| {
if e.kind() == io::ErrorKind::NotFound {
Ok(())
} else {
Err(e)
}
})?;
REPO_COUNT.fetch_sub(1, Ordering::Relaxed);
Ok(HttpResponse::TemporaryRedirect()
.header(
LOCATION,
format!("/view/{}/{}/{}", T::url_path(), data.0, data.1),
)
.finish())
}
async fn handle_hoc_request<T, F>( async fn handle_hoc_request<T, F>(
state: web::Data<Arc<State>>, state: web::Data<Arc<State>>,
data: web::Path<(String, String)>, data: web::Path<(String, String)>,
@ -176,9 +213,10 @@ where
F: Fn(HocResult) -> Result<HttpResponse>, F: Fn(HocResult) -> Result<HttpResponse>,
{ {
let repo = format!("{}/{}", data.0.to_lowercase(), data.1.to_lowercase()); let repo = format!("{}/{}", data.0.to_lowercase(), data.1.to_lowercase());
let service_path = format!("{}/{}", T::domain(), repo); let service_path = format!("{}/{}", T::url_path(), repo);
let path = format!("{}/{}", state.repos, service_path); let service_url = format!("{}/{}", T::domain(), repo);
let url = format!("https://{}", service_path); let path = format!("{}/{}", state.repos, service_url);
let url = format!("https://{}", service_url);
error!("{}", url); error!("{}", url);
let remote_exists = remote_exists(&url).await?; let remote_exists = remote_exists(&url).await?;
let file = Path::new(&path); let file = Path::new(&path);
@ -195,7 +233,7 @@ where
REPO_COUNT.fetch_add(1, Ordering::Relaxed); REPO_COUNT.fetch_add(1, Ordering::Relaxed);
} }
pull(&path)?; pull(&path)?;
let (hoc, head, commits) = hoc(&service_path, &state.repos, &state.cache)?; let (hoc, head, commits) = hoc(&service_url, &state.repos, &state.cache)?;
let hoc_pretty = match NumberPrefix::decimal(hoc as f64) { let hoc_pretty = match NumberPrefix::decimal(hoc as f64) {
NumberPrefix::Standalone(hoc) => hoc.to_string(), NumberPrefix::Standalone(hoc) => hoc.to_string(),
NumberPrefix::Prefixed(prefix, hoc) => format!("{:.1}{}", hoc, prefix), NumberPrefix::Prefixed(prefix, hoc) => format!("{:.1}{}", hoc, prefix),
@ -367,6 +405,18 @@ async fn start_server() -> std::io::Result<()> {
.service(web::resource("/github/{user}/{repo}").to(calculate_hoc::<GitHub>)) .service(web::resource("/github/{user}/{repo}").to(calculate_hoc::<GitHub>))
.service(web::resource("/gitlab/{user}/{repo}").to(calculate_hoc::<Gitlab>)) .service(web::resource("/gitlab/{user}/{repo}").to(calculate_hoc::<Gitlab>))
.service(web::resource("/bitbucket/{user}/{repo}").to(calculate_hoc::<Bitbucket>)) .service(web::resource("/bitbucket/{user}/{repo}").to(calculate_hoc::<Bitbucket>))
.service(
web::resource("/github/{user}/{repo}/delete")
.route(web::post().to(delete_repo_and_cache::<GitHub>)),
)
.service(
web::resource("/gitlab/{user}/{repo}/delete")
.route(web::post().to(delete_repo_and_cache::<Gitlab>)),
)
.service(
web::resource("/bitbucket/{user}/{repo}/delete")
.route(web::post().to(delete_repo_and_cache::<Bitbucket>)),
)
.service(web::resource("/github/{user}/{repo}/json").to(json_hoc::<GitHub>)) .service(web::resource("/github/{user}/{repo}/json").to(json_hoc::<GitHub>))
.service(web::resource("/gitlab/{user}/{repo}/json").to(json_hoc::<Gitlab>)) .service(web::resource("/gitlab/{user}/{repo}/json").to(json_hoc::<Gitlab>))
.service(web::resource("/bitbucket/{user}/{repo}/json").to(json_hoc::<Bitbucket>)) .service(web::resource("/bitbucket/{user}/{repo}/json").to(json_hoc::<Bitbucket>))

View File

@ -20,4 +20,9 @@ To include the badge in your readme, use the following markdown:
<pre> <pre>
[![Hits-of-Code](https://@repo_info.domain/@repo_info.path)](https://@repo_info.domain/view/@repo_info.path) [![Hits-of-Code](https://@repo_info.domain/@repo_info.path)](https://@repo_info.domain/view/@repo_info.path)
</pre> </pre>
<form method="post" action="/@repo_info.path/delete">
<button type="submit">Rebuild Cache</button>
</form>
}, version_info, repo_count) }, version_info, repo_count)