Compare commits
37 Commits
Author | SHA1 | Date | |
---|---|---|---|
0fcafc7e4b | |||
5fd0eaf289 | |||
2236cf8b53 | |||
60cba9951f | |||
d6835b96de | |||
6d980d92be | |||
48e65fef36 | |||
514c30e13c | |||
d082531ca4 | |||
0a58a75cd1 | |||
a7441f79cb | |||
c62f4e3db4 | |||
27c49f6e14 | |||
6d9b95e7d0 | |||
791cb38a41 | |||
eb0ee4b31d | |||
d5e6bf7839 | |||
4556d6a04a | |||
2d4e1930a8 | |||
06613ca9b0 | |||
22923e7121 | |||
49702c22cd | |||
2da2771218 | |||
f1ae1b4d59 | |||
80a0afbf53 | |||
751b8e9a6d | |||
6355dce827 | |||
bd4b8c64ba | |||
4a69022659 | |||
6f73bbd422 | |||
7b45d72b97 | |||
852a31315d | |||
95f2c987e3 | |||
2d4ad8c58f | |||
beb57036aa | |||
3e507b9b86 | |||
240ffec767 |
22
.drone.yml
Normal file
22
.drone.yml
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
---
|
||||||
|
kind: pipeline
|
||||||
|
name: build
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: docker
|
||||||
|
image: plugins/docker
|
||||||
|
settings:
|
||||||
|
repo: vbrandl/hits-of-code
|
||||||
|
auto_tag: true
|
||||||
|
username:
|
||||||
|
from_secret: docker_username
|
||||||
|
password:
|
||||||
|
from_secret: docker_password
|
||||||
|
ref:
|
||||||
|
- refs/heads/master
|
||||||
|
- refs/tags/v*
|
||||||
|
---
|
||||||
|
kind: signature
|
||||||
|
hmac: 36c14cd35c5abe274025760c9ca34f198d392be0c31435ad58cb9ecaa0abef2a
|
||||||
|
|
||||||
|
...
|
1
.gitignore
vendored
1
.gitignore
vendored
@ -2,3 +2,4 @@
|
|||||||
**/*.rs.bk
|
**/*.rs.bk
|
||||||
repos
|
repos
|
||||||
cache
|
cache
|
||||||
|
hoc.log
|
||||||
|
@ -42,7 +42,7 @@ release-tag:
|
|||||||
stage: release
|
stage: release
|
||||||
script:
|
script:
|
||||||
- docker pull $CONTAINER_TEST_IMAGE
|
- docker pull $CONTAINER_TEST_IMAGE
|
||||||
- docker tag $CONTAINER_TEST_IMAGE $CONTAINER_RELEASE_IMAGE
|
- docker tag $CONTAINER_TEST_IMAGE $CONTAINER_TAG_IMAGE
|
||||||
- docker push $CONTAINER_TAG_IMAGE
|
- docker push $CONTAINER_TAG_IMAGE
|
||||||
only:
|
only:
|
||||||
- /^v\d+\.\d+\.\d+/
|
- /^v\d+\.\d+\.\d+/
|
||||||
|
547
Cargo.lock
generated
547
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
11
Cargo.toml
11
Cargo.toml
@ -1,22 +1,23 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "hoc"
|
name = "hoc"
|
||||||
version = "0.2.2"
|
version = "0.5.0"
|
||||||
authors = ["Valentin Brandl <vbrandl@riseup.net>"]
|
authors = ["Valentin Brandl <vbrandl@riseup.net>"]
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
build = "build.rs"
|
build = "build.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-web = "1.0.0-alpha.4"
|
actix-web = "1.0.0-beta.2"
|
||||||
badge = "0.2.0"
|
badge = "0.2.0"
|
||||||
bytes = "0.4.12"
|
bytes = "0.4.12"
|
||||||
futures = "0.1.25"
|
futures = "0.1.26"
|
||||||
git2 = "0.8.0"
|
git2 = "0.8.0"
|
||||||
lazy_static = "1.3.0"
|
lazy_static = "1.3.0"
|
||||||
log = "0.4.6"
|
log = "0.4.6"
|
||||||
|
log4rs = "0.8.3"
|
||||||
number_prefix = "0.3.0"
|
number_prefix = "0.3.0"
|
||||||
openssl-probe = "0.1.2"
|
openssl-probe = "0.1.2"
|
||||||
pretty_env_logger = "0.3.0"
|
# pretty_env_logger = "0.3.0"
|
||||||
reqwest = "0.9.15"
|
reqwest = "0.9.16"
|
||||||
serde = "1.0.90"
|
serde = "1.0.90"
|
||||||
serde_derive = "1.0.90"
|
serde_derive = "1.0.90"
|
||||||
serde_json = "1.0.39"
|
serde_json = "1.0.39"
|
||||||
|
12
README.md
12
README.md
@ -1,14 +1,16 @@
|
|||||||
# Hits-of-Code
|
# Hits-of-Code
|
||||||
|
|
||||||
[](https://hitsofcode.com/view/github/vbrandl/hoc)
|
[](https://hitsofcode.com/view/github/vbrandl/hoc)
|
||||||
[](https://hub.docker.com/r/vbrandl/hits-of-code)
|
[](https://drone.vbrandl.net/vbrandl/hoc)
|
||||||
[](https://gitlab.com/vbrandl/hoc/pipelines)
|
[](https://gitlab.com/vbrandl/hoc/pipelines)
|
||||||
|
[](https://travis-ci.org/vbrandl/hoc)
|
||||||
|
[](https://deps.rs/repo/github/vbrandl/hoc)
|
||||||
|
|
||||||
Small webservice, that returns a badge of the Hits-of-Code of a git repository, as described by [Yegor
|
Small webservice, that returns a badge of the Hits-of-Code of a git repository, as described by [Yegor
|
||||||
Bugayenko](https://www.yegor256.com/2014/11/14/hits-of-code.html). It is implemented in
|
Bugayenko](https://www.yegor256.com/2014/11/14/hits-of-code.html). It is implemented in
|
||||||
[Rust](https://www.rust-lang.org/), using the [actix-web](https://actix.rs/) web framework.
|
[Rust](https://www.rust-lang.org/), using the [actix-web](https://actix.rs/) web framework.
|
||||||
|
|
||||||
A live version of this API can be found on [hitsofcode.com](https://hitsofcode.com/).
|
A live version of this webservice can be found on [hitsofcode.com](https://hitsofcode.com/).
|
||||||
|
|
||||||
## API
|
## API
|
||||||
|
|
||||||
@ -47,12 +49,8 @@ from [Docker Hub](https://hub.docker.com/r/vbrandl/hits-of-code)
|
|||||||
$ docker run -it --rm vbrandl/hits-of-code --help
|
$ docker run -it --rm vbrandl/hits-of-code --help
|
||||||
```
|
```
|
||||||
|
|
||||||
|
When running the binary directly, you need a git binary in your `PATH`.
|
||||||
|
|
||||||
## TODO
|
|
||||||
|
|
||||||
* [x] Customization of badges (e.g. colors)
|
|
||||||
* [x] Support other platforms beside GitHub (GitLab and Bitbucket)
|
|
||||||
* [ ] Allow exclusion of certain files/globs from the HoC count
|
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
71
src/config.rs
Normal file
71
src/config.rs
Normal file
@ -0,0 +1,71 @@
|
|||||||
|
use crate::{error::Result, statics::OPT};
|
||||||
|
use log::LevelFilter;
|
||||||
|
use log4rs::{
|
||||||
|
append::{console::ConsoleAppender, file::FileAppender},
|
||||||
|
config::{Appender, Config, Root},
|
||||||
|
encode::pattern::PatternEncoder,
|
||||||
|
};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use structopt::StructOpt;
|
||||||
|
|
||||||
|
#[derive(StructOpt, Debug)]
|
||||||
|
pub(crate) struct Opt {
|
||||||
|
#[structopt(
|
||||||
|
short = "o",
|
||||||
|
long = "outdir",
|
||||||
|
parse(from_os_str),
|
||||||
|
default_value = "./repos"
|
||||||
|
)]
|
||||||
|
/// Path to store cloned repositories
|
||||||
|
pub(crate) outdir: PathBuf,
|
||||||
|
#[structopt(
|
||||||
|
short = "c",
|
||||||
|
long = "cachedir",
|
||||||
|
parse(from_os_str),
|
||||||
|
default_value = "./cache"
|
||||||
|
)]
|
||||||
|
/// Path to store cache
|
||||||
|
pub(crate) cachedir: PathBuf,
|
||||||
|
#[structopt(short = "p", long = "port", default_value = "8080")]
|
||||||
|
/// Port to listen on
|
||||||
|
pub(crate) port: u16,
|
||||||
|
#[structopt(short = "h", long = "host", default_value = "0.0.0.0")]
|
||||||
|
/// Interface to listen on
|
||||||
|
pub(crate) host: String,
|
||||||
|
#[structopt(short = "d", long = "domain", default_value = "hitsofcode.com")]
|
||||||
|
/// Interface to listen on
|
||||||
|
pub(crate) domain: String,
|
||||||
|
#[structopt(short = "w", long = "workers", default_value = "4")]
|
||||||
|
/// Number of worker threads
|
||||||
|
pub(crate) workers: usize,
|
||||||
|
#[structopt(
|
||||||
|
short = "l",
|
||||||
|
long = "logfile",
|
||||||
|
parse(from_os_str),
|
||||||
|
default_value = "./hoc.log"
|
||||||
|
)]
|
||||||
|
/// The logfile
|
||||||
|
pub(crate) logfile: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn init() -> Result<()> {
|
||||||
|
std::env::set_var("RUST_LOG", "actix_web=info,hoc=info");
|
||||||
|
// pretty_env_logger::init();
|
||||||
|
openssl_probe::init_ssl_cert_env_vars();
|
||||||
|
let stdout = ConsoleAppender::builder().build();
|
||||||
|
let file = FileAppender::builder()
|
||||||
|
.encoder(Box::new(PatternEncoder::new("{d} - {m}{n}")))
|
||||||
|
.build(&OPT.logfile)
|
||||||
|
.unwrap();
|
||||||
|
let config = Config::builder()
|
||||||
|
.appender(Appender::builder().build("stdout", Box::new(stdout)))
|
||||||
|
.appender(Appender::builder().build("file", Box::new(file)))
|
||||||
|
.build(
|
||||||
|
Root::builder()
|
||||||
|
.appender("stdout")
|
||||||
|
.appender("file")
|
||||||
|
.build(LevelFilter::Info),
|
||||||
|
)?;
|
||||||
|
log4rs::init_config(config)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
18
src/error.rs
18
src/error.rs
@ -2,6 +2,8 @@ use crate::P500;
|
|||||||
use actix_web::{HttpResponse, ResponseError};
|
use actix_web::{HttpResponse, ResponseError};
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
|
|
||||||
|
pub(crate) type Result<T> = std::result::Result<T, Error>;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub(crate) enum Error {
|
pub(crate) enum Error {
|
||||||
Badge(String),
|
Badge(String),
|
||||||
@ -9,6 +11,8 @@ pub(crate) enum Error {
|
|||||||
Git(git2::Error),
|
Git(git2::Error),
|
||||||
Internal,
|
Internal,
|
||||||
Io(std::io::Error),
|
Io(std::io::Error),
|
||||||
|
Log(log::SetLoggerError),
|
||||||
|
LogBuilder(log4rs::config::Errors),
|
||||||
Serial(serde_json::Error),
|
Serial(serde_json::Error),
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -20,6 +24,8 @@ impl fmt::Display for Error {
|
|||||||
Error::Git(e) => write!(fmt, "Git({})", e),
|
Error::Git(e) => write!(fmt, "Git({})", e),
|
||||||
Error::Internal => write!(fmt, "Internal Error"),
|
Error::Internal => write!(fmt, "Internal Error"),
|
||||||
Error::Io(e) => write!(fmt, "Io({})", e),
|
Error::Io(e) => write!(fmt, "Io({})", e),
|
||||||
|
Error::Log(e) => write!(fmt, "Log({})", e),
|
||||||
|
Error::LogBuilder(e) => write!(fmt, "LogBuilder({})", e),
|
||||||
Error::Serial(e) => write!(fmt, "Serial({})", e),
|
Error::Serial(e) => write!(fmt, "Serial({})", e),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -53,6 +59,12 @@ impl From<git2::Error> for Error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl From<log::SetLoggerError> for Error {
|
||||||
|
fn from(err: log::SetLoggerError) -> Self {
|
||||||
|
Error::Log(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl From<std::io::Error> for Error {
|
impl From<std::io::Error> for Error {
|
||||||
fn from(err: std::io::Error) -> Self {
|
fn from(err: std::io::Error) -> Self {
|
||||||
Error::Io(err)
|
Error::Io(err)
|
||||||
@ -70,3 +82,9 @@ impl From<reqwest::Error> for Error {
|
|||||||
Error::Client(err)
|
Error::Client(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl From<log4rs::config::Errors> for Error {
|
||||||
|
fn from(err: log4rs::config::Errors) -> Self {
|
||||||
|
Error::LogBuilder(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
131
src/main.rs
131
src/main.rs
@ -8,13 +8,16 @@ extern crate log;
|
|||||||
extern crate serde_derive;
|
extern crate serde_derive;
|
||||||
|
|
||||||
mod cache;
|
mod cache;
|
||||||
|
mod config;
|
||||||
mod error;
|
mod error;
|
||||||
mod service;
|
mod service;
|
||||||
|
mod statics;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
cache::CacheState,
|
cache::CacheState,
|
||||||
error::Error,
|
error::{Error, Result},
|
||||||
service::{Bitbucket, GitHub, Gitlab, Service},
|
service::{Bitbucket, FormService, GitHub, Gitlab, Service},
|
||||||
|
statics::{CLIENT, CSS, FAVICON, INDEX, OPT, P404, P500, VERSION_INFO},
|
||||||
};
|
};
|
||||||
use actix_web::{
|
use actix_web::{
|
||||||
error::ErrorBadRequest,
|
error::ErrorBadRequest,
|
||||||
@ -27,44 +30,21 @@ use futures::{unsync::mpsc, Stream};
|
|||||||
use git2::Repository;
|
use git2::Repository;
|
||||||
use number_prefix::{NumberPrefix, Prefixed, Standalone};
|
use number_prefix::{NumberPrefix, Prefixed, Standalone};
|
||||||
use std::{
|
use std::{
|
||||||
|
borrow::Cow,
|
||||||
fs::create_dir_all,
|
fs::create_dir_all,
|
||||||
path::{Path, PathBuf},
|
path::Path,
|
||||||
process::Command,
|
process::Command,
|
||||||
sync::Arc,
|
sync::Arc,
|
||||||
time::{Duration, SystemTime},
|
time::{Duration, SystemTime},
|
||||||
};
|
};
|
||||||
use structopt::StructOpt;
|
|
||||||
|
|
||||||
include!(concat!(env!("OUT_DIR"), "/templates.rs"));
|
include!(concat!(env!("OUT_DIR"), "/templates.rs"));
|
||||||
|
|
||||||
pub struct VersionInfo<'a> {
|
#[derive(Deserialize, Serialize)]
|
||||||
pub commit: &'a str,
|
struct GeneratorForm<'a> {
|
||||||
pub version: &'a str,
|
service: FormService,
|
||||||
}
|
user: Cow<'a, str>,
|
||||||
|
repo: Cow<'a, str>,
|
||||||
const VERSION_INFO: VersionInfo = VersionInfo {
|
|
||||||
commit: env!("VERGEN_SHA_SHORT"),
|
|
||||||
version: env!("CARGO_PKG_VERSION"),
|
|
||||||
};
|
|
||||||
|
|
||||||
lazy_static! {
|
|
||||||
static ref CLIENT: reqwest::Client = reqwest::Client::new();
|
|
||||||
static ref OPT: Opt = Opt::from_args();
|
|
||||||
static ref INDEX: Vec<u8> = {
|
|
||||||
let mut buf = Vec::new();
|
|
||||||
templates::index(&mut buf, VERSION_INFO, &OPT.domain).unwrap();
|
|
||||||
buf
|
|
||||||
};
|
|
||||||
static ref P404: Vec<u8> = {
|
|
||||||
let mut buf = Vec::new();
|
|
||||||
templates::p404(&mut buf, VERSION_INFO).unwrap();
|
|
||||||
buf
|
|
||||||
};
|
|
||||||
static ref P500: Vec<u8> = {
|
|
||||||
let mut buf = Vec::new();
|
|
||||||
templates::p500(&mut buf, VERSION_INFO).unwrap();
|
|
||||||
buf
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
struct State {
|
struct State {
|
||||||
@ -72,45 +52,14 @@ struct State {
|
|||||||
cache: String,
|
cache: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
const CSS: &str = include_str!("../static/tacit-css.min.css");
|
fn pull(path: impl AsRef<Path>) -> Result<()> {
|
||||||
|
|
||||||
#[derive(StructOpt, Debug)]
|
|
||||||
struct Opt {
|
|
||||||
#[structopt(
|
|
||||||
short = "o",
|
|
||||||
long = "outdir",
|
|
||||||
parse(from_os_str),
|
|
||||||
default_value = "./repos"
|
|
||||||
)]
|
|
||||||
/// Path to store cloned repositories
|
|
||||||
outdir: PathBuf,
|
|
||||||
#[structopt(
|
|
||||||
short = "c",
|
|
||||||
long = "cachedir",
|
|
||||||
parse(from_os_str),
|
|
||||||
default_value = "./cache"
|
|
||||||
)]
|
|
||||||
/// Path to store cache
|
|
||||||
cachedir: PathBuf,
|
|
||||||
#[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,
|
|
||||||
#[structopt(short = "d", long = "domain", default_value = "hitsofcode.com")]
|
|
||||||
/// Interface to listen on
|
|
||||||
domain: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn pull(path: impl AsRef<Path>) -> Result<(), Error> {
|
|
||||||
let repo = Repository::open_bare(path)?;
|
let repo = Repository::open_bare(path)?;
|
||||||
let mut origin = repo.find_remote("origin")?;
|
let mut origin = repo.find_remote("origin")?;
|
||||||
origin.fetch(&["refs/heads/*:refs/heads/*"], None, None)?;
|
origin.fetch(&["refs/heads/*:refs/heads/*"], None, None)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn hoc(repo: &str, repo_dir: &str, cache_dir: &str) -> Result<(u64, String), Error> {
|
fn hoc(repo: &str, repo_dir: &str, cache_dir: &str) -> Result<(u64, String)> {
|
||||||
let repo_dir = format!("{}/{}", repo_dir, repo);
|
let repo_dir = format!("{}/{}", repo_dir, repo);
|
||||||
let cache_dir = format!("{}/{}.json", cache_dir, repo);
|
let cache_dir = format!("{}/{}.json", cache_dir, repo);
|
||||||
let cache_dir = Path::new(&cache_dir);
|
let cache_dir = Path::new(&cache_dir);
|
||||||
@ -161,7 +110,7 @@ fn hoc(repo: &str, repo_dir: &str, cache_dir: &str) -> Result<(u64, String), Err
|
|||||||
s.split_whitespace()
|
s.split_whitespace()
|
||||||
.take(2)
|
.take(2)
|
||||||
.map(str::parse::<u64>)
|
.map(str::parse::<u64>)
|
||||||
.filter_map(Result::ok)
|
.filter_map(std::result::Result::ok)
|
||||||
.sum::<u64>()
|
.sum::<u64>()
|
||||||
})
|
})
|
||||||
.sum();
|
.sum();
|
||||||
@ -172,7 +121,7 @@ fn hoc(repo: &str, repo_dir: &str, cache_dir: &str) -> Result<(u64, String), Err
|
|||||||
Ok((cache.count, head))
|
Ok((cache.count, head))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn remote_exists(url: &str) -> Result<bool, Error> {
|
fn remote_exists(url: &str) -> Result<bool> {
|
||||||
Ok(CLIENT.head(url).send()?.status() == reqwest::StatusCode::OK)
|
Ok(CLIENT.head(url).send()?.status() == reqwest::StatusCode::OK)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -192,10 +141,10 @@ 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)>,
|
||||||
mapper: F,
|
mapper: F,
|
||||||
) -> Result<HttpResponse, Error>
|
) -> Result<HttpResponse>
|
||||||
where
|
where
|
||||||
T: Service,
|
T: Service,
|
||||||
F: Fn(HocResult) -> Result<HttpResponse, Error>,
|
F: Fn(HocResult) -> Result<HttpResponse>,
|
||||||
{
|
{
|
||||||
hoc_request::<T>(state, data).and_then(mapper)
|
hoc_request::<T>(state, data).and_then(mapper)
|
||||||
}
|
}
|
||||||
@ -203,7 +152,7 @@ where
|
|||||||
fn hoc_request<T: Service>(
|
fn hoc_request<T: Service>(
|
||||||
state: web::Data<Arc<State>>,
|
state: web::Data<Arc<State>>,
|
||||||
data: web::Path<(String, String)>,
|
data: web::Path<(String, String)>,
|
||||||
) -> Result<HocResult, Error> {
|
) -> Result<HocResult> {
|
||||||
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::domain(), repo);
|
||||||
let path = format!("{}/{}", state.repos, service_path);
|
let path = format!("{}/{}", state.repos, service_path);
|
||||||
@ -239,7 +188,7 @@ fn hoc_request<T: Service>(
|
|||||||
fn calculate_hoc<T: Service>(
|
fn calculate_hoc<T: Service>(
|
||||||
state: web::Data<Arc<State>>,
|
state: web::Data<Arc<State>>,
|
||||||
data: web::Path<(String, String)>,
|
data: web::Path<(String, String)>,
|
||||||
) -> Result<HttpResponse, Error> {
|
) -> Result<HttpResponse> {
|
||||||
let mapper = |r| match r {
|
let mapper = |r| match r {
|
||||||
HocResult::NotFound => Ok(p404()),
|
HocResult::NotFound => Ok(p404()),
|
||||||
HocResult::Hoc { hoc_pretty, .. } => {
|
HocResult::Hoc { hoc_pretty, .. } => {
|
||||||
@ -272,7 +221,7 @@ fn calculate_hoc<T: Service>(
|
|||||||
fn overview<T: Service>(
|
fn overview<T: Service>(
|
||||||
state: web::Data<Arc<State>>,
|
state: web::Data<Arc<State>>,
|
||||||
data: web::Path<(String, String)>,
|
data: web::Path<(String, String)>,
|
||||||
) -> Result<HttpResponse, Error> {
|
) -> Result<HttpResponse> {
|
||||||
let mapper = |r| match r {
|
let mapper = |r| match r {
|
||||||
HocResult::NotFound => Ok(p404()),
|
HocResult::NotFound => Ok(p404()),
|
||||||
HocResult::Hoc {
|
HocResult::Hoc {
|
||||||
@ -314,6 +263,26 @@ fn index() -> HttpResponse {
|
|||||||
.body(INDEX.as_slice())
|
.body(INDEX.as_slice())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[post("/generate")]
|
||||||
|
fn generate(params: web::Form<GeneratorForm>) -> Result<HttpResponse> {
|
||||||
|
let repo = format!("{}/{}", params.user, params.repo);
|
||||||
|
let mut buf = Vec::new();
|
||||||
|
templates::generate(
|
||||||
|
&mut buf,
|
||||||
|
VERSION_INFO,
|
||||||
|
&OPT.domain,
|
||||||
|
params.service.url(),
|
||||||
|
params.service.service(),
|
||||||
|
&repo,
|
||||||
|
)?;
|
||||||
|
let (tx, rx_body) = mpsc::unbounded();
|
||||||
|
let _ = tx.unbounded_send(Bytes::from(buf));
|
||||||
|
|
||||||
|
Ok(HttpResponse::Ok()
|
||||||
|
.content_type("text/html")
|
||||||
|
.streaming(rx_body.map_err(|_| ErrorBadRequest("bad request"))))
|
||||||
|
}
|
||||||
|
|
||||||
fn p404() -> HttpResponse {
|
fn p404() -> HttpResponse {
|
||||||
HttpResponse::NotFound()
|
HttpResponse::NotFound()
|
||||||
.content_type("text/html")
|
.content_type("text/html")
|
||||||
@ -325,21 +294,26 @@ fn css() -> HttpResponse {
|
|||||||
HttpResponse::Ok().content_type("text/css").body(CSS)
|
HttpResponse::Ok().content_type("text/css").body(CSS)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() -> std::io::Result<()> {
|
#[get("/favicon.ico")]
|
||||||
std::env::set_var("RUST_LOG", "actix_web=info,hoc=info");
|
fn favicon32() -> HttpResponse {
|
||||||
pretty_env_logger::init();
|
HttpResponse::Ok().content_type("image/png").body(FAVICON)
|
||||||
openssl_probe::init_ssl_cert_env_vars();
|
}
|
||||||
|
|
||||||
|
fn main() -> Result<()> {
|
||||||
|
config::init()?;
|
||||||
let interface = format!("{}:{}", OPT.host, OPT.port);
|
let interface = format!("{}:{}", OPT.host, OPT.port);
|
||||||
let state = Arc::new(State {
|
let state = Arc::new(State {
|
||||||
repos: OPT.outdir.display().to_string(),
|
repos: OPT.outdir.display().to_string(),
|
||||||
cache: OPT.cachedir.display().to_string(),
|
cache: OPT.cachedir.display().to_string(),
|
||||||
});
|
});
|
||||||
HttpServer::new(move || {
|
Ok(HttpServer::new(move || {
|
||||||
App::new()
|
App::new()
|
||||||
.data(state.clone())
|
.data(state.clone())
|
||||||
.wrap(middleware::Logger::default())
|
.wrap(middleware::Logger::default())
|
||||||
.service(index)
|
.service(index)
|
||||||
.service(css)
|
.service(css)
|
||||||
|
.service(favicon32)
|
||||||
|
.service(generate)
|
||||||
.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>))
|
||||||
@ -348,6 +322,7 @@ fn main() -> std::io::Result<()> {
|
|||||||
.service(web::resource("/view/bitbucket/{user}/{repo}").to(overview::<Bitbucket>))
|
.service(web::resource("/view/bitbucket/{user}/{repo}").to(overview::<Bitbucket>))
|
||||||
.default_service(web::resource("").route(web::get().to(p404)))
|
.default_service(web::resource("").route(web::get().to(p404)))
|
||||||
})
|
})
|
||||||
|
.workers(OPT.workers)
|
||||||
.bind(interface)?
|
.bind(interface)?
|
||||||
.run()
|
.run()?)
|
||||||
}
|
}
|
||||||
|
@ -4,6 +4,34 @@ pub(crate) trait Service {
|
|||||||
fn commit_url(repo: &str, commit_ref: &str) -> String;
|
fn commit_url(repo: &str, commit_ref: &str) -> String;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, Serialize)]
|
||||||
|
pub(crate) enum FormService {
|
||||||
|
#[serde(rename = "github")]
|
||||||
|
GitHub,
|
||||||
|
#[serde(rename = "gitlab")]
|
||||||
|
Gitlab,
|
||||||
|
#[serde(rename = "bitbucket")]
|
||||||
|
Bitbucket,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FormService {
|
||||||
|
pub(crate) fn url(&self) -> &str {
|
||||||
|
match self {
|
||||||
|
FormService::GitHub => "github.com",
|
||||||
|
FormService::Gitlab => "gitlab.com",
|
||||||
|
FormService::Bitbucket => "bitbucket.org",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn service(&self) -> &str {
|
||||||
|
match self {
|
||||||
|
FormService::GitHub => "github",
|
||||||
|
FormService::Gitlab => "gitlab",
|
||||||
|
FormService::Bitbucket => "bitbucket",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) struct GitHub;
|
pub(crate) struct GitHub;
|
||||||
|
|
||||||
impl Service for GitHub {
|
impl Service for GitHub {
|
||||||
|
34
src/statics.rs
Normal file
34
src/statics.rs
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
use crate::{config::Opt, templates};
|
||||||
|
use structopt::StructOpt;
|
||||||
|
|
||||||
|
pub struct VersionInfo<'a> {
|
||||||
|
pub commit: &'a str,
|
||||||
|
pub version: &'a str,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) const VERSION_INFO: VersionInfo = VersionInfo {
|
||||||
|
commit: env!("VERGEN_SHA_SHORT"),
|
||||||
|
version: env!("CARGO_PKG_VERSION"),
|
||||||
|
};
|
||||||
|
pub(crate) const CSS: &str = include_str!("../static/tacit-css.min.css");
|
||||||
|
pub(crate) const FAVICON: &[u8] = include_bytes!("../static/favicon32.png");
|
||||||
|
|
||||||
|
lazy_static! {
|
||||||
|
pub(crate) static ref CLIENT: reqwest::Client = reqwest::Client::new();
|
||||||
|
pub(crate) static ref OPT: Opt = Opt::from_args();
|
||||||
|
pub(crate) static ref INDEX: Vec<u8> = {
|
||||||
|
let mut buf = Vec::new();
|
||||||
|
templates::index(&mut buf, VERSION_INFO, &OPT.domain).unwrap();
|
||||||
|
buf
|
||||||
|
};
|
||||||
|
pub(crate) static ref P404: Vec<u8> = {
|
||||||
|
let mut buf = Vec::new();
|
||||||
|
templates::p404(&mut buf, VERSION_INFO).unwrap();
|
||||||
|
buf
|
||||||
|
};
|
||||||
|
pub(crate) static ref P500: Vec<u8> = {
|
||||||
|
let mut buf = Vec::new();
|
||||||
|
templates::p500(&mut buf, VERSION_INFO).unwrap();
|
||||||
|
buf
|
||||||
|
};
|
||||||
|
}
|
BIN
static/favicon32.png
Normal file
BIN
static/favicon32.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 983 B |
@ -1,4 +1,4 @@
|
|||||||
@use crate::VersionInfo;
|
@use crate::statics::VersionInfo;
|
||||||
|
|
||||||
@(title: &str, header: &str, content: Content, version_info: VersionInfo)
|
@(title: &str, header: &str, content: Content, version_info: VersionInfo)
|
||||||
|
|
||||||
|
23
templates/generate.rs.html
Normal file
23
templates/generate.rs.html
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
@use super::base;
|
||||||
|
@use crate::statics::VersionInfo;
|
||||||
|
|
||||||
|
@(version_info: VersionInfo, domain: &str, url: &str, service: &str, path: &str)
|
||||||
|
|
||||||
|
@:base("Hits-of-Code Badges", "Badge Generator", {
|
||||||
|
|
||||||
|
<p>
|
||||||
|
Here is the markdown for the badge for <a href="https://@url/@path">@url/@path</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<pre>
|
||||||
|
[](https://@domain/view/@service/@path)
|
||||||
|
</pre>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
It will be rendered like this
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<pre>
|
||||||
|
<a href="https://@domain/view/@service/@path"><img src="https://@domain/@service/@path" alt="example badge" /></a>
|
||||||
|
</pre>
|
||||||
|
}, version_info)
|
@ -1,5 +1,5 @@
|
|||||||
@use super::base;
|
@use super::base;
|
||||||
@use crate::VersionInfo;
|
@use crate::statics::VersionInfo;
|
||||||
|
|
||||||
@(version_info: VersionInfo, domain: &str)
|
@(version_info: VersionInfo, domain: &str)
|
||||||
|
|
||||||
@ -45,6 +45,21 @@ would render this badge:
|
|||||||
alt="example badge" /></a>
|
alt="example badge" /></a>
|
||||||
</pre>
|
</pre>
|
||||||
|
|
||||||
|
<h2>Badge Generator</h2>
|
||||||
|
|
||||||
|
<form method="post" action="/generate">
|
||||||
|
<select name="service" id="service">
|
||||||
|
<option value="github">GitHub</option>
|
||||||
|
<option value="gitlab">Gitlab</option>
|
||||||
|
<option value="bitbucket">Bitbucket</option>
|
||||||
|
</select>
|
||||||
|
<label>/</label>
|
||||||
|
<input name="user" id="user" type="text" placeholder="user" />
|
||||||
|
<label>/</label>
|
||||||
|
<input name="repo" id="repo" type="text" placeholder="repository" />
|
||||||
|
<button type="submit">Generate</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
<h2>Source Code</h2>
|
<h2>Source Code</h2>
|
||||||
|
|
||||||
<p>
|
<p>
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
@use super::base;
|
@use super::base;
|
||||||
@use crate::VersionInfo;
|
@use crate::statics::VersionInfo;
|
||||||
|
|
||||||
@(version_info: VersionInfo, domain: &str, path: &str, url: &str, hoc: u64, hoc_pretty: &str, head: &str, commit_url: &str)
|
@(version_info: VersionInfo, domain: &str, path: &str, url: &str, hoc: u64, hoc_pretty: &str, head: &str, commit_url: &str)
|
||||||
|
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
@use super::base;
|
@use super::base;
|
||||||
@use crate::VersionInfo;
|
@use crate::statics::VersionInfo;
|
||||||
|
|
||||||
@(version_info: VersionInfo)
|
@(version_info: VersionInfo)
|
||||||
|
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
@use super::base;
|
@use super::base;
|
||||||
@use crate::VersionInfo;
|
@use crate::statics::VersionInfo;
|
||||||
|
|
||||||
@(version_info: VersionInfo)
|
@(version_info: VersionInfo)
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user