Skip to content

Implement GET /crates/:crate_id/maintenance.svg endpoint #2439

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ rustdoc-args = [
[dependencies]
ammonia = "3.0.0"
anyhow = "1.0"
badge = "0.3.0"
base64 = "0.13"
cargo-registry-s3 = { path = "src/s3", version = "0.2.0" }
chrono = { version = "0.4.0", features = ["serde"] }
Expand Down
1 change: 1 addition & 0 deletions src/controllers/krate.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod badges;
pub mod downloads;
pub mod follow;
pub mod metadata;
Expand Down
77 changes: 77 additions & 0 deletions src/controllers/krate/badges.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
//! Endpoints that provide badges based on crate metadata

use crate::controllers::frontend_prelude::*;

use crate::models::{Badge, Crate, CrateBadge, MaintenanceStatus};
use crate::schema::*;

use conduit::{Body, Response};

/// Handles the `GET /crates/:crate_id/maintenance.svg` route.
pub fn maintenance(req: &mut dyn RequestExt) -> EndpointResult {
let name = &req.params()["crate_id"];
let conn = req.db_read_only()?;

let krate = Crate::by_name(name).first::<Crate>(&*conn);
if krate.is_err() {
let response = Response::builder().status(404).body(Body::empty()).unwrap();

return Ok(response);
}

let krate = krate.unwrap();

let maintenance_badge: Option<CrateBadge> = CrateBadge::belonging_to(&krate)
.select((badges::crate_id, badges::all_columns))
.load::<CrateBadge>(&*conn)?
.into_iter()
.find(|cb| matches!(cb.badge, Badge::Maintenance { .. }));

let status = maintenance_badge
.map(|it| match it.badge {
Badge::Maintenance { status } => Some(status),
_ => None,
})
.flatten();

let badge = generate_badge(status);

let response = Response::builder()
.status(200)
.body(Body::from_vec(badge.into_bytes()))
.unwrap();

Ok(response)
}

fn generate_badge(status: Option<MaintenanceStatus>) -> String {
let message = match status {
Some(MaintenanceStatus::ActivelyDeveloped) => "actively-developed",
Some(MaintenanceStatus::PassivelyMaintained) => "passively-maintained",
Some(MaintenanceStatus::AsIs) => "as-is",
Some(MaintenanceStatus::None) => "unknown",
Some(MaintenanceStatus::Experimental) => "experimental",
Some(MaintenanceStatus::LookingForMaintainer) => "looking-for-maintainer",
Some(MaintenanceStatus::Deprecated) => "deprecated",
None => "unknown",
};

let color = match status {
Some(MaintenanceStatus::ActivelyDeveloped) => "brightgreen",
Some(MaintenanceStatus::PassivelyMaintained) => "yellowgreen",
Some(MaintenanceStatus::AsIs) => "yellow",
Some(MaintenanceStatus::None) => "lightgrey",
Some(MaintenanceStatus::Experimental) => "blue",
Some(MaintenanceStatus::LookingForMaintainer) => "orange",
Some(MaintenanceStatus::Deprecated) => "red",
None => "lightgrey",
};

let badge_options = badge::BadgeOptions {
subject: "maintenance".to_owned(),
status: message.to_owned(),
color: color.to_string(),
};

badge::Badge::new(badge_options).unwrap().to_svg()
}
4 changes: 4 additions & 0 deletions src/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,10 @@ pub fn build_router(app: &App) -> R404 {
"/crates/:crate_id/reverse_dependencies",
C(krate::metadata::reverse_dependencies),
);
api_router.get(
"/crates/:crate_id/maintenance.svg",
C(krate::badges::maintenance),
);
api_router.get("/keywords", C(keyword::index));
api_router.get("/keywords/:keyword_id", C(keyword::show));
api_router.get("/categories", C(category::index));
Expand Down
17 changes: 11 additions & 6 deletions src/tests/all.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ mod dump_db;
mod git;
mod keyword;
mod krate;
mod maintenance_badge;
mod owners;
mod read_only_mode;
mod record;
Expand Down Expand Up @@ -197,10 +198,7 @@ fn bad_resp(r: &mut AppResponse) -> Option<Bad> {
Some(bad)
}

fn json<T>(r: &mut AppResponse) -> T
where
for<'de> T: serde::Deserialize<'de>,
{
fn text(r: &mut AppResponse) -> String {
use conduit::Body::*;

let mut body = Body::empty();
Expand All @@ -211,8 +209,15 @@ where
File(_) => unimplemented!(),
};

let s = std::str::from_utf8(&body).unwrap();
match serde_json::from_str(s) {
std::str::from_utf8(&body).unwrap().to_owned()
}

fn json<T>(r: &mut AppResponse) -> T
where
for<'de> T: serde::Deserialize<'de>,
{
let s = text(r);
match serde_json::from_str(&s) {
Ok(t) => t,
Err(e) => panic!("failed to decode: {:?}\n{}", e, s),
}
Expand Down
60 changes: 60 additions & 0 deletions src/tests/maintenance_badge.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
use std::collections::HashMap;

use cargo_registry::models::Badge;
use conduit::StatusCode;

use crate::util::{MockAnonymousUser, RequestHelper};
use crate::{builders::CrateBuilder, TestApp};

fn set_up() -> MockAnonymousUser {
let (app, anon, user) = TestApp::init().with_user();
let user = user.as_model();

app.db(|conn| {
let mut badges = HashMap::new();
badges.insert("maintenance".to_owned(), {
let mut attributes = HashMap::new();
attributes.insert("status".to_owned(), "looking-for-maintainer".to_owned());
attributes
});

let krate = CrateBuilder::new("foo", user.id).expect_build(conn);
Badge::update_crate(conn, &krate, Some(&badges)).unwrap();

CrateBuilder::new("bar", user.id).expect_build(conn);
});

anon
}

#[test]
fn crate_with_maintenance_badge() {
let anon = set_up();

let response = anon
.get::<String>("/api/v1/crates/foo/maintenance.svg")
.good_text();

assert!(response.contains("looking-for-maintainer"));
assert!(response.contains("fill=\"orange\""));
}

#[test]
fn crate_without_maintenance_badge() {
let anon = set_up();

let response = anon
.get::<String>("/api/v1/crates/bar/maintenance.svg")
.good_text();

assert!(response.contains("unknown"));
assert!(response.contains("fill=\"lightgrey\""));
}

#[test]
fn unknown_crate() {
let anon = set_up();

anon.get::<()>("/api/v1/crates/unknown/maintenance.svg")
.assert_status(StatusCode::NOT_FOUND);
}
11 changes: 10 additions & 1 deletion src/tests/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -584,7 +584,7 @@ impl Bad {
/// A type providing helper methods for working with responses
#[must_use]
pub struct Response<T> {
response: AppResponse,
pub response: AppResponse,
callback_on_good: Option<Box<dyn Fn(&T)>>,
}

Expand All @@ -606,6 +606,15 @@ where
}
}

/// Assert that the response is good and deserialize the message
#[track_caller]
pub fn good_text(mut self) -> String {
if !self.response.status().is_success() {
panic!("bad response: {:?}", self.response.status());
}
crate::text(&mut self.response)
}

/// Assert that the response is good and deserialize the message
#[track_caller]
pub fn good(mut self) -> T {
Expand Down