Merge branch 'feature/commit-count'

Closes #33
This commit is contained in:
Valentin Brandl 2019-07-07 14:53:10 +02:00
commit 268734efdd
No known key found for this signature in database
GPG Key ID: 30D341DD34118D7D
6 changed files with 111 additions and 31 deletions

View File

@ -9,7 +9,7 @@ use std::{
/// Enum to indicate the state of the cache /// Enum to indicate the state of the cache
pub(crate) enum CacheState<'a> { pub(crate) enum CacheState<'a> {
/// Current head and cached head are the same /// Current head and cached head are the same
Current(u64), Current { count: u64, commits: u64 },
/// Cached head is older than current head /// Cached head is older than current head
Old(Cache<'a>), Old(Cache<'a>),
/// No cache was found /// No cache was found
@ -21,7 +21,10 @@ impl<'a> CacheState<'a> {
if path.as_ref().exists() { if path.as_ref().exists() {
let cache: Cache = serde_json::from_reader(BufReader::new(File::open(path)?))?; let cache: Cache = serde_json::from_reader(BufReader::new(File::open(path)?))?;
if cache.head == head { if cache.head == head {
Ok(CacheState::Current(cache.count)) Ok(CacheState::Current {
count: cache.count,
commits: cache.commits,
})
} else { } else {
Ok(CacheState::Old(cache)) Ok(CacheState::Old(cache))
} }
@ -30,22 +33,31 @@ 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 { match self {
CacheState::Old(mut cache) => { CacheState::Old(mut cache) => {
cache.head = head; cache.head = head;
cache.count += count; cache.count += count;
cache.commits += commits;
cache cache
} }
CacheState::No | CacheState::Current(_) => Cache { head, count }, CacheState::No | CacheState::Current { .. } => Cache {
head,
count,
commits,
},
} }
} }
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
pub(crate) struct Cache<'a> { pub(crate) struct Cache<'a> {
/// HEAD commit ref
pub head: Cow<'a, str>, pub head: Cow<'a, str>,
/// HoC value
pub count: u64, pub count: u64,
/// Number of commits
pub commits: u64,
} }
impl<'a> Cache<'a> { impl<'a> Cache<'a> {

View File

@ -46,6 +46,14 @@ pub(crate) struct Opt {
)] )]
/// The logfile /// The logfile
pub(crate) logfile: PathBuf, 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<()> { pub(crate) fn init() -> Result<()> {

View File

@ -16,6 +16,7 @@ pub(crate) enum Error {
Io(std::io::Error), Io(std::io::Error),
Log(log::SetLoggerError), Log(log::SetLoggerError),
LogBuilder(log4rs::config::Errors), LogBuilder(log4rs::config::Errors),
Parse(std::num::ParseIntError),
Serial(serde_json::Error), Serial(serde_json::Error),
} }
@ -29,6 +30,7 @@ impl fmt::Display for Error {
Error::Io(e) => write!(fmt, "Io({})", e), Error::Io(e) => write!(fmt, "Io({})", e),
Error::Log(e) => write!(fmt, "Log({})", e), Error::Log(e) => write!(fmt, "Log({})", e),
Error::LogBuilder(e) => write!(fmt, "LogBuilder({})", e), Error::LogBuilder(e) => write!(fmt, "LogBuilder({})", e),
Error::Parse(e) => write!(fmt, "Parse({})", e),
Error::Serial(e) => write!(fmt, "Serial({})", e), Error::Serial(e) => write!(fmt, "Serial({})", e),
} }
} }
@ -91,3 +93,9 @@ impl From<log4rs::config::Errors> for Error {
Error::LogBuilder(err) Error::LogBuilder(err)
} }
} }
impl From<std::num::ParseIntError> for Error {
fn from(err: std::num::ParseIntError) -> Self {
Error::Parse(err)
}
}

View File

