Remove color feature

This commit is contained in:
Valentin Brandl 2019-04-20 15:01:11 +02:00
parent a06e0e3fae
commit d890288640
No known key found for this signature in database
GPG Key ID: 30D341DD34118D7D
3 changed files with 5 additions and 235 deletions

View File

@ -1,147 +0,0 @@
use crate::error::Error;
use std::convert::TryFrom;
pub(crate) trait ToCode {
fn to_code(&self) -> String;
}
#[derive(Debug)]
pub(crate) enum ColorName {
BrightGreen,
Green,
YellowGreen,
Yellow,
Orange,
Red,
Blue,
LightGrey,
Success,
Important,
Critical,
Informational,
Inactive,
}
impl TryFrom<&str> for ColorName {
type Error = Error;
fn try_from(s: &str) -> Result<Self, Self::Error> {
match s.to_lowercase().as_str() {
"brightgreen" => Ok(ColorName::BrightGreen),
"green" => Ok(ColorName::Green),
"yellowgreen" => Ok(ColorName::YellowGreen),
"yellow" => Ok(ColorName::Yellow),
"orange" => Ok(ColorName::Orange),
"red" => Ok(ColorName::Red),
"blue" => Ok(ColorName::Blue),
"lightgrey" => Ok(ColorName::LightGrey),
"success" => Ok(ColorName::Success),
"important" => Ok(ColorName::Important),
"critical" => Ok(ColorName::Critical),
"informational" => Ok(ColorName::Informational),
"inactive" => Ok(ColorName::Inactive),
_ => Err(Error::ParseColor),
}
}
}
impl ToCode for ColorName {
fn to_code(&self) -> String {
use ColorName::*;
match self {
BrightGreen | Success => "#44cc11",
Green => "#97ca00",
YellowGreen => "#a4a61d",
Yellow => "#dfb317",
Orange | Important => "#fe7d37",
Red | Critical => "#e05d44",
Blue | Informational => "#007ec6",
LightGrey | Inactive => "#9f9f9f",
}
.to_string()
}
}
#[derive(Debug)]
pub(crate) struct ColorCode(String);
impl TryFrom<&str> for ColorCode {
type Error = Error;
fn try_from(s: &str) -> Result<Self, Self::Error> {
let s = if s.starts_with('#') { &s[1..] } else { s };
let len = s.len();
if (len == 3 || len == 6) && s.chars().all(|c| c.is_digit(16)) {
Ok(ColorCode(s.to_lowercase().to_string()))
} else {
Err(Error::ParseColor)
}
}
}
impl ToCode for ColorCode {
fn to_code(&self) -> String {
format!("#{}", self.0)
}
}
#[derive(Debug)]
pub(crate) enum ColorKind {
Name(ColorName),
Code(ColorCode),
}
impl TryFrom<&str> for ColorKind {
type Error = Error;
fn try_from(s: &str) -> Result<Self, Self::Error> {
ColorName::try_from(s)
.map(|c| ColorKind::Name(c))
.or_else(|_| ColorCode::try_from(s).map(|c| ColorKind::Code(c)))
}
}
impl ToCode for ColorKind {
fn to_code(&self) -> String {
match self {
ColorKind::Name(name) => name.to_code(),
ColorKind::Code(code) => code.to_code(),
}
}
}
impl Default for ColorKind {
fn default() -> Self {
ColorKind::Name(ColorName::Success)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn parse_colorcode() {
let valid_long = "aaBB11";
let valid_short = "aB1";
let pound_valid_long: &str = &format!("#{}", valid_long);
let pound_valid_short: &str = &format!("#{}", valid_short);
let valid_long = ColorCode::try_from(valid_long);
let valid_short = ColorCode::try_from(valid_short);
let pound_valid_long = ColorCode::try_from(pound_valid_long);
let pound_valid_short = ColorCode::try_from(pound_valid_short);
let too_short = "ab";
let too_long = "aaaaaab";
let non_hex = "aag";
let too_short = ColorCode::try_from(too_short);
let too_long = ColorCode::try_from(too_long);
let non_hex = ColorCode::try_from(non_hex);
assert_eq!(&valid_long.unwrap().to_code(), "#aabb11");
assert_eq!(&valid_short.unwrap().to_code(), "#ab1");
assert_eq!(&pound_valid_long.unwrap().to_code(), "#aabb11");
assert_eq!(&pound_valid_short.unwrap().to_code(), "#ab1");
assert!(too_short.is_err());
assert!(too_long.is_err());
assert!(non_hex.is_err());
}
}

View File

@ -5,14 +5,9 @@ extern crate serde_json;
extern crate serde_derive; extern crate serde_derive;
mod cache; mod cache;
mod color;
mod error; mod error;
use crate::{ use crate::{cache::CacheState, error::Error};
cache::CacheState,
color::{ColorKind, ToCode},
error::Error,
};
use actix_web::{ use actix_web::{
error::ErrorBadRequest, error::ErrorBadRequest,
http::{ http::{
@ -26,7 +21,6 @@ use bytes::Bytes;
use futures::{unsync::mpsc, Stream}; use futures::{unsync::mpsc, Stream};
use git2::Repository; use git2::Repository;
use std::{ use std::{
convert::TryFrom,
fs::create_dir_all, fs::create_dir_all,
path::{Path, PathBuf}, path::{Path, PathBuf},
process::Command, process::Command,
@ -69,11 +63,6 @@ struct Opt {
host: String, host: String,
} }
#[derive(Debug, Deserialize)]
struct BadgeQuery {
color: Option<String>,
}
fn pull(path: impl AsRef<Path>) -> Result<(), Error> { fn pull(path: impl AsRef<Path>) -> Result<(), Error> {
let repo = Repository::open_bare(path)?; let repo = Repository::open_bare(path)?;
let mut origin = repo.find_remote("origin")?; let mut origin = repo.find_remote("origin")?;
@ -141,7 +130,6 @@ fn calculate_hoc(
service: &str, service: &str,
state: web::Data<Arc<State>>, state: web::Data<Arc<State>>,
data: web::Path<(String, String)>, data: web::Path<(String, String)>,
color: web::Query<BadgeQuery>,
) -> Result<HttpResponse, Error> { ) -> Result<HttpResponse, Error> {
let service_path = format!("{}/{}/{}", service, data.0, data.1); let service_path = format!("{}/{}/{}", service, data.0, data.1);
let path = format!("{}/{}", state.repos, service_path); let path = format!("{}/{}", state.repos, service_path);
@ -154,15 +142,9 @@ fn calculate_hoc(
} }
pull(&path)?; pull(&path)?;
let hoc = hoc(&service_path, &state.repos, &state.cache)?; let hoc = hoc(&service_path, &state.repos, &state.cache)?;
let color = color
.into_inner()
.color
.map(|s| ColorKind::try_from(s.as_str()))
.and_then(Result::ok)
.unwrap_or_default();
let badge_opt = BadgeOptions { let badge_opt = BadgeOptions {
subject: "Hits-of-Code".to_string(), subject: "Hits-of-Code".to_string(),
color: color.to_code(), color: "#007ec6".to_string(),
status: hoc.to_string(), status: hoc.to_string(),
}; };
let badge = Badge::new(badge_opt)?; let badge = Badge::new(badge_opt)?;
@ -186,53 +168,22 @@ fn calculate_hoc(
fn github( fn github(
state: web::Data<Arc<State>>, state: web::Data<Arc<State>>,
data: web::Path<(String, String)>, data: web::Path<(String, String)>,
color: web::Query<BadgeQuery>,
) -> Result<HttpResponse, Error> { ) -> Result<HttpResponse, Error> {
calculate_hoc("github.com", state, data, color) calculate_hoc("github.com", state, data)
} }
fn gitlab( fn gitlab(
state: web::Data<Arc<State>>, state: web::Data<Arc<State>>,
data: web::Path<(String, String)>, data: web::Path<(String, String)>,
color: web::Query<BadgeQuery>,
) -> Result<HttpResponse, Error> { ) -> Result<HttpResponse, Error> {
calculate_hoc("gitlab.com", state, data, color) calculate_hoc("gitlab.com", state, data)
} }
fn bitbucket( fn bitbucket(
state: web::Data<Arc<State>>, state: web::Data<Arc<State>>,
data: web::Path<(String, String)>, data: web::Path<(String, String)>,
color: web::Query<BadgeQuery>,
) -> Result<HttpResponse, Error> { ) -> Result<HttpResponse, Error> {
calculate_hoc("bitbucket.org", state, data, color) calculate_hoc("bitbucket.org", state, data)
}
#[get("/badge")]
fn badge_example(col: web::Query<BadgeQuery>) -> Result<HttpResponse, Error> {
let col = col.into_inner();
let color = col
.color
.clone()
.map(|s| ColorKind::try_from(s.as_str()))
.transpose()?
// .and_then(Result::ok)
.unwrap_or_default();
let badge_opt = BadgeOptions {
subject: "Hits-of-Code".to_string(),
color: color.to_code(),
status: col.color.unwrap_or_else(|| "success".to_string()),
};
let badge = Badge::new(badge_opt)?;
let (tx, rx_body) = mpsc::unbounded();
let _ = tx.unbounded_send(Bytes::from(badge.to_svg().as_bytes()));
let expiration = SystemTime::now() + Duration::from_secs(60 * 60 * 24 * 365);
Ok(HttpResponse::Ok()
.content_type("image/svg+xml")
.set(Expires(expiration.into()))
.set(CacheControl(vec![CacheDirective::Public]))
.streaming(rx_body.map_err(|_| ErrorBadRequest("bad request"))))
} }
fn overview(_: web::Path<(String, String)>) -> HttpResponse { fn overview(_: web::Path<(String, String)>) -> HttpResponse {
@ -277,7 +228,6 @@ fn main() -> std::io::Result<()> {
.wrap(middleware::Logger::default()) .wrap(middleware::Logger::default())
.service(index) .service(index)
.service(css) .service(css)
.service(badge_example)
.service(web::resource("/github/{user}/{repo}").to(github)) .service(web::resource("/github/{user}/{repo}").to(github))
.service(web::resource("/gitlab/{user}/{repo}").to(gitlab)) .service(web::resource("/gitlab/{user}/{repo}").to(gitlab))
.service(web::resource("/bitbucket/{user}/{repo}").to(bitbucket)) .service(web::resource("/bitbucket/{user}/{repo}").to(bitbucket))

View File

@ -56,39 +56,6 @@ would render this badge:
alt="example badge" /></a> alt="example badge" /></a>
</pre> </pre>
<h2>Colors</h2>
<p>
You can generate badges with custom colors via the <code>color</code> query parameter. The following predefined colors
are supported:
</p>
<pre>
<img src="/badge?color=brightgreen" alt="brightgreen example badge" />
<img src="/badge?color=green" alt="green example badge" />
<img src="/badge?color=yellowgreen" alt="yellowgreen example badge" />
<img src="/badge?color=yellow" alt="yellow example badge" />
<img src="/badge?color=orange" alt="orange example badge" />
<img src="/badge?color=red" alt="red example badge" />
<img src="/badge?color=blue" alt="blue example badge" />
<img src="/badge?color=lightgrey" alt="lightgrey example badge" />
<img src="/badge?color=success" alt="success example badge" />
<img src="/badge?color=important" alt="important example badge" />
<img src="/badge?color=critical" alt="critical example badge" />
<img src="/badge?color=informational" alt="informational example badge" />
<img src="/badge?color=inactive" alt="inactive example badge" />
</pre>
<p>
You can also pass HTML color codes:
</p>
<pre>
<img src="/badge?color=ff69b4" alt="long HTML color code example badge" /> <img src="/badge?color=9cf" alt="short HTML
color code example badge" />
</pre>
<h2>Source Code</h2> <h2>Source Code</h2>
<p> <p>