Compare commits

...

73 Commits

Author SHA1 Message Date
b8e454762e Bump version number
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/tag Build is passing
2019-07-07 14:53:51 +02:00
268734efdd Merge branch 'feature/commit-count'
Closes #33
2019-07-07 14:53:10 +02:00
c71925f61e Add migration subcommand 2019-07-07 14:52:42 +02:00
c5bbd14a05 Update documentation for the JSON endpoint 2019-07-07 13:36:14 +02:00
a239a3f80b Calculate number of commits
The number of commits is shown in the overview page and returned in the
JSON response.

Closes #33
2019-07-07 13:30:17 +02:00
00b4e60341 Add parse error 2019-07-07 13:29:26 +02:00
ed1cafafd0 Show commit count in overview page 2019-07-07 13:29:03 +02:00
bdb10fd54a Add commit count to the cache struct 2019-07-07 13:28:43 +02:00
1f01c3b964 Bump version number
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/tag Build is passing
2019-07-05 12:50:55 +02:00
3f94789b8b Merge pull request #32 from vbrandl/dependabot/cargo/actix-web-1.0.3
Bump actix-web from 1.0.2 to 1.0.3
2019-07-05 12:49:40 +02:00
e4f8604861 Bump actix-web from 1.0.2 to 1.0.3
All checks were successful
continuous-integration/drone/push Build is passing
Bumps [actix-web](https://github.com/actix/actix-web) from 1.0.2 to 1.0.3.
- [Release notes](https://github.com/actix/actix-web/releases)
- [Changelog](https://github.com/actix/actix-web/blob/master/CHANGES.md)
- [Commits](https://github.com/actix/actix-web/compare/web-v1.0.2...web-v1.0.3)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-07-03 04:24:43 +00:00
25a179dad6 Bump version number
All checks were successful
continuous-integration/drone/tag Build is passing
continuous-integration/drone/push Build is passing
2019-07-02 17:13:51 +02:00
6ee44f7ba3 Revert "Update dependencies"
This reverts commit 7e13f93ee3. This
commit broke following builds. It was impossible to clone new
repositories.

Reverting the commit closes #31.
2019-07-02 17:11:58 +02:00
e9ebbee957 Bump version number
All checks were successful
continuous-integration/drone/tag Build is passing
continuous-integration/drone/push Build is passing
2019-07-01 18:28:14 +02:00
5211481226 Merge pull request #30 from vbrandl/dependabot/cargo/serde_json-1.0.40
Bump serde_json from 1.0.39 to 1.0.40
2019-07-01 18:24:59 +02:00
fd230db0cb Bump serde_json from 1.0.39 to 1.0.40
Bumps [serde_json](https://github.com/serde-rs/json) from 1.0.39 to 1.0.40.
- [Release notes](https://github.com/serde-rs/json/releases)
- [Commits](https://github.com/serde-rs/json/compare/v1.0.39...v1.0.40)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-07-01 04:29:15 +00:00
92a95f33d4 Bump version number
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/tag Build is passing
2019-06-28 15:26:12 +02:00
7e13f93ee3 Update dependencies 2019-06-28 15:25:28 +02:00
36afc8732e Merge pull request #29 from vbrandl/dependabot/cargo/serde_derive-1.0.94
All checks were successful
continuous-integration/drone/push Build is passing
Bump serde_derive from 1.0.93 to 1.0.94
2019-06-28 14:16:41 +02:00
abeed1f971 Bump serde_derive from 1.0.93 to 1.0.94
Bumps [serde_derive](https://github.com/serde-rs/serde) from 1.0.93 to 1.0.94.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.93...v1.0.94)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-06-28 04:26:03 +00:00
03a0743517 Merge pull request #27 from vbrandl/dependabot/cargo/structopt-0.2.18 2019-06-27 07:19:36 +00:00
cbfd56b33a Merge pull request #26 from vbrandl/dependabot/cargo/futures-0.1.28 2019-06-27 07:18:43 +00:00
9c5208d6e4 Bump structopt from 0.2.16 to 0.2.18
Bumps [structopt](https://github.com/TeXitoi/structopt) from 0.2.16 to 0.2.18.
- [Release notes](https://github.com/TeXitoi/structopt/releases)
- [Changelog](https://github.com/TeXitoi/structopt/blob/v0.2.18/CHANGELOG.md)
- [Commits](https://github.com/TeXitoi/structopt/compare/v0.2.16...v0.2.18)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-06-27 04:25:09 +00:00
92d7b6668a Bump futures from 0.1.27 to 0.1.28
Bumps [futures](https://github.com/rust-lang-nursery/futures-rs) from 0.1.27 to 0.1.28.
- [Release notes](https://github.com/rust-lang-nursery/futures-rs/releases)
- [Changelog](https://github.com/rust-lang-nursery/futures-rs/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-lang-nursery/futures-rs/compare/0.1.27...0.1.28)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-06-27 04:24:37 +00:00
97510fa325 Bump version number
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/tag Build is passing
2019-06-26 18:20:56 +02:00
65ba104de1 Merge pull request #23 from vbrandl/dependabot/cargo/ructe-0.6.4
All checks were successful
continuous-integration/drone/push Build is passing
Bump ructe from 0.6.2 to 0.6.4
2019-06-26 18:18:20 +02:00
9599d934a2 Merge pull request #25 from vbrandl/dependabot/cargo/serde_derive-1.0.93
Bump serde_derive from 1.0.92 to 1.0.93
2019-06-26 18:18:06 +02:00
61e2dd174a Bump ructe from 0.6.2 to 0.6.4
Bumps [ructe](https://github.com/kaj/ructe) from 0.6.2 to 0.6.4.
- [Release notes](https://github.com/kaj/ructe/releases)
- [Commits](https://github.com/kaj/ructe/compare/v0.6.2...v0.6.4)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-06-26 16:17:36 +00:00
fe00cddd47 Bump serde_derive from 1.0.92 to 1.0.93
Bumps [serde_derive](https://github.com/serde-rs/serde) from 1.0.92 to 1.0.93.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.92...v1.0.93)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-06-26 16:17:33 +00:00
9b73c99922 Merge pull request #24 from vbrandl/dependabot/cargo/serde-1.0.93
All checks were successful
continuous-integration/drone/push Build is passing
Bump serde from 1.0.92 to 1.0.93
2019-06-26 18:16:03 +02:00
ed3da3a2c3 Bump serde from 1.0.92 to 1.0.93
Bumps [serde](https://github.com/serde-rs/serde) from 1.0.92 to 1.0.93.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.92...v1.0.93)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-06-24 04:29:52 +00:00
504476b145 Merge pull request #22 from vbrandl/dependabot/cargo/actix-web-1.0.2
All checks were successful
continuous-integration/drone/push Build is passing
Bump actix-web from 1.0.0 to 1.0.2
2019-06-22 13:45:41 +02:00
9bc1b42750 Bump actix-web from 1.0.0 to 1.0.2
Bumps [actix-web](https://github.com/actix/actix-web) from 1.0.0 to 1.0.2.
- [Release notes](https://github.com/actix/actix-web/releases)
- [Changelog](https://github.com/actix/actix-web/blob/master/CHANGES.md)
- [Commits](https://github.com/actix/actix-web/compare/web-v1.0.0...web-v1.0.2)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-06-19 04:22:48 +00:00
140265b713 Cleanup and use internal result type
All checks were successful
continuous-integration/drone/push Build is passing
2019-06-16 22:20:09 +02:00
4446d9b879 Bump version number
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/tag Build is passing
2019-06-16 21:46:43 +02:00
ac8ba338bb Don't reuse cache struct
Also we avoid converting from String into Cow<'a, str>'
2019-06-16 21:45:13 +02:00
d609f9bf43 Bump version number
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/tag Build is passing
2019-06-16 15:03:12 +02:00
6bc783451e Update README 2019-06-16 15:02:45 +02:00
21243e6cfb Document JSON endpoint on index page 2019-06-16 15:00:46 +02:00
05736ee3ba Bump version number
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/tag Build is passing
2019-06-16 14:43:00 +02:00
d23588172b Merge branch 'feature/json-output' 2019-06-16 14:33:47 +02:00
ce77854754 Implement JSON endpoint 2019-06-16 14:33:15 +02:00
70e83d8cee Bump version number
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/tag Build is passing
2019-06-12 21:58:02 +02:00
284e41c591 Fix footer structure 2019-06-12 21:57:24 +02:00
ec8bbe0325 Bump version number
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/tag Build is passing
2019-06-12 21:53:47 +02:00
8d4de48c11 Calculate repo count on start and increment when a new repo is cloned
All checks were successful
continuous-integration/drone/push Build is passing
2019-06-12 21:51:54 +02:00
eb718990ec Add repo count to templates 2019-06-12 21:51:16 +02:00
60dc242e5a Add repo count to templates 2019-06-12 21:50:45 +02:00
615460c87b Update dependencies
All checks were successful
continuous-integration/drone/push Build is passing
2019-06-12 20:05:55 +02:00
ba6fc7d394 Update git2 to 0.9.1
All checks were successful
continuous-integration/drone/push Build is passing
2019-06-12 20:04:26 +02:00
5551c6f3e4 Update serde and serde_derive to 1.0.92
All checks were successful
continuous-integration/drone/push Build is passing
2019-06-12 20:00:00 +02:00
38399b0bcd Update actix-web to 1.0.0 2019-06-12 19:55:32 +02:00
ad4d87ca2f Update reqwest to 0.9.18 2019-06-12 19:53:51 +02:00
137f264bdf Merge pull request #13 from vbrandl/dependabot/cargo/structopt-0.2.16
All checks were successful
continuous-integration/drone/push Build is passing
Bump structopt from 0.2.15 to 0.2.16
2019-06-01 20:51:42 +02:00
8cfe84c763 Bump structopt from 0.2.15 to 0.2.16
Bumps [structopt](https://github.com/TeXitoi/structopt) from 0.2.15 to 0.2.16.
- [Release notes](https://github.com/TeXitoi/structopt/releases)
- [Changelog](https://github.com/TeXitoi/structopt/blob/master/CHANGELOG.md)
- [Commits](https://github.com/TeXitoi/structopt/compare/v0.2.15...v0.2.16)
2019-05-30 05:32:17 +00:00
787ff55444 Bump version number
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/tag Build is passing
2019-05-28 22:26:55 +02:00
3901fe9e9c Cleanup
All checks were successful
continuous-integration/drone/push Build is passing
2019-05-28 22:06:31 +02:00
e0b6ee69f1 Actually run as user
All checks were successful
continuous-integration/drone/push Build is passing
2019-05-28 21:59:18 +02:00
75398a3613 Use adduser
All checks were successful
continuous-integration/drone/push Build is passing
2019-05-28 21:56:44 +02:00
a944e8b149 Don't run as root in the container
All checks were successful
continuous-integration/drone/push Build is passing
2019-05-28 21:46:47 +02:00
d9faf25648 Make script executable
[skip ci]
2019-05-19 16:05:58 +02:00
d2977eee32 Add script to list repositories
[ci skip]
2019-05-19 16:01:58 +02:00
569ce3a457 Bump version number
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/tag Build is passing
2019-05-19 13:56:56 +02:00
a77962732e Update dependencies 2019-05-19 13:56:23 +02:00
6438bbba82 Make code async 2019-05-19 13:56:11 +02:00
0fcafc7e4b Bump version number
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/tag Build is passing
2019-05-14 01:13:16 +02:00
5fd0eaf289 Use log4rs instead of pretty env logger 2019-05-14 01:12:43 +02:00
2236cf8b53 Refactor into smaller modules and implement new logger 2019-05-14 01:12:13 +02:00
60cba9951f Add new error types 2019-05-14 01:11:54 +02:00
d6835b96de Refactor into smaller modules 2019-05-14 01:11:39 +02:00
6d980d92be Ignore default log file 2019-05-14 01:10:46 +02:00
48e65fef36 Bump version number
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/tag Build is passing
2019-05-13 22:08:10 +02:00
514c30e13c Use orange favicon 2019-05-13 22:07:37 +02:00
20 changed files with 997 additions and 694 deletions

1
.gitignore vendored
View File

@ -2,3 +2,4 @@
**/*.rs.bk
repos
cache
hoc.log

1089
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,27 +1,27 @@
[package]
name = "hoc"
version = "0.4.0"
version = "0.10.0"
authors = ["Valentin Brandl <vbrandl@riseup.net>"]
edition = "2018"
build = "build.rs"
[dependencies]
actix-web = "1.0.0-beta.2"
actix-web = "1.0.3"
badge = "0.2.0"
bytes = "0.4.12"
futures = "0.1.26"
git2 = "0.8.0"
futures = "0.1.28"
git2 = "0.9.1"
lazy_static = "1.3.0"
log = "0.4.6"
log4rs = "0.8.3"
number_prefix = "0.3.0"
openssl-probe = "0.1.2"
pretty_env_logger = "0.3.0"
reqwest = "0.9.16"
serde = "1.0.90"
serde_derive = "1.0.90"
serde_json = "1.0.39"
structopt = "0.2.15"
reqwest = "0.9.17"
serde = "1.0.93"
serde_derive = "1.0.94"
serde_json = "1.0.40"
structopt = "0.2.18"
[build-dependencies]
ructe = "0.6.2"
ructe = "0.6.4"
vergen = "3.0.4"

View File

@ -29,10 +29,14 @@ FROM alpine:latest
RUN apk --no-cache add --update git
RUN adduser -D hoc
WORKDIR /home/hoc
USER hoc
# once we don't need a git binary anymore, this should be enough
# FROM scratch
# COPY --from=linuxkit/ca-certificates:v0.7 / /
COPY --from=builder /home/rust/src/target/x86_64-unknown-linux-musl/release/hoc /hoc
COPY --from=builder /home/rust/src/target/x86_64-unknown-linux-musl/release/hoc .
ENTRYPOINT ["/hoc"]
ENTRYPOINT ["/home/hoc/hoc"]

View File

@ -20,8 +20,14 @@ The API is as simple as
https://<host>/<service>/<user>/<repo>
```
where `<service>` is one of `gitub`, `gitlab` or `bitbucket`.
where `<service>` is one of `gitub`, `gitlab` or `bitbucket`. The HoC data can also be received as JSON by appending
`/json` to the reuqest path:
```
https://<host>/<service>/<user>/<repo>/json
```
There is also an overview page available via `https://<host>/view/<service>/<user>/<repo>`
## Building

View File

@ -2,11 +2,10 @@ version: "2"
services:
hoc:
# build: .
# image: local/hoc:latest
image: registry.gitlab.com/vbrandl/hoc:latest
image: vbrandl/hits-of-code:latest
volumes:
- ./repos:/repos
- ./cache:/cache
ports:
- "127.0.0.1:8080:8080"
- ./repos:/home/hoc/repos
- ./cache:/home/hoc/cache
# ports:
# - "127.0.0.1:8080:8080"
restart: always

9
scripts/list.sh Executable file
View File

@ -0,0 +1,9 @@
#!/usr/bin/env sh
set -e
DIR=${1:-repos}
find "$DIR" -mindepth 3 -maxdepth 3 -type d \
| sed -e "s/$DIR/https:\//g" \
| sort

View File

@ -1,4 +1,4 @@
use crate::Error;
use crate::error::{Error, Result};
use std::{
borrow::Cow,
fs::{create_dir_all, File, OpenOptions},
@ -9,7 +9,7 @@ use std::{
/// Enum to indicate the state of the cache
pub(crate) enum CacheState<'a> {
/// Current head and cached head are the same
Current(u64),
Current { count: u64, commits: u64 },
/// Cached head is older than current head
Old(Cache<'a>),
/// No cache was found
@ -17,11 +17,14 @@ pub(crate) enum CacheState<'a> {
}
impl<'a> CacheState<'a> {
pub(crate) fn read_from_file(path: impl AsRef<Path>, head: &str) -> Result<CacheState, Error> {
pub(crate) fn read_from_file(path: impl AsRef<Path>, head: &str) -> Result<CacheState> {
if path.as_ref().exists() {
let cache: Cache = serde_json::from_reader(BufReader::new(File::open(path)?))?;
if cache.head == head {
Ok(CacheState::Current(cache.count))
Ok(CacheState::Current {
count: cache.count,
commits: cache.commits,
})
} else {
Ok(CacheState::Old(cache))
}
@ -30,26 +33,35 @@ impl<'a> CacheState<'a> {
}
}
pub(crate) fn calculate_new_cache(self, count: u64, head: Cow<'a, str>) -> Cache {
pub(crate) fn calculate_new_cache(self, count: u64, commits: u64, head: Cow<'a, str>) -> Cache {
match self {
CacheState::Old(mut cache) => {
cache.head = head;
cache.count += count;
cache.commits += commits;
cache
}
CacheState::No | CacheState::Current(_) => Cache { head, count },
CacheState::No | CacheState::Current { .. } => Cache {
head,
count,
commits,
},
}
}
}
#[derive(Serialize, Deserialize)]
pub(crate) struct Cache<'a> {
/// HEAD commit ref
pub head: Cow<'a, str>,
/// HoC value
pub count: u64,
/// Number of commits
pub commits: u64,
}
impl<'a> Cache<'a> {
pub(crate) fn write_to_file(&self, path: impl AsRef<Path>) -> Result<(), Error> {
pub(crate) fn write_to_file(&self, path: impl AsRef<Path>) -> Result<()> {
create_dir_all(path.as_ref().parent().ok_or(Error::Internal)?)?;
serde_json::to_writer(
OpenOptions::new()

79
src/config.rs Normal file
View File

@ -0,0 +1,79 @@
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,
#[structopt(subcommand)]
pub(crate) migrate: Option<Migration>,
}
#[derive(StructOpt, Debug, Clone, Copy)]
pub(crate) enum Migration {
#[structopt(name = "migrate-commit-count")]
CacheCommitCount,
}
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(())
}

24
src/count.rs Normal file
View File

@ -0,0 +1,24 @@
use crate::error::Result;
use std::{fs::read_dir, path::Path, result::Result as StdResult};
pub(crate) fn count_repositories<P>(repo_path: P) -> Result<usize>
where
P: AsRef<Path>,
{
Ok(read_dir(repo_path)?
.filter_map(StdResult::ok)
.filter(|entry| entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false))
.map(|entry| read_dir(entry.path()))
.filter_map(StdResult::ok)
.flat_map(|dir| {
dir.filter_map(StdResult::ok)
.filter(|entry| entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false))
})
.map(|entry| read_dir(entry.path()))
.filter_map(StdResult::ok)
.flat_map(|dir| {
dir.filter_map(StdResult::ok)
.filter(|entry| entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false))
})
.count())
}

View File

@ -1,6 +1,9 @@
use crate::P500;
use crate::{
statics::{REPO_COUNT, VERSION_INFO},
templates,
};
use actix_web::{HttpResponse, ResponseError};
use std::fmt;
use std::{fmt, sync::atomic::Ordering};
pub(crate) type Result<T> = std::result::Result<T, Error>;
@ -11,6 +14,9 @@ pub(crate) enum Error {
Git(git2::Error),
Internal,
Io(std::io::Error),
Log(log::SetLoggerError),
LogBuilder(log4rs::config::Errors),
Parse(std::num::ParseIntError),
Serial(serde_json::Error),
}
@ -22,6 +28,9 @@ impl fmt::Display for Error {
Error::Git(e) => write!(fmt, "Git({})", e),
Error::Internal => write!(fmt, "Internal Error"),
Error::Io(e) => write!(fmt, "Io({})", e),
Error::Log(e) => write!(fmt, "Log({})", e),
Error::LogBuilder(e) => write!(fmt, "LogBuilder({})", e),
Error::Parse(e) => write!(fmt, "Parse({})", e),
Error::Serial(e) => write!(fmt, "Serial({})", e),
}
}
@ -29,15 +38,15 @@ impl fmt::Display for Error {
impl ResponseError for Error {
fn error_response(&self) -> HttpResponse {
let mut buf = Vec::new();
templates::p500(&mut buf, VERSION_INFO, REPO_COUNT.load(Ordering::Relaxed)).unwrap();
HttpResponse::InternalServerError()
.content_type("text/html")
.body(P500.as_slice())
.body(buf)
}
fn render_response(&self) -> HttpResponse {
HttpResponse::InternalServerError()
.content_type("text/html")
.body(P500.as_slice())
self.error_response()
}
}
@ -55,6 +64,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 {
fn from(err: std::io::Error) -> Self {
Error::Io(err)
@ -72,3 +87,15 @@ impl From<reqwest::Error> for Error {
Error::Client(err)
}
}
impl From<log4rs::config::Errors> for Error {
fn from(err: log4rs::config::Errors) -> Self {
Error::LogBuilder(err)
}
}
impl From<std::num::ParseIntError> for Error {
fn from(err: std::num::ParseIntError) -> Self {
Error::Parse(err)
}
}

View File

@ -1,3 +1,5 @@
#![type_length_limit = "2257138"]
#[macro_use]
extern crate actix_web;
#[macro_use]
@ -8,13 +10,18 @@ extern crate log;
extern crate serde_derive;
mod cache;
mod config;
mod count;
mod error;
mod service;
mod statics;
use crate::{
cache::CacheState,
config::Migration,
error::{Error, Result},
service::{Bitbucket, FormService, GitHub, Gitlab, Service},
statics::{CLIENT, CSS, FAVICON, OPT, REPO_COUNT, VERSION_INFO},
};
use actix_web::{
error::ErrorBadRequest,
@ -23,26 +30,21 @@ use actix_web::{
};
use badge::{Badge, BadgeOptions};
use bytes::Bytes;
use futures::{unsync::mpsc, Stream};
use futures::{unsync::mpsc, Future, Stream};
use git2::Repository;
use number_prefix::{NumberPrefix, Prefixed, Standalone};
use std::{
borrow::Cow,
fs::create_dir_all,
path::{Path, PathBuf},
fs::{create_dir_all, read_dir, rename},
path::Path,
process::Command,
sync::atomic::Ordering,
sync::Arc,
time::{Duration, SystemTime},
};
use structopt::StructOpt;
include!(concat!(env!("OUT_DIR"), "/templates.rs"));
pub struct VersionInfo<'a> {
pub commit: &'a str,
pub version: &'a str,
}
#[derive(Deserialize, Serialize)]
struct GeneratorForm<'a> {
service: FormService,
@ -50,69 +52,16 @@ struct GeneratorForm<'a> {
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 {
repos: String,
cache: String,
}
const CSS: &str = include_str!("../static/tacit-css.min.css");
const FAVICON: &[u8] = include_bytes!("../static/favicon32.png");
#[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,
#[structopt(short = "w", long = "workers", default_value = "4")]
/// Number of worker threads
workers: usize,
#[derive(Serialize)]
struct JsonResponse<'a> {
head: &'a str,
count: u64,
commits: u64,
}
fn pull(path: impl AsRef<Path>) -> Result<()> {
@ -122,17 +71,13 @@ fn pull(path: impl AsRef<Path>) -> Result<()> {
Ok(())
}
fn hoc(repo: &str, repo_dir: &str, cache_dir: &str) -> Result<(u64, String)> {
fn hoc(repo: &str, repo_dir: &str, cache_dir: &str) -> Result<(u64, String, u64)> {
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 repo = Repository::open_bare(&repo_dir)?;
let head = format!("{}", repo.head()?.target().ok_or(Error::Internal)?);
let mut arg_commit_count = vec!["rev-list".to_string(), "--count".to_string()];
let mut arg = vec![
"log".to_string(),
"--pretty=tformat:".to_string(),
@ -147,16 +92,18 @@ fn hoc(repo: &str, repo_dir: &str, cache_dir: &str) -> Result<(u64, String)> {
];
let cache = CacheState::read_from_file(&cache_dir, &head)?;
match &cache {
CacheState::Current(res) => {
CacheState::Current { count, commits } => {
info!("Using cache for {}", repo_dir);
return Ok((*res, head));
return Ok((*count, head, *commits));
}
CacheState::Old(cache) => {
info!("Updating cache for {}", repo_dir);
arg.push(format!("{}..HEAD", cache.head));
arg_commit_count.push(format!("{}..HEAD", cache.head));
}
CacheState::No => {
info!("Creating cache for {}", repo_dir);
arg_commit_count.push("HEAD".to_string());
}
};
arg.push("--".to_string());
@ -167,6 +114,13 @@ fn hoc(repo: &str, repo_dir: &str, cache_dir: &str) -> Result<(u64, String)> {
.output()?
.stdout;
let output = String::from_utf8_lossy(&output);
let output_commits = Command::new("git")
.args(&arg_commit_count)
.current_dir(&repo_dir)
.output()?
.stdout;
let output_commits = String::from_utf8_lossy(&output_commits);
let commits: u64 = output_commits.trim().parse()?;
let count: u64 = output
.lines()
.map(|s| {
@ -178,10 +132,10 @@ fn hoc(repo: &str, repo_dir: &str, cache_dir: &str) -> Result<(u64, String)> {
})
.sum();
let cache = cache.calculate_new_cache(count, (&head).into());
let cache = cache.calculate_new_cache(count, commits, (&head).into());
cache.write_to_file(cache_dir)?;
Ok((cache.count, head))
Ok((cache.count, head, commits))
}
fn remote_exists(url: &str) -> Result<bool> {
@ -191,6 +145,7 @@ fn remote_exists(url: &str) -> Result<bool> {
enum HocResult {
Hoc {
hoc: u64,
commits: u64,
hoc_pretty: String,
head: String,
url: String,
@ -204,56 +159,72 @@ fn handle_hoc_request<T, F>(
state: web::Data<Arc<State>>,
data: web::Path<(String, String)>,
mapper: F,
) -> Result<HttpResponse>
) -> impl Future<Item = HttpResponse, Error = Error>
where
T: Service,
F: Fn(HocResult) -> Result<HttpResponse>,
{
hoc_request::<T>(state, data).and_then(mapper)
futures::future::result(Ok(()))
.and_then(move |_| {
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);
let url = format!("https://{}", service_path);
if !file.exists() {
if !remote_exists(&url)? {
warn!("Repository does not exist: {}", url);
return Ok(HocResult::NotFound);
}
info!("Cloning {} for the first time", url);
create_dir_all(file)?;
let repo = Repository::init_bare(file)?;
repo.remote_add_fetch("origin", "refs/heads/*:refs/heads/*")?;
repo.remote_set_url("origin", &url)?;
REPO_COUNT.fetch_add(1, Ordering::Relaxed);
}
pull(&path)?;
let (hoc, head, commits) = hoc(&service_path, &state.repos, &state.cache)?;
let hoc_pretty = match NumberPrefix::decimal(hoc as f64) {
Standalone(hoc) => hoc.to_string(),
Prefixed(prefix, hoc) => format!("{:.1}{}", hoc, prefix),
};
Ok(HocResult::Hoc {
hoc,
commits,
hoc_pretty,
head: head.to_string(),
url,
repo,
service_path,
})
})
.and_then(mapper)
}
fn hoc_request<T: Service>(
fn json_hoc<T: Service>(
state: web::Data<Arc<State>>,
data: web::Path<(String, String)>,
) -> 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);
let url = format!("https://{}", service_path);
if !file.exists() {
if !remote_exists(&url)? {
warn!("Repository does not exist: {}", url);
return Ok(HocResult::NotFound);
}
info!("Cloning {} for the first time", url);
create_dir_all(file)?;
let repo = Repository::init_bare(file)?;
repo.remote_add_fetch("origin", "refs/heads/*:refs/heads/*")?;
repo.remote_set_url("origin", &url)?;
}
pull(&path)?;
let (hoc, head) = hoc(&service_path, &state.repos, &state.cache)?;
let hoc_pretty = match NumberPrefix::decimal(hoc as f64) {
Standalone(hoc) => hoc.to_string(),
Prefixed(prefix, hoc) => format!("{:.1}{}", hoc, prefix),
) -> impl Future<Item = HttpResponse, Error = Error> {
let mapper = |r| match r {
HocResult::NotFound => p404(),
HocResult::Hoc {
hoc, head, commits, ..
} => Ok(HttpResponse::Ok().json(JsonResponse {
head: &head,
count: hoc,
commits,
})),
};
Ok(HocResult::Hoc {
hoc,
hoc_pretty,
head,
url,
repo,
service_path,
})
handle_hoc_request::<T, _>(state, data, mapper)
}
fn calculate_hoc<T: Service>(
state: web::Data<Arc<State>>,
data: web::Path<(String, String)>,
) -> Result<HttpResponse> {
) -> impl Future<Item = HttpResponse, Error = Error> {
let mapper = |r| match r {
HocResult::NotFound => Ok(p404()),
HocResult::NotFound => p404(),
HocResult::Hoc { hoc_pretty, .. } => {
let badge_opt = BadgeOptions {
subject: "Hits-of-Code".to_string(),
@ -284,11 +255,12 @@ fn calculate_hoc<T: Service>(
fn overview<T: Service>(
state: web::Data<Arc<State>>,
data: web::Path<(String, String)>,
) -> Result<HttpResponse> {
) -> impl Future<Item = HttpResponse, Error = Error> {
let mapper = |r| match r {
HocResult::NotFound => Ok(p404()),
HocResult::NotFound => p404(),
HocResult::Hoc {
hoc,
commits,
hoc_pretty,
url,
head,
@ -299,6 +271,7 @@ fn overview<T: Service>(
templates::overview(
&mut buf,
VERSION_INFO,
REPO_COUNT.load(Ordering::Relaxed),
&OPT.domain,
&service_path,
&url,
@ -306,6 +279,7 @@ fn overview<T: Service>(
&hoc_pretty,
&head,
&T::commit_url(&repo, &head),
commits,
)?;
let (tx, rx_body) = mpsc::unbounded();
@ -320,10 +294,15 @@ fn overview<T: Service>(
}
#[get("/")]
fn index() -> HttpResponse {
HttpResponse::Ok()
.content_type("text/html")
.body(INDEX.as_slice())
fn index() -> Result<HttpResponse> {
let mut buf = Vec::new();
templates::index(
&mut buf,
VERSION_INFO,
REPO_COUNT.load(Ordering::Relaxed),
&OPT.domain,
)?;
Ok(HttpResponse::Ok().content_type("text/html").body(buf))
}
#[post("/generate")]
@ -333,6 +312,7 @@ fn generate(params: web::Form<GeneratorForm>) -> Result<HttpResponse> {
templates::generate(
&mut buf,
VERSION_INFO,
REPO_COUNT.load(Ordering::Relaxed),
&OPT.domain,
params.service.url(),
params.service.service(),
@ -346,10 +326,10 @@ fn generate(params: web::Form<GeneratorForm>) -> Result<HttpResponse> {
.streaming(rx_body.map_err(|_| ErrorBadRequest("bad request"))))
}
fn p404() -> HttpResponse {
HttpResponse::NotFound()
.content_type("text/html")
.body(P404.as_slice())
fn p404() -> Result<HttpResponse> {
let mut buf = Vec::new();
templates::p404(&mut buf, VERSION_INFO, REPO_COUNT.load(Ordering::Relaxed))?;
Ok(HttpResponse::NotFound().content_type("text/html").body(buf))
}
#[get("/tacit-css.min.css")]
@ -362,16 +342,13 @@ fn favicon32() -> HttpResponse {
HttpResponse::Ok().content_type("image/png").body(FAVICON)
}
fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG", "actix_web=info,hoc=info");
pretty_env_logger::init();
openssl_probe::init_ssl_cert_env_vars();
fn start_server() -> Result<()> {
let interface = format!("{}:{}", OPT.host, OPT.port);
let state = Arc::new(State {
repos: OPT.outdir.display().to_string(),
cache: OPT.cachedir.display().to_string(),
});
HttpServer::new(move || {
Ok(HttpServer::new(move || {
App::new()
.data(state.clone())
.wrap(middleware::Logger::default())
@ -379,15 +356,55 @@ fn main() -> std::io::Result<()> {
.service(css)
.service(favicon32)
.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>))
.service(web::resource("/view/github/{user}/{repo}").to(overview::<GitHub>))
.service(web::resource("/view/gitlab/{user}/{repo}").to(overview::<Gitlab>))
.service(web::resource("/view/bitbucket/{user}/{repo}").to(overview::<Bitbucket>))
.default_service(web::resource("").route(web::get().to(p404)))
.service(web::resource("/github/{user}/{repo}").to_async(calculate_hoc::<GitHub>))
.service(web::resource("/gitlab/{user}/{repo}").to_async(calculate_hoc::<Gitlab>))
.service(web::resource("/bitbucket/{user}/{repo}").to_async(calculate_hoc::<Bitbucket>))
.service(web::resource("/github/{user}/{repo}/json").to_async(json_hoc::<GitHub>))
.service(web::resource("/gitlab/{user}/{repo}/json").to_async(json_hoc::<Gitlab>))
.service(web::resource("/bitbucket/{user}/{repo}/json").to_async(json_hoc::<Bitbucket>))
.service(web::resource("/view/github/{user}/{repo}").to_async(overview::<GitHub>))
.service(web::resource("/view/gitlab/{user}/{repo}").to_async(overview::<Gitlab>))
.service(web::resource("/view/bitbucket/{user}/{repo}").to_async(overview::<Bitbucket>))
.default_service(web::resource("").route(web::get().to_async(p404)))
})
.workers(OPT.workers)
.bind(interface)?
.run()
.run()?)
}
fn migrate_cache() -> Result<()> {
let mut backup_cache = OPT.cachedir.clone();
backup_cache.set_extension("bak");
rename(&OPT.cachedir, backup_cache)?;
let outdir = OPT.outdir.display().to_string();
let cachedir = OPT.cachedir.display().to_string();
for service in read_dir(&OPT.outdir)? {
let service = service?;
for namespace in read_dir(service.path())? {
let namespace = namespace?;
for repo in read_dir(namespace.path())? {
let repo_path = repo?.path().display().to_string();
let repo_path: String =
repo_path
.split(&outdir)
.fold(String::new(), |mut acc, next| {
acc.push_str(next);
acc
});
println!("{}", repo_path);
hoc(&repo_path, &outdir, &cachedir)?;
}
}
}
Ok(())
}
fn main() -> Result<()> {
config::init()?;
match &OPT.migrate {
None => start_server(),
Some(migration) => match migration {
Migration::CacheCommitCount => migrate_cache(),
},
}
}

22
src/statics.rs Normal file
View File

@ -0,0 +1,22 @@
use crate::{config::Opt, count::count_repositories};
use std::sync::atomic::AtomicUsize;
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 REPO_COUNT: AtomicUsize =
AtomicUsize::new(count_repositories(&OPT.outdir).unwrap());
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 682 B

After

Width:  |  Height:  |  Size: 983 B

View File

@ -1,6 +1,6 @@
@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, repo_count: usize)
<!DOCTYPE html>
<html lang="en">
@ -38,6 +38,13 @@
</li>
</ul>
</nav>
<nav>
<ul>
<li>
<small>Currently serving @repo_count repositories</small>
</li>
</ul>
</nav>
<nav>
<ul>
<li><small><a href="https://github.com/vbrandl/hoc">GitHub</a></small></li>

View File

@ -1,7 +1,7 @@
@use super::base;
@use crate::VersionInfo;
@use crate::statics::VersionInfo;
@(version_info: VersionInfo, domain: &str, url: &str, service: &str, path: &str)
@(version_info: VersionInfo, repo_count: usize, domain: &str, url: &str, service: &str, path: &str)
@:base("Hits-of-Code Badges", "Badge Generator", {
@ -20,4 +20,4 @@ It will be rendered like this
<pre>
<a href="https://@domain/view/@service/@path"><img src="https://@domain/@service/@path" alt="example badge" /></a>
</pre>
}, version_info)
}, version_info, repo_count)

View File

@ -1,7 +1,7 @@
@use super::base;
@use crate::VersionInfo;
@use crate::statics::VersionInfo;
@(version_info: VersionInfo, domain: &str)
@(version_info: VersionInfo, repo_count: usize, domain: &str)
@:base("Hits-of-Code Badges", "Hits-of-Code Badges", {
@ -45,6 +45,22 @@ would render this badge:
alt="example badge" /></a>
</pre>
<p>
You can also request the HoC as JSON by appending <code>/json</code> to the request path. This will return a JSON object
with three fields: <code>count</code> (the HoC value), <code>commits</code> (the number of commits) and
<code>head</code> (the commit ref of HEAD). Requesting <a
href="https://@domain/github/vbrandl/hoc/json">https://@domain/github/vbrandl/hoc/json</a> might return something along
the lines of
</p>
<pre>
&#123;
"head": "1f01c3b964b018fb0c0c2c5b572bf4ace2968546",
"count": 8324,
"commits": 223
&#125;
</pre>
<h2>Badge Generator</h2>
<form method="post" action="/generate">
@ -76,4 +92,4 @@ my <a href="https://mirror.oldsql.cc/key.asc">GPG key</a>
(<a href="http://pool.sks-keyservers.net/pks/lookup?op=get&amp;search=0x1FFE431282F4B8CC0A7579167FB009175885FC76">from a
keyserver</a>), or by using any other UID from my key.
</p>
}, version_info)
}, version_info, repo_count)

View File

@ -1,12 +1,13 @@
@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, repo_count: usize, domain: &str, path: &str, url: &str, hoc: u64, hoc_pretty: &str, head: &str, commit_url: &str, commits: u64)
@:base("Hits-of-Code Badges", "Overview", {
<p>
The project <a href="@url">@url</a> has <strong>@hoc_pretty</strong> (exactly @hoc) hits of code at <a href="@commit_url">@head</a>.
The project <a href="@url">@url</a> has <strong>@hoc_pretty</strong> (exactly @hoc) hits of code at
<a href="@commit_url">@head</a>. The repository contains <strong>@commits</strong> commits.
</p>
<p>
@ -16,4 +17,4 @@ To include the badge in your readme, use the following markdown:
<pre>
[![Hits-of-Code](https://@domain/@path)](https://@domain/view/@path)
</pre>
}, version_info)
}, version_info, repo_count)

View File

@ -1,7 +1,7 @@
@use super::base;
@use crate::VersionInfo;
@use crate::statics::VersionInfo;
@(version_info: VersionInfo)
@(version_info: VersionInfo, repo_count: usize)
@:base("Page not Found - Hits-of-Code Badges", "404 - Page not Found", {
<p>
@ -11,4 +11,4 @@
<p>
If you think, this is a mistake on my side, please <a href="mailto:mail+hoc@@vbrandl.net">drop me a mail</a>.
</p>
}, version_info)
}, version_info, repo_count)

View File

@ -1,7 +1,7 @@
@use super::base;
@use crate::VersionInfo;
@use crate::statics::VersionInfo;
@(version_info: VersionInfo)
@(version_info: VersionInfo, repo_count: usize)
@:base("Internal Server Error - Hits-of-Code Badges", "500 - Internal Server Error", {
<p>
@ -11,4 +11,4 @@
<p>
If you think, this is a bug, please <a href="mailto:mail+hoc@@vbrandl.net">drop me a mail</a>.
</p>
}, version_info)
}, version_info, repo_count)