Compare commits

...

29 Commits

Author SHA1 Message Date
c62f4e3db4 Bump version number
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/tag Build is passing
2019-05-04 15:47:19 +02:00
27c49f6e14 Add dependency badge 2019-05-04 15:46:36 +02:00
6d9b95e7d0 Merge branch 'feature/generator-from' 2019-05-04 15:45:35 +02:00
791cb38a41 Implement generator and use custom result type 2019-05-04 15:45:25 +02:00
eb0ee4b31d Add generator and result page 2019-05-04 15:38:00 +02:00
d5e6bf7839 Add service enum for form data 2019-05-04 15:37:29 +02:00
4556d6a04a Add custom result type 2019-05-04 15:33:21 +02:00
2d4e1930a8 Sign CI config [skip ci] 2019-05-01 22:32:34 +02:00
06613ca9b0 Bump version number
All checks were successful
continuous-integration/drone/tag Build is passing
2019-05-01 22:24:20 +02:00
22923e7121 Only run builds on master and tags 2019-05-01 22:23:46 +02:00
49702c22cd Merge branch 'feature/drone-ci'
All checks were successful
continuous-integration/drone/push Build is passing
2019-05-01 22:13:18 +02:00
2da2771218 Add drone badge and remove docker cloud badge 2019-05-01 22:13:06 +02:00
f1ae1b4d59 Enable autotag
All checks were successful
continuous-integration/drone/push Build is passing
2019-05-01 22:08:23 +02:00
80a0afbf53 Upload docker image
All checks were successful
continuous-integration/drone/push Build is passing
2019-05-01 21:56:59 +02:00
751b8e9a6d Build image in CI
Some checks failed
continuous-integration/drone/push Build is failing
2019-05-01 21:31:48 +02:00
6355dce827 Test release build
All checks were successful
continuous-integration/drone/push Build is passing
2019-05-01 18:43:20 +02:00
bd4b8c64ba Fix user
All checks were successful
continuous-integration/drone/push Build is passing
2019-05-01 18:28:16 +02:00
4a69022659 Dummy commit
Some checks failed
continuous-integration/drone/push Build is failing
2019-05-01 18:23:27 +02:00
6f73bbd422 Add drone config
Some checks reported errors
continuous-integration/drone/push Build encountered an error
2019-05-01 18:21:10 +02:00
7b45d72b97 Make worker threads configurable 2019-05-01 16:37:51 +02:00
852a31315d Start 4 worker threads 2019-05-01 16:21:36 +02:00
95f2c987e3 Add travis badge 2019-05-01 13:44:33 +02:00
2d4ad8c58f Clarify binary dependency on git
[ci skip]
2019-05-01 13:42:43 +02:00
beb57036aa Remove TODO from readme 2019-05-01 13:41:02 +02:00
3e507b9b86 Update dependencies 2019-05-01 13:38:57 +02:00
240ffec767 Fix CI config for releases 2019-04-30 17:17:18 +02:00
1bc91a9e41 Bump version number 2019-04-30 16:46:27 +02:00
8ae71cdb5d Merge branch 'feature/case-insensitive-path' 2019-04-30 16:45:43 +02:00
8fc46ab7cc Use all lowercase path names for storage and caching
`Microsoft/vscode` and `microsoft/vscode` point to the same directory
but the repo would have been cloned twice.
2019-04-30 16:45:29 +02:00
10 changed files with 339 additions and 212 deletions

22
.drone.yml Normal file
View 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
...

View File

@ -42,7 +42,7 @@ release-tag:
stage: release
script:
- 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
only:
- /^v\d+\.\d+\.\d+/

382
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,22 +1,22 @@
[package]
name = "hoc"
version = "0.2.1"
version = "0.3.0"
authors = ["Valentin Brandl <vbrandl@riseup.net>"]
edition = "2018"
build = "build.rs"
[dependencies]
actix-web = "1.0.0-alpha.4"
actix-web = "1.0.0-beta.2"
badge = "0.2.0"
bytes = "0.4.12"
futures = "0.1.25"
futures = "0.1.26"
git2 = "0.8.0"
lazy_static = "1.3.0"
log = "0.4.6"
number_prefix = "0.3.0"
openssl-probe = "0.1.2"
pretty_env_logger = "0.3.0"
reqwest = "0.9.15"
reqwest = "0.9.16"
serde = "1.0.90"
serde_derive = "1.0.90"
serde_json = "1.0.39"

View File

