hoc/src/main.rs

274 lines
7.7 KiB
Rust
Raw Normal View History

2019-04-16 20:55:25 +02:00
#[macro_use]
2019-04-16 16:57:06 +02:00
extern crate actix_web;
2019-04-21 20:45:36 +02:00
#[macro_use]
extern crate lazy_static;
extern crate reqwest;
2019-04-19 22:51:58 +02:00
extern crate serde_json;
2019-04-19 16:01:47 +02:00
#[macro_use]
extern crate serde_derive;
2019-04-19 22:51:58 +02:00
mod cache;
2019-04-19 16:01:47 +02:00
mod error;
2019-04-16 16:57:06 +02:00
2019-04-20 15:01:11 +02:00
use crate::{cache::CacheState, error::Error};
use actix_web::{
2019-04-19 16:01:47 +02:00
error::ErrorBadRequest,
2019-04-18 15:13:58 +02:00
http::{
self,
header::{CacheControl, CacheDirective, Expires},
},
2019-04-19 16:01:47 +02:00
middleware, web, App, HttpResponse, HttpServer,
};
2019-04-16 16:57:06 +02:00
use badge::{Badge, BadgeOptions};
2019-04-16 21:37:39 +02:00
use bytes::Bytes;
use futures::{unsync::mpsc, Stream};
use git2::Repository;
2019-04-16 16:57:06 +02:00
use std::{
fs::create_dir_all,
2019-04-16 16:57:06 +02:00
path::{Path, PathBuf},
process::Command,
sync::Arc,
time::{Duration, SystemTime},
2019-04-16 16:57:06 +02:00
};
use structopt::StructOpt;
include!(concat!(env!("OUT_DIR"), "/templates.rs"));
const COMMIT: &str = env!("VERGEN_SHA_SHORT");
const VERSION: &str = env!("CARGO_PKG_VERSION");
2019-04-21 20:45:36 +02:00
lazy_static! {
static ref CLIENT: reqwest::Client = reqwest::Client::new();
static ref INDEX: Vec<u8> = {
let mut buf = Vec::new();
templates::index(&mut buf, COMMIT, VERSION).unwrap();
buf
};
static ref P404: Vec<u8> = {
let mut buf = Vec::new();
templates::p404(&mut buf, COMMIT, VERSION).unwrap();
buf
};
static ref P500: Vec<u8> = {
let mut buf = Vec::new();
templates::p500(&mut buf, COMMIT, VERSION).unwrap();
buf
};
2019-04-21 20:45:36 +02:00
}
2019-04-19 22:51:58 +02:00
struct State {
repos: String,
cache: String,
}
2019-04-16 16:57:06 +02:00
2019-04-17 20:48:47 +02:00
const CSS: &str = include_str!("../static/tacit-css.min.css");
2019-04-16 21:37:39 +02:00
2019-04-16 16:57:06 +02:00
#[derive(StructOpt, Debug)]
struct Opt {
#[structopt(
short = "o",
long = "outdir",
parse(from_os_str),
default_value = "./repos"
)]
/// Path to store cloned repositories
outdir: PathBuf,
2019-04-19 22:51:58 +02:00
#[structopt(
short = "c",
long = "cachedir",
parse(from_os_str),
default_value = "./cache"
)]
/// Path to store cache
cachedir: PathBuf,
2019-04-16 16:57:06 +02:00
#[structopt(short = "p", long = "port", default_value = "8080")]
/// Port to listen on
port: u16,
#[structopt(short = "h", long = "host", default_value = "0.0.0.0")]
/// Interface to listen on
host: String,
}
fn pull(path: impl AsRef<Path>) -> Result<(), Error> {
let repo = Repository::open_bare(path)?;
2019-04-16 16:57:06 +02:00
let mut origin = repo.find_remote("origin")?;
origin.fetch(&["refs/heads/*:refs/heads/*"], None, None)?;
Ok(())
2019-04-16 16:57:06 +02:00
}
2019-04-19 22:51:58 +02:00
fn hoc(repo: &str, repo_dir: &str, cache_dir: &str) -> Result<u64, Error> {
let repo_dir = format!("{}/{}", repo_dir, repo);
let cache_dir = format!("{}/{}.json", cache_dir, repo);
let cache_dir = Path::new(&cache_dir);
let head = format!(
"{}",
Repository::open_bare(&repo_dir)?
.head()?
.target()
.ok_or(Error::Internal)?
);
let mut arg = vec![
"log".to_string(),
"--pretty=tformat:".to_string(),
"--numstat".to_string(),
"--ignore-space-change".to_string(),
"--ignore-all-space".to_string(),
"--ignore-submodules".to_string(),
"--no-color".to_string(),
"--find-copies-harder".to_string(),
"-M".to_string(),
"--diff-filter=ACDM".to_string(),
];
let cache = CacheState::read_from_file(&cache_dir, &head)?;
match &cache {
CacheState::Current(res) => return Ok(*res),
CacheState::Old(cache) => {
arg.push(format!("{}..HEAD", cache.head));
}
CacheState::No => {}
};
arg.push("--".to_string());
arg.push(".".to_string());
2019-04-16 16:57:06 +02:00
let output = Command::new("git")
2019-04-19 22:51:58 +02:00
.args(&arg)
.current_dir(&repo_dir)
2019-04-16 16:57:06 +02:00
.output()?
.stdout;
let output = String::from_utf8_lossy(&output);
2019-04-19 22:51:58 +02:00
let count: u64 = output
2019-04-16 16:57:06 +02:00
.lines()
.map(|s| {
s.split_whitespace()
.take(2)
.map(str::parse::<u64>)
.filter_map(Result::ok)
.sum::<u64>()
})
.sum();
2019-04-19 22:51:58 +02:00
let cache = cache.calculate_new_cache(count, head);
cache.write_to_file(cache_dir)?;
Ok(cache.count)
2019-04-16 16:57:06 +02:00
}
2019-04-21 20:45:36 +02:00
fn remote_exists(url: &str) -> Result<bool, Error> {
Ok(CLIENT.head(url).send()?.status() == reqwest::StatusCode::OK)
}
2019-04-16 19:52:12 +02:00
fn calculate_hoc(
service: &str,
2019-04-19 22:51:58 +02:00
state: web::Data<Arc<State>>,
2019-04-16 16:57:06 +02:00
data: web::Path<(String, String)>,
) -> Result<HttpResponse, Error> {
2019-04-16 19:52:12 +02:00
let service_path = format!("{}/{}/{}", service, data.0, data.1);
2019-04-19 22:51:58 +02:00
let path = format!("{}/{}", state.repos, service_path);
2019-04-16 16:57:06 +02:00
let file = Path::new(&path);
if !file.exists() {
2019-04-21 20:45:36 +02:00
let url = format!("https://{}", service_path);
if !remote_exists(&url)? {
return Ok(p404());
}
create_dir_all(file)?;
let repo = Repository::init_bare(file)?;
repo.remote_add_fetch("origin", "refs/heads/*:refs/heads/*")?;
2019-04-21 20:45:36 +02:00
repo.remote_set_url("origin", &url)?;
2019-04-16 16:57:06 +02:00
}
pull(&path)?;
2019-04-19 22:51:58 +02:00
let hoc = hoc(&service_path, &state.repos, &state.cache)?;
2019-04-16 16:57:06 +02:00
let badge_opt = BadgeOptions {
subject: "Hits-of-Code".to_string(),
2019-04-20 15:01:11 +02:00
color: "#007ec6".to_string(),
2019-04-16 16:57:06 +02:00
status: hoc.to_string(),
};
let badge = Badge::new(badge_opt)?;
2019-04-16 21:37:39 +02:00
let (tx, rx_body) = mpsc::unbounded();
let _ = tx.unbounded_send(Bytes::from(badge.to_svg().as_bytes()));
2019-04-18 15:13:58 +02:00
let expiration = SystemTime::now() + Duration::from_secs(30);
2019-04-16 22:18:40 +02:00
Ok(HttpResponse::Ok()
.content_type("image/svg+xml")
.set(Expires(expiration.into()))
2019-04-18 15:13:58 +02:00
.set(CacheControl(vec![
CacheDirective::MaxAge(0u32),
CacheDirective::MustRevalidate,
CacheDirective::NoCache,
CacheDirective::NoStore,
]))
2019-04-19 16:02:04 +02:00
.streaming(rx_body.map_err(|_| ErrorBadRequest("bad request"))))
2019-04-16 16:57:06 +02:00
}
2019-04-16 19:52:12 +02:00
fn github(
2019-04-19 22:51:58 +02:00
state: web::Data<Arc<State>>,
2019-04-16 19:52:12 +02:00
data: web::Path<(String, String)>,
) -> Result<HttpResponse, Error> {
2019-04-20 15:01:11 +02:00
calculate_hoc("github.com", state, data)
2019-04-16 19:52:12 +02:00
}
fn gitlab(
2019-04-19 22:51:58 +02:00
state: web::Data<Arc<State>>,
2019-04-16 19:52:12 +02:00
data: web::Path<(String, String)>,
) -> Result<HttpResponse, Error> {
2019-04-20 15:01:11 +02:00
calculate_hoc("gitlab.com", state, data)
2019-04-16 19:52:12 +02:00
}
fn bitbucket(
2019-04-19 22:51:58 +02:00
state: web::Data<Arc<State>>,
2019-04-16 19:52:12 +02:00
data: web::Path<(String, String)>,
) -> Result<HttpResponse, Error> {
2019-04-20 15:01:11 +02:00
calculate_hoc("bitbucket.org", state, data)
2019-04-16 19:52:12 +02:00
}
fn overview(_: web::Path<(String, String)>) -> HttpResponse {
HttpResponse::TemporaryRedirect()
.header(http::header::LOCATION, "/")
.finish()
}
2019-04-16 20:55:25 +02:00
#[get("/")]
fn index() -> HttpResponse {
HttpResponse::Ok()
.content_type("text/html")
.body(INDEX.as_slice())
2019-04-21 17:57:57 +02:00
}
2019-04-16 21:37:39 +02:00
2019-04-21 17:57:57 +02:00
fn p404() -> HttpResponse {
HttpResponse::NotFound()
2019-04-17 16:16:50 +02:00
.content_type("text/html")
.body(P404.as_slice())
2019-04-16 20:55:25 +02:00
}
2019-04-17 20:48:47 +02:00
#[get("/tacit-css.min.css")]
fn css() -> HttpResponse {
2019-04-21 17:57:57 +02:00
HttpResponse::Ok().content_type("text/css").body(CSS)
2019-04-17 20:48:47 +02:00
}
2019-04-16 16:57:06 +02:00
fn main() -> std::io::Result<()> {
2019-04-21 20:45:36 +02:00
std::env::set_var("RUST_LOG", "actix_web=warn");
2019-04-16 16:57:06 +02:00
pretty_env_logger::init();
openssl_probe::init_ssl_cert_env_vars();
let opt = Opt::from_args();
let interface = format!("{}:{}", opt.host, opt.port);
2019-04-19 22:51:58 +02:00
let state = Arc::new(State {
repos: opt.outdir.display().to_string(),
cache: opt.cachedir.display().to_string(),
});
2019-04-16 16:57:06 +02:00
HttpServer::new(move || {
App::new()
.data(state.clone())
.wrap(middleware::Logger::default())
2019-04-16 20:55:25 +02:00
.service(index)
2019-04-17 20:48:47 +02:00
.service(css)
2019-04-16 16:57:06 +02:00
.service(web::resource("/github/{user}/{repo}").to(github))
2019-04-16 19:52:12 +02:00
.service(web::resource("/gitlab/{user}/{repo}").to(gitlab))
.service(web::resource("/bitbucket/{user}/{repo}").to(bitbucket))
.service(web::resource("/view/github/{user}/{repo}").to(overview))
.service(web::resource("/view/gitlab/{user}/{repo}").to(overview))
.service(web::resource("/view/github/{user}/{repo}").to(overview))
2019-04-21 17:57:57 +02:00
.default_service(web::resource("").route(web::get().to(p404)))
2019-04-16 16:57:06 +02:00
})
.bind(interface)?
.run()
}