Compare commits

...

53 Commits

Author SHA1 Message Date
9f8b781f7b Bump version (v0.14.5)
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/tag Build is passing
2020-11-23 14:47:22 +01:00
175b7c828b Cleanup cache keys
All checks were successful
continuous-integration/drone/push Build is passing
2020-11-23 14:36:43 +01:00
002119324f Remove unused dependencies 2020-11-23 14:35:12 +01:00
df78b6f1e5 Revert "Dummy modification for audit"
All checks were successful
continuous-integration/drone/push Build is passing
This reverts commit e1bff0d280.
2020-11-23 14:21:46 +01:00
e1bff0d280 Dummy modification for audit
All checks were successful
continuous-integration/drone/push Build is passing
2020-11-23 14:19:39 +01:00
4c9454aa9e Use different cache keys per pipeline 2020-11-23 14:19:11 +01:00
e9e57495a6 Disable nix-build
All checks were successful
continuous-integration/drone/push Build is passing
2020-11-23 14:13:02 +01:00
b6505f6a37 Disable nix-build
All checks were successful
continuous-integration/drone/push Build is passing
2020-11-23 14:12:32 +01:00
a2463bf657 Release binaries on github release page
All checks were successful
continuous-integration/drone/push Build is passing
2020-11-23 14:11:36 +01:00
53cb73cd9b Use checkout@v2 2020-11-23 14:11:18 +01:00
423a3aa0b0 Split formatting and clippy checks into separate pipelines 2020-11-23 14:11:01 +01:00
7a2c6b6f06 Merge pull request #197 from vbrandl/dependabot/cargo/reqwest-0.10.9
Bump reqwest from 0.10.8 to 0.10.9
2020-11-23 12:13:19 +01:00
ffb306a7a8 Merge pull request #196 from vbrandl/dependabot/cargo/ructe-0.13.0
Bump ructe from 0.12.0 to 0.13.0
2020-11-23 12:13:08 +01:00
cef2ae2299 Merge pull request #195 from vbrandl/dependabot/cargo/futures-0.3.8
Bump futures from 0.3.7 to 0.3.8
2020-11-23 12:07:59 +01:00
b91de72d19 Remove travis
All checks were successful
continuous-integration/drone/push Build is passing
2020-11-23 12:07:26 +01:00
fd08489587 Bump futures from 0.3.7 to 0.3.8
Bumps [futures](https://github.com/rust-lang/futures-rs) from 0.3.7 to 0.3.8.
- [Release notes](https://github.com/rust-lang/futures-rs/releases)
- [Changelog](https://github.com/rust-lang/futures-rs/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/futures-rs/compare/0.3.7...0.3.8)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-11-23 10:57:43 +00:00
ce0d6041ea Bump reqwest from 0.10.8 to 0.10.9
Bumps [reqwest](https://github.com/seanmonstar/reqwest) from 0.10.8 to 0.10.9.
- [Release notes](https://github.com/seanmonstar/reqwest/releases)
- [Changelog](https://github.com/seanmonstar/reqwest/blob/master/CHANGELOG.md)
- [Commits](https://github.com/seanmonstar/reqwest/compare/v0.10.8...v0.10.9)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-11-23 10:57:41 +00:00
3af60a82ce Merge pull request #194 from vbrandl/dependabot/cargo/tracing-subscriber-0.2.15
Bump tracing-subscriber from 0.2.14 to 0.2.15
2020-11-23 11:56:47 +01:00
bcdf7db549 Merge pull request #189 from vbrandl/dependabot/cargo/actix-web-3.2.0
Bump actix-web from 3.1.0 to 3.2.0
2020-11-23 11:56:24 +01:00
9b2f1f4ebb Bump ructe from 0.12.0 to 0.13.0
Bumps [ructe](https://github.com/kaj/ructe) from 0.12.0 to 0.13.0.
- [Release notes](https://github.com/kaj/ructe/releases)
- [Changelog](https://github.com/kaj/ructe/blob/master/CHANGELOG.md)
- [Commits](https://github.com/kaj/ructe/compare/v0.12.0...v0.13.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-11-16 04:19:05 +00:00
84e47237de Bump tracing-subscriber from 0.2.14 to 0.2.15
Bumps [tracing-subscriber](https://github.com/tokio-rs/tracing) from 0.2.14 to 0.2.15.
- [Release notes](https://github.com/tokio-rs/tracing/releases)
- [Commits](https://github.com/tokio-rs/tracing/compare/tracing-subscriber-0.2.14...tracing-subscriber-0.2.15)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-11-03 04:18:03 +00:00
909f6585b5 Always return a SVG badge
All checks were successful
continuous-integration/drone/push Build is passing
2020-11-01 13:57:56 +01:00
b48d7f1492 Bump actix-web from 3.1.0 to 3.2.0
Bumps [actix-web](https://github.com/actix/actix-web) from 3.1.0 to 3.2.0.
- [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-v3.1.0...web-v3.2.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-10-30 20:02:12 +00:00
f1e9d1806f Bump version (v0.14.4)
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/tag Build is passing
2020-10-30 21:01:37 +01:00
8c62d01f3c Merge pull request #191 from vbrandl/feature/tracing
Use `tracing` instead of `slog` for better ergonomics
2020-10-30 21:00:46 +01:00
26a5025a32 Fix state in test
All checks were successful
continuous-integration/drone/push Build is passing
2020-10-30 17:15:09 +01:00
6f931ce46f Use tracing instead of slog for better ergonomics
All checks were successful
continuous-integration/drone/push Build is passing
2020-10-30 16:40:35 +01:00
2d46592c4a Merge pull request #190 from vbrandl/feature/structured-logging
Feature/structured logging
2020-10-30 13:24:45 +01:00
c2d496f2b4 Add logger to test state
All checks were successful
continuous-integration/drone/push Build is passing
2020-10-30 13:20:24 +01:00
19d37806f2 Remove unused import
All checks were successful
continuous-integration/drone/push Build is passing
2020-10-30 13:11:05 +01:00
b4bd9b8830 Refactor to use slog for structured logging
All checks were successful
continuous-integration/drone/push Build is passing
2020-10-30 13:03:06 +01:00
3c8227d0e9 Add slog dependencies 2020-10-30 13:02:53 +01:00
d6409c21ec Bump version (v0.14.3)
All checks were successful
continuous-integration/drone/tag Build is passing
2020-10-28 09:08:30 +01:00
990b5acbda Merge pull request #184 from vbrandl/dependabot/cargo/git2-0.13.12
Bump git2 from 0.13.11 to 0.13.12
2020-10-28 09:07:35 +01:00
f9e14e2ffd Bump git2 from 0.13.11 to 0.13.12
Bumps [git2](https://github.com/rust-lang/git2-rs) from 0.13.11 to 0.13.12.
- [Release notes](https://github.com/rust-lang/git2-rs/releases)
- [Commits](https://github.com/rust-lang/git2-rs/compare/0.13.11...0.13.12)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-10-28 08:05:44 +00:00
a73afe6851 Merge pull request #186 from vbrandl/dependabot/cargo/bytes-0.6.0
Bump bytes from 0.5.6 to 0.6.0
2020-10-28 09:04:22 +01:00
20544b27d9 Bump bytes from 0.5.6 to 0.6.0
Bumps [bytes](https://github.com/tokio-rs/bytes) from 0.5.6 to 0.6.0.
- [Release notes](https://github.com/tokio-rs/bytes/releases)
- [Changelog](https://github.com/tokio-rs/bytes/blob/master/CHANGELOG.md)
- [Commits](https://github.com/tokio-rs/bytes/compare/v0.5.6...v0.6.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-10-27 09:32:39 +00:00
288573b1a4 Merge pull request #178 from vbrandl/dependabot/cargo/actix-web-3.1.0
Bump actix-web from 3.0.2 to 3.1.0
2020-10-27 10:31:01 +01:00
a12755d7be Merge pull request #182 from vbrandl/dependabot/cargo/structopt-0.3.20
Bump structopt from 0.3.17 to 0.3.20
2020-10-27 09:10:24 +01:00
a248531ce2 Bump actix-web from 3.0.2 to 3.1.0
Bumps [actix-web](https://github.com/actix/actix-web) from 3.0.2 to 3.1.0.
- [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-v3.0.2...web-v3.1.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-10-27 08:07:18 +00:00
de7919a031 Bump structopt from 0.3.17 to 0.3.20
Bumps [structopt](https://github.com/TeXitoi/structopt) from 0.3.17 to 0.3.20.
- [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.3.17...v0.3.20)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-10-27 08:07:15 +00:00
3913039010 Merge pull request #183 from vbrandl/dependabot/cargo/serde_json-1.0.59
Bump serde_json from 1.0.57 to 1.0.59
2020-10-27 09:05:57 +01:00
078d3cdcf9 Merge pull request #185 from vbrandl/dependabot/cargo/serde-1.0.117
Bump serde from 1.0.116 to 1.0.117
2020-10-27 09:05:49 +01:00
c552a84870 Merge pull request #188 from vbrandl/dependabot/cargo/futures-0.3.7
Bump futures from 0.3.5 to 0.3.7
2020-10-27 09:05:37 +01:00
7c1a14b6ad Bump futures from 0.3.5 to 0.3.7
Bumps [futures](https://github.com/rust-lang/futures-rs) from 0.3.5 to 0.3.7.
- [Release notes](https://github.com/rust-lang/futures-rs/releases)
- [Changelog](https://github.com/rust-lang/futures-rs/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/futures-rs/compare/0.3.5...0.3.7)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-10-26 04:17:33 +00:00
c69b8207b8 Bump serde from 1.0.116 to 1.0.117
Bumps [serde](https://github.com/serde-rs/serde) from 1.0.116 to 1.0.117.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.116...v1.0.117)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-10-16 04:22:26 +00:00
a319f400e9 Bump serde_json from 1.0.57 to 1.0.59
Bumps [serde_json](https://github.com/serde-rs/json) from 1.0.57 to 1.0.59.
- [Release notes](https://github.com/serde-rs/json/releases)
- [Commits](https://github.com/serde-rs/json/compare/v1.0.57...v1.0.59)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-10-13 04:19:16 +00:00
ddcb041f3f Bump version
All checks were successful
continuous-integration/drone/tag Build is passing
continuous-integration/drone/push Build is passing
2020-09-19 14:23:21 +02:00
2a73370c9f Use normalize path middleware 2020-09-19 14:22:56 +02:00
689a2109fa Merge pull request #175 from vbrandl/dependabot/cargo/actix-web-3.0.2
Bump actix-web from 3.0.0 to 3.0.2
2020-09-19 14:16:00 +02:00
e82146c912 Merge pull request #174 from vbrandl/dependabot/cargo/serde-1.0.116
Bump serde from 1.0.115 to 1.0.116
2020-09-19 14:15:51 +02:00
568398f1c6 Bump actix-web from 3.0.0 to 3.0.2
Bumps [actix-web](https://github.com/actix/actix-web) from 3.0.0 to 3.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-v3.0.0...web-v3.0.2)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-09-16 04:18:46 +00:00
1cc6363cba Bump serde from 1.0.115 to 1.0.116
Bumps [serde](https://github.com/serde-rs/serde) from 1.0.115 to 1.0.116.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.115...v1.0.116)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-09-14 04:18:28 +00:00
13 changed files with 686 additions and 569 deletions

View File

@ -4,27 +4,24 @@ on:
- cron: '0 1 * * *'
push:
paths:
- 'Cargo.toml'
- 'Cargo.lock'
- '**/Cargo.toml'
- '**/Cargo.lock'
pull_request:
jobs:
security_audit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- uses: actions/checkout@v2
- name: Cache cargo registry
uses: actions/cache@v1
- name: Cache cargo registry, index and build directory
uses: actions/cache@v2
with:
path: /usr/share/rust/.cargo/registry
key: ${{ runner.os }}-cargo-registry
- name: Cache cargo index
uses: actions/cache@v1
with:
path: /usr/share/rust/.cargo/git
key: ${{ runner.os }}-cargo-index
path: |
~/.cargo/registry
~/.cargo/git
./target
key: audit-${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
- uses: actions-rs/audit-check@v1
with:

View File

@ -1,20 +0,0 @@
name: "Nix Build"
on: [push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: cachix/install-nix-action@v8
- name: Cache nix store
uses: actions/cache@v1
with:
path: /nix
key: ${{ runner.os }}-nix-store
- uses: cachix/cachix-action@v5
with:
name: hitsofcode
signingKey: '${{ secrets.CACHIX_SIGNING_KEY }}'
attributes: package

76
.github/workflows/release.yml vendored Normal file
View File

@ -0,0 +1,76 @@
name: Release
on:
push:
tags:
- 'v[0-9]+.[0-9]+.[0-9]+'
jobs:
publish:
name: Publishing for ${{ matrix.os }}
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [macos-latest, ubuntu-latest, windows-latest]
rust: [stable]
include:
- os: macos-latest
artifact_prefix: macos
target: x86_64-apple-darwin
binary_postfix: ""
- os: ubuntu-latest
artifact_prefix: linux
target: x86_64-unknown-linux-gnu
binary_postfix: ""
- os: windows-latest
artifact_prefix: windows
target: x86_64-pc-windows-msvc
binary_postfix: ".exe"
steps:
- name: Checkout sources
uses: actions/checkout@v2
- name: Install stable toolchain
uses: actions-rs/toolchain@v1
with:
toolchain: ${{ matrix.rust }}
override: true
- name: Cache cargo registry, index and build directory
uses: actions/cache@v2
with:
path: |
~/.cargo/registry
~/.cargo/git
./target
key: release-${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
- name: Cargo build
uses: actions-rs/cargo@v1
with:
command: build
toolchain: ${{ matrix.rust }}
args: --release --target ${{ matrix.target }}
- name: Packaging final binary
shell: bash
run: |
cd target/${{ matrix.target }}/release
strip hoc${{ matrix.binary_postfix }}
tar czvf hoc-${{ matrix.artifact_prefix }}.tar.gz hoc${{ matrix.binary_postfix }}
if [[ ${{ runner.os }} == 'Windows' ]]; then
certutil -hashfile hoc-${{ matrix.artifact_prefix }}.tar.gz sha256 | grep -E [A-Fa-f0-9]{64} > hoc-${{ matrix.artifact_prefix }}.sha256
else
shasum -a 256 hoc-${{ matrix.artifact_prefix }}.tar.gz > hoc-${{ matrix.artifact_prefix }}.sha256
fi
- name: Releasing assets
uses: softprops/action-gh-release@v1
with:
files: |
target/${{ matrix.target }}/release/hoc-${{ matrix.artifact_prefix }}.tar.gz
target/${{ matrix.target }}/release/hoc-${{ matrix.artifact_prefix }}.sha256
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@ -1,41 +1,30 @@
name: Rust
on: [push, pull_request]
jobs:
lint:
name: Linting and Formatting Checks
rustfmt:
name: Rustfmt
runs-on: ubuntu-latest
steps:
- name: Checkout sources
uses: actions/checkout@v1
uses: actions/checkout@v2
- name: Install stable toolchain
uses: actions-rs/toolchain@v1
with:
toolchain: stable
profile: minimal
override: true
components: rustfmt
- name: Install rustfmt
run: rustup component add rustfmt
- name: Cache cargo registry
uses: actions/cache@v1
- name: Cache cargo registry, index and build directory
uses: actions/cache@v2
with:
path: ~/.cargo/registry
key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }}
- name: Cache cargo index
uses: actions/cache@v1
with:
path: ~/.cargo/git
key: ${{ runner.os }}-cargo-index-${{ hashFiles('**/Cargo.lock') }}
- name: Cache cargo build
uses: actions/cache@v1
with:
path: target
key: ${{ runner.os }}-cargo-build-target-${{ hashFiles('**/Cargo.lock') }}
path: |
~/.cargo/registry
~/.cargo/git
./target
key: rustfmt-${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
- name: Check Formatting
uses: actions-rs/cargo@v1
@ -43,8 +32,29 @@ jobs:
command: fmt
args: --all -- --check
- name: Install clippy
run: rustup component add clippy
clippy:
name: Clippy
runs-on: ubuntu-latest
steps:
- name: Checkout sources
uses: actions/checkout@v2
- name: Install stable toolchain
uses: actions-rs/toolchain@v1
with:
toolchain: stable
profile: minimal
override: true
components: rustfmt
- name: Cache cargo registry, index and build directory
uses: actions/cache@v2
with:
path: |
~/.cargo/registry
~/.cargo/git
./target
key: clippy-${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
- name: Clippy Linting
uses: actions-rs/cargo@v1
@ -52,8 +62,9 @@ jobs:
command: clippy
args: -- -D warnings
test:
name: Run Tests
name: Test Suite
runs-on: ${{ matrix.os }}
strategy:
matrix:
@ -62,31 +73,23 @@ jobs:
steps:
- name: Checkout sources
uses: actions/checkout@v1
uses: actions/checkout@v2
- name: Install stable toolchain
uses: actions-rs/toolchain@v1
with:
toolchain: stable
profile: minimal
override: true
- name: Cache cargo registry
uses: actions/cache@v1
- name: Cache cargo registry, index and build directory
uses: actions/cache@v2
with:
path: ~/.cargo/registry
key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }}
- name: Cache cargo index
uses: actions/cache@v1
with:
path: ~/.cargo/git
key: ${{ runner.os }}-cargo-index-${{ hashFiles('**/Cargo.lock') }}
- name: Cache cargo build
uses: actions/cache@v1
with:
path: target
key: ${{ runner.os }}-cargo-build-target-${{ hashFiles('**/Cargo.lock') }}
path: |
~/.cargo/registry
~/.cargo/git
./target
key: test-${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
- name: Run Tests
uses: actions-rs/cargo@v1

View File

@ -1,17 +0,0 @@
language: rust
rust:
- stable
- beta
- nightly
cache:
- cargo
matrix:
allow_failures:
- rust: nightly
notifications:
email:
on_failure: always

713
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,30 +1,32 @@
[package]
name = "hoc"
version = "0.14.1"
version = "0.14.5"
authors = ["Valentin Brandl <vbrandl@riseup.net>"]
edition = "2018"
build = "build.rs"
[dependencies]
actix-web = "3.0.0"
actix-rt = "1.1.1"
actix-web = "3.2.0"
badge = "0.3.0"
bytes = "0.5.6"
futures = "0.3.5"
git2 = "0.13.11"
bytes = "0.6.0"
futures = "0.3.8"
git2 = "0.13.12"
lazy_static = "1.4.0"
log = "0.4.11"
log4rs = "0.13.0"
number_prefix = "0.4.0"
openssl-probe = "0.1.2"
reqwest = "0.10.8"
serde = "1.0.115"
reqwest = "0.10.9"
serde = "1.0.117"
serde_derive = "1.0.103"
serde_json = "1.0.57"
structopt = "0.3.17"
actix-rt = "1.1.1"
serde_json = "1.0.59"
structopt = "0.3.20"
tracing = "0.1.21"
tracing-subscriber = "0.2.15"
tracing-actix-web = "0.2.1"
tracing-futures = "0.2.4"
[build-dependencies]
ructe = "0.12.0"
ructe = "0.13.0"
vergen = "3.1.0"
[dev-dependencies]

View File

@ -3,7 +3,6 @@
[![Hits-of-Code](https://hitsofcode.com/github/vbrandl/hoc)](https://hitsofcode.com/view/github/vbrandl/hoc)
[![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

View File

@ -8,6 +8,7 @@ use std::{
};
/// Enum to indicate the state of the cache
#[derive(Debug)]
pub(crate) enum CacheState<'a> {
/// Current head and cached head are the same
Current {
@ -26,11 +27,13 @@ pub(crate) enum CacheState<'a> {
}
impl<'a> CacheState<'a> {
#[instrument]
pub(crate) fn read_from_file(
path: impl AsRef<Path>,
path: impl AsRef<Path> + std::fmt::Debug,
branch: &str,
head: &str,
) -> Result<CacheState<'a>> {
trace!("Reading cache");
if path.as_ref().exists() {
let cache: Cache = serde_json::from_reader(BufReader::new(File::open(path)?))?;
Ok(cache
@ -38,6 +41,7 @@ impl<'a> CacheState<'a> {
.get(branch)
.map(|c| {
if c.head == head {
trace!("Cache is up to date");
CacheState::Current {
count: c.count,
commits: c.commits,
@ -45,6 +49,7 @@ impl<'a> CacheState<'a> {
cache: cache.clone(),
}
} else {
trace!("Cache is out of date");
CacheState::Old {
head: c.head.to_string(),
// TODO: get rid of clone
@ -59,6 +64,7 @@ impl<'a> CacheState<'a> {
}
}
#[instrument]
pub(crate) fn calculate_new_cache(
self,
count: u64,
@ -66,6 +72,7 @@ impl<'a> CacheState<'a> {
head: Cow<'a, str>,
branch: &'a str,
) -> Cache<'a> {
trace!("Calculating new cache");
match self {
CacheState::Old { mut cache, .. } => {
if let Some(mut cache) = cache.entries.get_mut(branch) {
@ -77,6 +84,7 @@ impl<'a> CacheState<'a> {
}
CacheState::Current { cache, .. } => cache,
CacheState::NoneForBranch(mut cache) => {
trace!("Creating new cache for branch");
cache.entries.insert(
branch.into(),
CacheEntry {
@ -88,6 +96,7 @@ impl<'a> CacheState<'a> {
cache
}
CacheState::No => {
trace!("Creating new cache file");
let mut entries = HashMap::with_capacity(1);
entries.insert(
branch.into(),
@ -103,12 +112,12 @@ impl<'a> CacheState<'a> {
}
}
#[derive(Serialize, Deserialize, Clone)]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub(crate) struct Cache<'a> {
pub entries: HashMap<Cow<'a, str>, CacheEntry<'a>>,
}
#[derive(Serialize, Deserialize, Clone)]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub(crate) struct CacheEntry<'a> {
/// HEAD commit ref
pub head: Cow<'a, str>,
@ -119,7 +128,9 @@ pub(crate) struct CacheEntry<'a> {
}
impl<'a> Cache<'a> {
pub(crate) fn write_to_file(&self, path: impl AsRef<Path>) -> Result<()> {
#[instrument]
pub(crate) fn write_to_file(&self, path: impl AsRef<Path> + std::fmt::Debug) -> Result<()> {
trace!("Persisting cache to disk");
create_dir_all(path.as_ref().parent().ok_or(Error::Internal)?)?;
serde_json::to_writer(
OpenOptions::new()

View File

@ -1,10 +1,3 @@
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;
@ -38,33 +31,11 @@ pub(crate) struct Opt {
#[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) async fn init() -> Result<()> {
pub(crate) fn init() {
std::env::set_var("RUST_LOG", "actix_web=info,hoc=info");
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(())
tracing_subscriber::fmt().init();
}

View File

@ -1,10 +1,12 @@
use crate::error::Result;
use std::{fs::read_dir, path::Path, result::Result as StdResult};
#[instrument]
pub(crate) fn count_repositories<P>(repo_path: P) -> Result<usize>
where
P: AsRef<Path>,
P: AsRef<Path> + std::fmt::Debug,
{
trace!("Counting repositories");
std::fs::create_dir_all(&repo_path)?;
Ok(read_dir(repo_path)?
.filter_map(StdResult::ok)

View File

@ -14,8 +14,6 @@ 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),
BranchNotFound,
@ -29,8 +27,6 @@ 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),
Error::BranchNotFound => write!(fmt, "Repo doesn't have master branch"),
@ -76,12 +72,6 @@ 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)
@ -100,12 +90,6 @@ impl From<reqwest::Error> for Error {
}
}
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

@ -5,9 +5,9 @@ extern crate actix_web;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate tracing;
mod cache;
mod config;
@ -29,7 +29,8 @@ use crate::{
};
use actix_web::{
http::header::{CacheControl, CacheDirective, Expires, LOCATION},
middleware, web, App, HttpResponse, HttpServer, Responder,
middleware::{self, normalize::TrailingSlash},
web, App, HttpResponse, HttpServer, Responder,
};
use badge::{Badge, BadgeOptions};
use git2::{BranchType, Repository};
@ -44,6 +45,7 @@ use std::{
sync::Arc,
time::{Duration, SystemTime},
};
use tracing::Instrument;
include!(concat!(env!("OUT_DIR"), "/templates.rs"));
@ -107,16 +109,16 @@ fn hoc(repo: &str, repo_dir: &str, cache_dir: &str, branch: &str) -> Result<(u64
let cache = CacheState::read_from_file(&cache_dir, branch, &head)?;
match &cache {
CacheState::Current { count, commits, .. } => {
info!("Using cache for {}", repo_dir);
info!("Using cache");
return Ok((*count, head, *commits));
}
CacheState::Old { head, .. } => {
info!("Updating cache for {}", repo_dir);
info!("Updating cache");
arg.push(format!("{}..{}", head, branch));
arg_commit_count.push(format!("{}..{}", head, branch));
}
CacheState::No | CacheState::NoneForBranch(..) => {
info!("Creating cache for {}", repo_dir);
info!("Creating cache");
arg.push(branch.to_string());
arg_commit_count.push(branch.to_string());
}
@ -124,7 +126,7 @@ fn hoc(repo: &str, repo_dir: &str, cache_dir: &str, branch: &str) -> Result<(u64
arg.push("--".to_string());
arg.push(".".to_string());
let output = Command::new("git")
.args(&dbg!(arg))
.args(&arg)
.current_dir(&repo_dir)
.output()?
.stdout;
@ -179,36 +181,45 @@ where
T: Service,
{
let data = data.into_inner();
let repo = format!(
"{}/{}/{}",
T::domain(),
data.0.to_lowercase(),
data.1.to_lowercase()
let span = info_span!(
"deleting repository and cache",
service = T::domain(),
user = data.0.as_str(),
repo = data.1.as_str()
);
info!("Deleting cache and repository for {}", repo);
let cache_dir = dbg!(format!("{}/{}.json", &state.cache, repo));
let repo_dir = dbg!(format!("{}/{}", &state.repos, repo));
std::fs::remove_file(&cache_dir).or_else(|e| {
if e.kind() == io::ErrorKind::NotFound {
Ok(())
} else {
Err(e)
}
})?;
std::fs::remove_dir_all(&repo_dir).or_else(|e| {
if e.kind() == io::ErrorKind::NotFound {
Ok(())
} else {
Err(e)
}
})?;
REPO_COUNT.fetch_sub(1, Ordering::Relaxed);
Ok(HttpResponse::TemporaryRedirect()
.header(
LOCATION,
format!("/view/{}/{}/{}", T::url_path(), data.0, data.1),
)
.finish())
let future = async {
let repo = format!(
"{}/{}/{}",
T::domain(),
data.0.to_lowercase(),
data.1.to_lowercase()
);
info!("Deleting cache and repository");
let cache_dir = format!("{}/{}.json", &state.cache, repo);
let repo_dir = format!("{}/{}", &state.repos, repo);
std::fs::remove_file(&cache_dir).or_else(|e| {
if e.kind() == io::ErrorKind::NotFound {
Ok(())
} else {
Err(e)
}
})?;
std::fs::remove_dir_all(&repo_dir).or_else(|e| {
if e.kind() == io::ErrorKind::NotFound {
Ok(())
} else {
Err(e)
}
})?;
REPO_COUNT.fetch_sub(1, Ordering::Relaxed);
Ok(HttpResponse::TemporaryRedirect()
.header(
LOCATION,
format!("/view/{}/{}/{}", T::url_path(), data.0, data.1),
)
.finish())
};
future.instrument(span).await
}
async fn handle_hoc_request<T, F>(
@ -222,41 +233,51 @@ where
F: Fn(HocResult) -> Result<HttpResponse>,
{
let data = data.into_inner();
let repo = format!("{}/{}", data.0.to_lowercase(), data.1.to_lowercase());
let service_path = format!("{}/{}", T::url_path(), repo);
let service_url = format!("{}/{}", T::domain(), repo);
let path = format!("{}/{}", state.repos, service_url);
let url = format!("https://{}", service_url);
let remote_exists = remote_exists(&url).await?;
let file = Path::new(&path);
if !file.exists() {
if !remote_exists {
warn!("Repository does not exist: {}", url);
return mapper(HocResult::NotFound);
let span = info_span!(
"handling hoc calculation",
service = T::domain(),
user = data.0.as_str(),
repo = data.1.as_str(),
branch
);
let future = async {
let repo = format!("{}/{}", data.0.to_lowercase(), data.1.to_lowercase());
let service_path = format!("{}/{}", T::url_path(), repo);
let service_url = format!("{}/{}", T::domain(), repo);
let path = format!("{}/{}", state.repos, service_url);
let url = format!("https://{}", service_url);
let remote_exists = remote_exists(&url).await?;
let file = Path::new(&path);
if !file.exists() {
if !remote_exists {
warn!("Repository does not exist");
return mapper(HocResult::NotFound);
}
info!("Cloning for the first time");
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);
}
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_url, &state.repos, &state.cache, branch)?;
let hoc_pretty = match NumberPrefix::decimal(hoc as f64) {
NumberPrefix::Standalone(hoc) => hoc.to_string(),
NumberPrefix::Prefixed(prefix, hoc) => format!("{:.1}{}", hoc, prefix),
pull(&path)?;
let (hoc, head, commits) = hoc(&service_url, &state.repos, &state.cache, branch)?;
let hoc_pretty = match NumberPrefix::decimal(hoc as f64) {
NumberPrefix::Standalone(hoc) => hoc.to_string(),
NumberPrefix::Prefixed(prefix, hoc) => format!("{:.1}{}", hoc, prefix),
};
let res = HocResult::Hoc {
hoc,
commits,
hoc_pretty,
head,
url,
repo,
service_path,
};
mapper(res)
};
let res = HocResult::Hoc {
hoc,
commits,
hoc_pretty,
head,
url,
repo,
service_path,
};
mapper(res)
future.instrument(span).await
}
pub(crate) async fn json_hoc<T: Service>(
@ -279,11 +300,25 @@ pub(crate) async fn json_hoc<T: Service>(
handle_hoc_request::<T, _>(state, data, branch, mapper).await
}
fn no_cache_response(body: Vec<u8>) -> HttpResponse {
let expiration = SystemTime::now() + Duration::from_secs(30);
HttpResponse::Ok()
.content_type("image/svg+xml")
.set(Expires(expiration.into()))
.set(CacheControl(vec![
CacheDirective::MaxAge(0u32),
CacheDirective::MustRevalidate,
CacheDirective::NoCache,
CacheDirective::NoStore,
]))
.body(body)
}
pub(crate) async fn calculate_hoc<T: Service>(
state: web::Data<Arc<State>>,
data: web::Path<(String, String)>,
branch: web::Query<BranchQuery>,
) -> Result<HttpResponse> {
) -> HttpResponse {
let mapper = move |r| match r {
HocResult::NotFound => p404(),
HocResult::Hoc { hoc_pretty, .. } => {
@ -296,21 +331,23 @@ pub(crate) async fn calculate_hoc<T: Service>(
// TODO: remove clone
let body = badge.to_svg().as_bytes().to_vec();
let expiration = SystemTime::now() + Duration::from_secs(30);
Ok(HttpResponse::Ok()
.content_type("image/svg+xml")
.set(Expires(expiration.into()))
.set(CacheControl(vec![
CacheDirective::MaxAge(0u32),
CacheDirective::MustRevalidate,
CacheDirective::NoCache,
CacheDirective::NoStore,
]))
.body(body))
Ok(no_cache_response(body))
}
};
let branch = branch.branch.as_deref().unwrap_or("master");
handle_hoc_request::<T, _>(state, data, branch, mapper).await
let error_badge = |_| {
let error_badge = Badge::new(BadgeOptions {
subject: "Hits-of-Code".to_string(),
color: "#ff0000".to_string(),
status: "error".to_string(),
})
.unwrap();
let body = error_badge.to_svg().as_bytes().to_vec();
no_cache_response(body)
};
handle_hoc_request::<T, _>(state, data, branch, mapper)
.await
.unwrap_or_else(error_badge)
}
async fn overview<T: Service>(
@ -411,11 +448,10 @@ async fn start_server() -> std::io::Result<()> {
HttpServer::new(move || {
App::new()
.data(state.clone())
.wrap(middleware::Logger::default())
// .wrap(middleware::NormalizePath::default())
.wrap(tracing_actix_web::TracingLogger)
.wrap(middleware::NormalizePath::new(TrailingSlash::Trim))
.service(index)
.service(web::resource("/tacit-css.min.css").route(web::get().to(css)))
// TODO
.service(web::resource("/favicon.ico").route(web::get().to(favicon32)))
.service(generate)
.service(web::resource("/github/{user}/{repo}").to(calculate_hoc::<GitHub>))
@ -449,6 +485,8 @@ async fn start_server() -> std::io::Result<()> {
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
config::init().await.unwrap();
start_server().await
config::init();
let span = info_span!("hoc", version = env!("CARGO_PKG_VERSION"));
let _ = span.enter();
start_server().instrument(span).await
}