@ -1,14 +1,16 @@
# Hits-of-Code
[![Hits-of-Code](https://hitsofcode.com/github/vbrandl/hoc)](https://hitsofcode.com/view/github/vbrandl/hoc)
[![Docker build](https://img.shields.io/docker/cloud/build/vbrandl/hits-of-code.svg)](https://hub.docker.com/r/vbrandl/hits-of-code)
[![Drone build](https://drone.vbrandl.net/api/badges/vbrandl/hoc/status.svg)](https://drone.vbrandl.net/vbrandl/hoc)
[![Gitlab build](https://gitlab.com/vbrandl/hoc/badges/master/pipeline.svg)](https://gitlab.com/vbrandl/hoc/pipelines)
[![Travis build](https://travis-ci.org/vbrandl/hoc.svg?branch=master)](https://travis-ci.org/vbrandl/hoc)
[![dependency status](https://deps.rs/repo/github/vbrandl/hoc/status.svg)](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
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.
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
@ -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
```
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

View File

@ -2,6 +2,8 @@ use crate::P500;
use actix_web::{HttpResponse, ResponseError};
use std::fmt;
pub(crate) type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
pub(crate) enum Error {
Badge(String),

View File

@ -13,8 +13,8 @@ mod service;
use crate::{
cache::CacheState,
error::Error,
service::{Bitbucket, GitHub, Gitlab, Service},
error::{Error, Result},
service::{Bitbucket, FormService, GitHub, Gitlab, Service},
};
use actix_web::{
error::ErrorBadRequest,
@ -27,6 +27,7 @@ use futures::{unsync::mpsc, Stream};
use git2::Repository;
use number_prefix::{NumberPrefix, Prefixed, Standalone};
use std::{
borrow::Cow,
fs::create_dir_all,
path::{Path, PathBuf},
process::Command,
@ -42,6 +43,13 @@ pub struct VersionInfo<'a> {
pub version: &'a str,
}
#[derive(Deserialize, Serialize)]
struct GeneratorForm<'a> {
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"),
@ -101,16 +109,19 @@ struct Opt {
#[structopt(short = "d", long = "domain", default_value = "hitsofcode.com")]
/// Interface to listen on
domain: String,
#[structopt(short = "w", long = "workers", default_value = "4")]
/// Number of worker threads
workers: usize,
}
fn pull(path: impl AsRef<Path>) -> Result<(), Error> {
fn pull(path: impl AsRef<Path>) -> Result<()> {
let repo = Repository::open_bare(path)?;
let mut origin = repo.find_remote("origin")?;
origin.fetch(&["refs/heads/*:refs/heads/*"], None, None)?;
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 cache_dir = format!("{}/{}.json", cache_dir, repo);
let cache_dir = Path::new(&cache_dir);
@ -161,7 +172,7 @@ fn hoc(repo: &str, repo_dir: &str, cache_dir: &str) -> Result<(u64, String), Err
s.split_whitespace()
.take(2)
.map(str::parse::<u64>)
.filter_map(Result::ok)
.filter_map(std::result::Result::ok)
.sum::<u64>()
})
.sum();
@ -172,7 +183,7 @@ fn hoc(repo: &str, repo_dir: &str, cache_dir: &str) -> Result<(u64, String), Err
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)
}
@ -192,10 +203,10 @@ fn handle_hoc_request<T, F>(
state: web::Data<Arc<State>>,
data: web::Path<(String, String)>,
mapper: F,
) -> Result<HttpResponse, Error>
) -> Result<HttpResponse>
where
T: Service,
F: Fn(HocResult) -> Result<HttpResponse, Error>,
F: Fn(HocResult) -> Result<HttpResponse>,
{
hoc_request::<T>(state, data).and_then(mapper)
}
@ -203,8 +214,8 @@ where
fn hoc_request<T: Service>(
state: web::Data<Arc<State>>,
data: web::Path<(String, String)>,
) -> Result<HocResult, Error> {
let repo = format!("{}/{}", data.0, data.1);
) -> Result<HocResult> {
let repo = format!("{}/{}", data.0.to_lowercase(), data.1.to_lowercase());
let service_path = format!("{}/{}", T::domain(), repo);
let path = format!("{}/{}", state.repos, service_path);
let file = Path::new(&path);
@ -239,7 +250,7 @@ fn hoc_request<T: Service>(
fn calculate_hoc<T: Service>(
state: web::Data<Arc<State>>,
data: web::Path<(String, String)>,
) -> Result<HttpResponse, Error> {
) -> Result<HttpResponse> {
let mapper = |r| match r {
HocResult::NotFound => Ok(p404()),
HocResult::Hoc { hoc_pretty, .. } => {
@ -272,7 +283,7 @@ fn calculate_hoc<T: Service>(
fn overview<T: Service>(
state: web::Data<Arc<State>>,
data: web::Path<(String, String)>,
) -> Result<HttpResponse, Error> {
) -> Result<HttpResponse> {
let mapper = |r| match r {
HocResult::NotFound => Ok(p404()),
HocResult::Hoc {
@ -314,6 +325,26 @@ fn index() -> HttpResponse {
.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 {
HttpResponse::NotFound()
.content_type("text/html")
@ -340,6 +371,7 @@ fn main() -> std::io::Result<()> {
.wrap(middleware::Logger::default())
.service(index)
.service(css)
.service(generate)
.service(web::resource("/github/{user}/{repo}").to(calculate_hoc::<GitHub>))
.service(web::resource("/gitlab/{user}/{repo}").to(calculate_hoc::<Gitlab>))
.service(web::resource("/bitbucket/{user}/{repo}").to(calculate_hoc::<Bitbucket>))
@ -348,6 +380,7 @@ fn main() -> std::io::Result<()> {
.service(web::resource("/view/bitbucket/{user}/{repo}").to(overview::<Bitbucket>))
.default_service(web::resource("").route(web::get().to(p404)))
})
.workers(OPT.workers)
.bind(interface)?
.run()
}

View File

@ -4,6 +4,34 @@ pub(crate) trait Service {
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;
impl Service for GitHub {

View File

@ -0,0 +1,23 @@
@use super::base;
@use crate::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>
[![Hits-of-Code](https://@domain/@service/@path)](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)

View File

@ -45,6 +45,21 @@ would render this badge:
alt="example badge" /></a>
</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>
<p>