Skip to content
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

frontend: Show feature flags in topbar and separate page #1144

Merged
merged 4 commits into from
Nov 13, 2020
Merged
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
10 changes: 7 additions & 3 deletions src/db/types.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
use postgres_types::{FromSql, ToSql};
use serde::Serialize;

#[derive(Debug, Clone, PartialEq, Serialize, FromSql, ToSql)]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, FromSql, ToSql)]
#[postgres(name = "feature")]
pub struct Feature {
name: String,
subfeatures: Vec<String>,
pub(crate) name: String,
pub(crate) subfeatures: Vec<String>,
}

impl Feature {
pub fn new(name: String, subfeatures: Vec<String>) -> Self {
Feature { name, subfeatures }
}

pub fn is_private(&self) -> bool {
self.name.starts_with('_')
}
}
5 changes: 5 additions & 0 deletions src/test/fakes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,11 @@ impl<'a> FakeRelease<'a> {
self
}

pub(crate) fn features(mut self, features: HashMap<String, Vec<String>>) -> Self {
self.package.features = features;
self
}

/// Returns the release_id
pub(crate) fn create(self) -> Result<i32, Error> {
use std::fs;
Expand Down
129 changes: 129 additions & 0 deletions src/web/crate_details.rs
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,7 @@ mod tests {
use crate::test::{wrapper, TestDatabase};
use failure::Error;
use kuchiki::traits::TendrilSink;
use std::collections::HashMap;

fn assert_last_successful_build_equals(
db: &TestDatabase,
Expand Down Expand Up @@ -741,4 +742,132 @@ mod tests {
Ok(())
});
}

#[test]
fn feature_flags_report_empty() {
wrapper(|env| {
env.fake_release()
.name("library")
.version("0.1.0")
.features(HashMap::new())
.create()?;

let page = kuchiki::parse_html().one(
env.frontend()
.get("/crate/library/0.1.0/features")
.send()?
.text()?,
);
assert!(page.select_first(r#"p[data-id="empty-features"]"#).is_ok());
Ok(())
});
}

#[test]
fn feature_private_feature_flags_are_hidden() {
wrapper(|env| {
let features = [("_private".into(), Vec::new())]
.iter()
.cloned()
.collect::<HashMap<String, Vec<String>>>();
env.fake_release()
.name("library")
.version("0.1.0")
.features(features)
.create()?;

let page = kuchiki::parse_html().one(
env.frontend()
.get("/crate/library/0.1.0/features")
.send()?
.text()?,
);
assert!(page.select_first(r#"p[data-id="empty-features"]"#).is_ok());
Ok(())
});
}

#[test]
fn feature_flags_without_default() {
wrapper(|env| {
let features = [("feature1".into(), Vec::new())]
.iter()
.cloned()
.collect::<HashMap<String, Vec<String>>>();
env.fake_release()
.name("library")
.version("0.1.0")
.features(features)
.create()?;

let page = kuchiki::parse_html().one(
env.frontend()
.get("/crate/library/0.1.0/features")
.send()?
.text()?,
);
assert!(page.select_first(r#"p[data-id="empty-features"]"#).is_err());
let def_len = page
.select_first(r#"b[data-id="default-feature-len"]"#)
.unwrap();
assert_eq!(def_len.text_contents(), "0");
Ok(())
});
}

#[test]
fn feature_flags_with_nested_default() {
wrapper(|env| {
let features = [
("default".into(), vec!["feature1".into()]),
("feature1".into(), vec!["feature2".into()]),
("feature2".into(), Vec::new()),
]
.iter()
.cloned()
.collect::<HashMap<String, Vec<String>>>();
env.fake_release()
.name("library")
.version("0.1.0")
.features(features)
.create()?;

let page = kuchiki::parse_html().one(
env.frontend()
.get("/crate/library/0.1.0/features")
.send()?
.text()?,
);
assert!(page.select_first(r#"p[data-id="empty-features"]"#).is_err());
let def_len = page
.select_first(r#"b[data-id="default-feature-len"]"#)
.unwrap();
assert_eq!(def_len.text_contents(), "3");
Ok(())
});
}

#[test]
fn feature_flags_report_null() {
wrapper(|env| {
let id = env
.fake_release()
.name("library")
.version("0.1.0")
.create()?;

env.db()
.conn()
.query("UPDATE releases SET features = NULL WHERE id = $1", &[&id])?;

let page = kuchiki::parse_html().one(
env.frontend()
.get("/crate/library/0.1.0/features")
.send()?
.text()?,
);
assert!(page.select_first(r#"p[data-id="null-features"]"#).is_ok());
Ok(())
});
}
}
220 changes: 220 additions & 0 deletions src/web/features.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
use crate::db::types::Feature;
use crate::{
db::Pool,
impl_webpage,
web::{page::WebPage, MetaData},
};
use iron::{IronResult, Request, Response};
use router::Router;
use serde::Serialize;
use std::collections::{HashMap, VecDeque};

const DEFAULT_NAME: &str = "default";

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
struct FeaturesPage {
metadata: MetaData,
features: Option<Vec<Feature>>,
default_len: usize,
}

impl_webpage! {
FeaturesPage = "crate/features.html",
}

pub fn build_features_handler(req: &mut Request) -> IronResult<Response> {
let router = extension!(req, Router);
let name = cexpect!(req, router.find("name"));
let version = cexpect!(req, router.find("version"));

let mut conn = extension!(req, Pool).get()?;
let rows = ctry!(
req,
conn.query(
"SELECT releases.features FROM releases
INNER JOIN crates ON crates.id = releases.crate_id
WHERE crates.name = $1 AND releases.version = $2",
&[&name, &version]
)
);

let row = cexpect!(req, rows.get(0));

let mut features = None;
let mut default_len = 0;

if let Some(raw) = row.get(0) {
let result = order_features_and_count_default_len(raw);
features = Some(result.0);
default_len = result.1;
Comment on lines +47 to +49
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rust-lang/rust#71156 would help with this :) 'coming soon to rust versions near you'

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That will be nice :)

}

FeaturesPage {
metadata: cexpect!(req, MetaData::from_crate(&mut conn, &name, &version)),
features,
default_len,
}
.into_response(req)
}

fn order_features_and_count_default_len(raw: Vec<Feature>) -> (Vec<Feature>, usize) {
let mut feature_map = get_feature_map(raw);
let mut features = get_tree_structure_from_default(&mut feature_map);
let mut remaining: Vec<_> = feature_map
.into_iter()
.map(|(_, feature)| feature)
.collect();
remaining.sort_by_key(|feature| feature.subfeatures.len());

let default_len = features.len();

features.extend(remaining.into_iter().rev());
(features, default_len)
}

fn get_tree_structure_from_default(feature_map: &mut HashMap<String, Feature>) -> Vec<Feature> {
let mut features = Vec::new();
let mut queue: VecDeque<String> = VecDeque::new();

queue.push_back(DEFAULT_NAME.into());
while !queue.is_empty() {
let name = queue.pop_front().unwrap();
if let Some(feature) = feature_map.remove(&name) {
feature
.subfeatures
.iter()
.for_each(|sub| queue.push_back(sub.clone()));
features.push(feature);
}
}
features
}

fn get_feature_map(raw: Vec<Feature>) -> HashMap<String, Feature> {
raw.into_iter()
.filter(|feature| !feature.is_private())
.map(|feature| (feature.name.clone(), feature))
.collect()
}

#[cfg(test)]
mod tests {
use crate::db::types::Feature;
use crate::web::features::{
get_feature_map, get_tree_structure_from_default, order_features_and_count_default_len,
DEFAULT_NAME,
};

#[test]
fn test_feature_map_filters_private() {
let private1 = Feature::new("_private1".into(), vec!["feature1".into()]);
let feature2 = Feature::new("feature2".into(), Vec::new());

let raw = vec![private1.clone(), feature2.clone()];
let feature_map = get_feature_map(raw);

assert_eq!(feature_map.len(), 1);
assert!(feature_map.contains_key(&feature2.name));
assert!(!feature_map.contains_key(&private1.name));
}

#[test]
fn test_default_tree_structure_with_nested_default() {
let default = Feature::new(DEFAULT_NAME.into(), vec!["feature1".into()]);
let non_default = Feature::new("non-default".into(), Vec::new());
let feature1 = Feature::new(
"feature1".into(),
vec!["feature2".into(), "feature3".into()],
);
let feature2 = Feature::new("feature2".into(), Vec::new());
let feature3 = Feature::new("feature3".into(), Vec::new());

let raw = vec![
default.clone(),
non_default.clone(),
feature3.clone(),
feature2.clone(),
feature1.clone(),
];
let mut feature_map = get_feature_map(raw);
let default_tree = get_tree_structure_from_default(&mut feature_map);

assert_eq!(feature_map.len(), 1);
assert_eq!(default_tree.len(), 4);
assert!(feature_map.contains_key(&non_default.name));
assert!(!feature_map.contains_key(&default.name));
assert_eq!(default_tree[0], default);
assert_eq!(default_tree[1], feature1);
assert_eq!(default_tree[2], feature2);
assert_eq!(default_tree[3], feature3);
}

#[test]
fn test_default_tree_structure_without_default() {
let feature1 = Feature::new(
"feature1".into(),
vec!["feature2".into(), "feature3".into()],
);
let feature2 = Feature::new("feature2".into(), Vec::new());
let feature3 = Feature::new("feature3".into(), Vec::new());

let raw = vec![feature3.clone(), feature2.clone(), feature1.clone()];
let mut feature_map = get_feature_map(raw);
let default_tree = get_tree_structure_from_default(&mut feature_map);

assert_eq!(feature_map.len(), 3);
assert_eq!(default_tree.len(), 0);
assert!(feature_map.contains_key(&feature1.name));
assert!(feature_map.contains_key(&feature2.name));
assert!(feature_map.contains_key(&feature3.name));
}

#[test]
fn test_default_tree_structure_single_default() {
let default = Feature::new(DEFAULT_NAME.into(), Vec::new());
let non_default = Feature::new("non-default".into(), Vec::new());

let raw = vec![default.clone(), non_default.clone()];
let mut feature_map = get_feature_map(raw);
let default_tree = get_tree_structure_from_default(&mut feature_map);

assert_eq!(feature_map.len(), 1);
assert_eq!(default_tree.len(), 1);
assert!(feature_map.contains_key(&non_default.name));
assert!(!feature_map.contains_key(&default.name));
assert_eq!(default_tree[0], default);
}

#[test]
fn test_order_features_and_get_len_without_default() {
let feature1 = Feature::new(
"feature1".into(),
vec!["feature10".into(), "feature11".into()],
);
let feature2 = Feature::new("feature2".into(), vec!["feature20".into()]);
let feature3 = Feature::new("feature3".into(), Vec::new());

let raw = vec![feature3.clone(), feature2.clone(), feature1.clone()];
let (features, default_len) = order_features_and_count_default_len(raw);

assert_eq!(features.len(), 3);
assert_eq!(default_len, 0);
assert_eq!(features[0], feature1);
assert_eq!(features[1], feature2);
assert_eq!(features[2], feature3);
}

#[test]
fn test_order_features_and_get_len_single_default() {
let default = Feature::new(DEFAULT_NAME.into(), Vec::new());
let non_default = Feature::new("non-default".into(), Vec::new());

let raw = vec![default.clone(), non_default.clone()];
let (features, default_len) = order_features_and_count_default_len(raw);

assert_eq!(features.len(), 2);
assert_eq!(default_len, 1);
assert_eq!(features[0], default);
assert_eq!(features[1], non_default);
}
}
Loading