@ -18,6 +18,7 @@ mod statics;
use crate::{ use crate::{
cache::CacheState, cache::CacheState,
config::Migration,
error::{Error, Result}, error::{Error, Result},
service::{Bitbucket, FormService, GitHub, Gitlab, Service}, service::{Bitbucket, FormService, GitHub, Gitlab, Service},
statics::{CLIENT, CSS, FAVICON, OPT, REPO_COUNT, VERSION_INFO}, statics::{CLIENT, CSS, FAVICON, OPT, REPO_COUNT, VERSION_INFO},
@ -34,7 +35,7 @@ use git2::Repository;
use number_prefix::{NumberPrefix, Prefixed, Standalone}; use number_prefix::{NumberPrefix, Prefixed, Standalone};
use std::{ use std::{
borrow::Cow, borrow::Cow,
fs::create_dir_all, fs::{create_dir_all, read_dir, rename},
path::Path, path::Path,
process::Command, process::Command,
sync::atomic::Ordering, sync::atomic::Ordering,
@ -60,6 +61,7 @@ struct State {
struct JsonResponse<'a> { struct JsonResponse<'a> {
head: &'a str, head: &'a str,
count: u64, count: u64,
commits: u64,
} }
fn pull(path: impl AsRef<Path>) -> Result<()> { fn pull(path: impl AsRef<Path>) -> Result<()> {
@ -69,17 +71,13 @@ fn pull(path: impl AsRef<Path>) -> Result<()> {
Ok(()) 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 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);
let head = format!( let repo = Repository::open_bare(&repo_dir)?;
"{}", let head = format!("{}", repo.head()?.target().ok_or(Error::Internal)?);
Repository::open_bare(&repo_dir)? let mut arg_commit_count = vec!["rev-list".to_string(), "--count".to_string()];
.head()?
.target()
.ok_or(Error::Internal)?
);
let mut arg = vec![ let mut arg = vec![
"log".to_string(), "log".to_string(),
"--pretty=tformat:".to_string(), "--pretty=tformat:".to_string(),
@ -94,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)?; let cache = CacheState::read_from_file(&cache_dir, &head)?;
match &cache { match &cache {
CacheState::Current(res) => { CacheState::Current { count, commits } => {
info!("Using cache for {}", repo_dir); info!("Using cache for {}", repo_dir);
return Ok((*res, head)); return Ok((*count, head, *commits));
} }
CacheState::Old(cache) => { CacheState::Old(cache) => {
info!("Updating cache for {}", repo_dir); info!("Updating cache for {}", repo_dir);
arg.push(format!("{}..HEAD", cache.head)); arg.push(format!("{}..HEAD", cache.head));
arg_commit_count.push(format!("{}..HEAD", cache.head));
} }
CacheState::No => { CacheState::No => {
info!("Creating cache for {}", repo_dir); info!("Creating cache for {}", repo_dir);
arg_commit_count.push("HEAD".to_string());
} }
}; };
arg.push("--".to_string()); arg.push("--".to_string());
@ -114,6 +114,13 @@ fn hoc(repo: &str, repo_dir: &str, cache_dir: &str) -> Result<(u64, String)> {
.output()? .output()?
.stdout; .stdout;
let output = String::from_utf8_lossy(&output); 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 let count: u64 = output
.lines() .lines()
.map(|s| { .map(|s| {
@ -125,10 +132,10 @@ fn hoc(repo: &str, repo_dir: &str, cache_dir: &str) -> Result<(u64, String)> {
}) })
.sum(); .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)?; cache.write_to_file(cache_dir)?;
Ok((cache.count, head)) Ok((cache.count, head, commits))
} }
fn remote_exists(url: &str) -> Result<bool> { fn remote_exists(url: &str) -> Result<bool> {
@ -138,6 +145,7 @@ fn remote_exists(url: &str) -> Result<bool> {
enum HocResult { enum HocResult {
Hoc { Hoc {
hoc: u64, hoc: u64,
commits: u64,
hoc_pretty: String, hoc_pretty: String,
head: String, head: String,
url: String, url: String,
@ -176,15 +184,16 @@ where
REPO_COUNT.fetch_add(1, Ordering::Relaxed); REPO_COUNT.fetch_add(1, Ordering::Relaxed);
} }
pull(&path)?; pull(&path)?;
let (hoc, head) = hoc(&service_path, &state.repos, &state.cache)?; let (hoc, head, commits) = hoc(&service_path, &state.repos, &state.cache)?;
let hoc_pretty = match NumberPrefix::decimal(hoc as f64) { let hoc_pretty = match NumberPrefix::decimal(hoc as f64) {
Standalone(hoc) => hoc.to_string(), Standalone(hoc) => hoc.to_string(),
Prefixed(prefix, hoc) => format!("{:.1}{}", hoc, prefix), Prefixed(prefix, hoc) => format!("{:.1}{}", hoc, prefix),
}; };
Ok(HocResult::Hoc { Ok(HocResult::Hoc {
hoc, hoc,
commits,
hoc_pretty, hoc_pretty,
head, head: head.to_string(),
url, url,
repo, repo,
service_path, service_path,
@ -199,9 +208,12 @@ fn json_hoc<T: Service>(
) -> impl Future<Item = HttpResponse, Error = Error> { ) -> impl Future<Item = HttpResponse, Error = Error> {
let mapper = |r| match r { let mapper = |r| match r {
HocResult::NotFound => p404(), HocResult::NotFound => p404(),
HocResult::Hoc { hoc, head, .. } => Ok(HttpResponse::Ok().json(JsonResponse { HocResult::Hoc {
hoc, head, commits, ..
} => Ok(HttpResponse::Ok().json(JsonResponse {
head: &head, head: &head,
count: hoc, count: hoc,
commits,
})), })),
}; };
handle_hoc_request::<T, _>(state, data, mapper) handle_hoc_request::<T, _>(state, data, mapper)
@ -248,6 +260,7 @@ fn overview<T: Service>(
HocResult::NotFound => p404(), HocResult::NotFound => p404(),
HocResult::Hoc { HocResult::Hoc {
hoc, hoc,
commits,
hoc_pretty, hoc_pretty,
url, url,
head, head,
@ -266,6 +279,7 @@ fn overview<T: Service>(
&hoc_pretty, &hoc_pretty,
&head, &head,
&T::commit_url(&repo, &head), &T::commit_url(&repo, &head),
commits,
)?; )?;
let (tx, rx_body) = mpsc::unbounded(); let (tx, rx_body) = mpsc::unbounded();
@ -328,8 +342,7 @@ fn favicon32() -> HttpResponse {
HttpResponse::Ok().content_type("image/png").body(FAVICON) HttpResponse::Ok().content_type("image/png").body(FAVICON)
} }
fn main() -> Result<()> { fn start_server() -> 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(),
@ -358,3 +371,40 @@ fn main() -> Result<()> {
.bind(interface)? .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(),
},
}
}

View File

@ -46,17 +46,18 @@ alt="example badge" /></a>
</pre> </pre>
<p> <p>
You can also request the HoC as JSON by appending <code>/json</code> to the request path. This will return a JSON You can also request the HoC as JSON by appending <code>/json</code> to the request path. This will return a JSON object
object with two fields: <code>count</code> and <code>head</code> with count being the HoC value and head being the with three fields: <code>count</code> (the HoC value), <code>commits</code> (the number of commits) and
commit ref of <code>HEAD</code>. Requesting <code>head</code> (the commit ref of HEAD). Requesting <a
<a href="https://@domain/github/vbrandl/hoc/json">https://@domain/github/vbrandl/hoc/json</a> might return something href="https://@domain/github/vbrandl/hoc/json">https://@domain/github/vbrandl/hoc/json</a> might return something along
along the lines of the lines of
</p> </p>
<pre> <pre>
&#123; &#123;
"head" : "05736ee3ba256ec9a7227c436aef2bf43db109ab", "head": "1f01c3b964b018fb0c0c2c5b572bf4ace2968546",
"count": 7582 "count": 8324,
"commits": 223
&#125; &#125;
</pre> </pre>

View File

@ -1,12 +1,13 @@
@use super::base; @use super::base;
@use crate::statics::VersionInfo; @use crate::statics::VersionInfo;
@(version_info: VersionInfo, repo_count: usize, 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", { @:base("Hits-of-Code Badges", "Overview", {
<p> <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>
<p> <p>