diff --git a/juniper/src/executor/look_ahead.rs b/juniper/src/executor/look_ahead.rs index 44744716..0c945455 100644 --- a/juniper/src/executor/look_ahead.rs +++ b/juniper/src/executor/look_ahead.rs @@ -42,22 +42,21 @@ impl<'a> LookAheadValue<'a> { InputValue::Boolean(b) => LookAheadValue::Boolean(b), InputValue::Enum(ref e) => LookAheadValue::Enum(e), InputValue::Variable(ref v) => Self::from_input_value(vars.get(v).unwrap(), vars), - InputValue::List(ref l) => { - LookAheadValue::List(l.iter() - .map(|i| { - LookAheadValue::from_input_value(&i.item, vars) - }) - .collect()) - } - InputValue::Object(ref o) => { - LookAheadValue::Object(o.iter() - .map(|&(ref n, ref i)| { - (&n.item as &str, - LookAheadValue::from_input_value(&i.item, - vars)) - }) - .collect()) - } + InputValue::List(ref l) => LookAheadValue::List( + l.iter() + .map(|i| LookAheadValue::from_input_value(&i.item, vars)) + .collect(), + ), + InputValue::Object(ref o) => LookAheadValue::Object( + o.iter() + .map(|&(ref n, ref i)| { + ( + &n.item as &str, + LookAheadValue::from_input_value(&i.item, vars), + ) + }) + .collect(), + ), } } } @@ -70,9 +69,10 @@ pub struct LookAheadArgument<'a> { } impl<'a> LookAheadArgument<'a> { - pub(super) fn new(&(ref name, ref value): &'a (Spanning<&'a str>, Spanning<InputValue>), - vars: &'a Variables) - -> Self { + pub(super) fn new( + &(ref name, ref value): &'a (Spanning<&'a str>, Spanning<InputValue>), + vars: &'a Variables, + ) -> Self { LookAheadArgument { name: name.item, value: LookAheadValue::from_input_value(&value.item, vars), @@ -104,58 +104,61 @@ impl<'a> LookAheadSelection<'a> { fn should_include(directives: Option<&Vec<Spanning<Directive>>>, vars: &Variables) -> bool { directives .map(|d| { - d.iter() - .all(|d| { - let d = &d.item; - let arguments = &d.arguments; - match (d.name.item, arguments) { - ("include", &Some(ref a)) => { - a.item - .items - .iter() - .find(|item| item.0.item == "if") - .map(|&(_, ref v)| if let LookAheadValue::Boolean(b) = - LookAheadValue::from_input_value(&v.item, vars) { - b - } else { - false - }) - .unwrap_or(false) - } - ("skip", &Some(ref a)) => { - a.item - .items - .iter() - .find(|item| item.0.item == "if") - .map(|&(_, ref v)| if let LookAheadValue::Boolean(b) = - LookAheadValue::from_input_value(&v.item, vars) { - !b - } else { - false - }) - .unwrap_or(false) - } - ("skip", &None) => false, - ("include", &None) => true, - (_, _) => unreachable!(), - } - }) + d.iter().all(|d| { + let d = &d.item; + let arguments = &d.arguments; + match (d.name.item, arguments) { + ("include", &Some(ref a)) => a.item + .items + .iter() + .find(|item| item.0.item == "if") + .map(|&(_, ref v)| { + if let LookAheadValue::Boolean(b) = + LookAheadValue::from_input_value(&v.item, vars) + { + b + } else { + false + } + }) + .unwrap_or(false), + ("skip", &Some(ref a)) => a.item + .items + .iter() + .find(|item| item.0.item == "if") + .map(|&(_, ref v)| { + if let LookAheadValue::Boolean(b) = + LookAheadValue::from_input_value(&v.item, vars) + { + !b + } else { + false + } + }) + .unwrap_or(false), + ("skip", &None) => false, + ("include", &None) => true, + (_, _) => unreachable!(), + } + }) }) .unwrap_or(true) } - pub(super) fn build_from_selection(s: &'a Selection<'a>, - vars: &'a Variables, - fragments: &'a HashMap<&'a str, &'a Fragment<'a>>) - -> LookAheadSelection<'a> { + pub(super) fn build_from_selection( + s: &'a Selection<'a>, + vars: &'a Variables, + fragments: &'a HashMap<&'a str, &'a Fragment<'a>>, + ) -> LookAheadSelection<'a> { Self::build_from_selection_with_parent(s, None, vars, fragments).unwrap() } - fn build_from_selection_with_parent(s: &'a Selection<'a>, - parent: Option<&mut Self>, - vars: &'a Variables, - fragments: &'a HashMap<&'a str, &'a Fragment<'a>>) - -> Option<LookAheadSelection<'a>> { + fn build_from_selection_with_parent( + s: &'a Selection<'a>, + parent: Option<&mut Self>, + vars: &'a Variables, + fragments: &'a HashMap<&'a str, &'a Fragment<'a>>, + ) -> Option<LookAheadSelection<'a>> { let empty: &[Selection] = &[]; match *s { Selection::Field(ref field) => { @@ -171,11 +174,11 @@ impl<'a> LookAheadSelection<'a> { .as_ref() .map(|a| &a.item) .map(|a| { - a.items - .iter() - .map(|p| LookAheadArgument::new(p, vars)) - .collect() - }) + a.items + .iter() + .map(|p| LookAheadArgument::new(p, vars)) + .collect() + }) .unwrap_or_else(Vec::new); let mut ret = LookAheadSelection { name, @@ -184,23 +187,25 @@ impl<'a> LookAheadSelection<'a> { children: Vec::new(), }; for c in field - .selection_set - .as_ref() - .map(|s| s as &[_]) - .unwrap_or_else(|| empty) - .iter() { - let s = LookAheadSelection::build_from_selection_with_parent(c, - Some(&mut ret), - vars, - fragments); + .selection_set + .as_ref() + .map(|s| s as &[_]) + .unwrap_or_else(|| empty) + .iter() + { + let s = LookAheadSelection::build_from_selection_with_parent( + c, + Some(&mut ret), + vars, + fragments, + ); assert!(s.is_none()); } if let Some(p) = parent { - p.children - .push(ChildSelection { - inner: ret, - applies_for: Applies::All, - }); + p.children.push(ChildSelection { + inner: ret, + applies_for: Applies::All, + }); None } else { Some(ret) @@ -214,10 +219,12 @@ impl<'a> LookAheadSelection<'a> { let parent = parent.unwrap(); let f = fragments.get(&fragment.item.name.item).unwrap(); for c in f.selection_set.iter() { - let s = LookAheadSelection::build_from_selection_with_parent(c, - Some(parent), - vars, - fragments); + let s = LookAheadSelection::build_from_selection_with_parent( + c, + Some(parent), + vars, + fragments, + ); assert!(s.is_none()); } None @@ -229,10 +236,12 @@ impl<'a> LookAheadSelection<'a> { } let parent = parent.unwrap(); for c in inline.item.selection_set.iter() { - let s = LookAheadSelection::build_from_selection_with_parent(c, - Some(parent), - vars, - fragments); + let s = LookAheadSelection::build_from_selection_with_parent( + c, + Some(parent), + vars, + fragments, + ); assert!(s.is_none()); if let Some(ref c) = inline.item.type_condition.as_ref().map(|t| t.item) { if let Some(p) = parent.children.last_mut() { @@ -252,12 +261,12 @@ impl<'a> LookAheadSelection<'a> { children: self.children .iter() .filter_map(|c| match c.applies_for { - Applies::OnlyType(ref t) if *t == type_name => { - Some(c.inner.for_explicit_type(type_name)) - } - Applies::All => Some(c.inner.for_explicit_type(type_name)), - Applies::OnlyType(_) => None, - }) + Applies::OnlyType(ref t) if *t == type_name => { + Some(c.inner.for_explicit_type(type_name)) + } + Applies::All => Some(c.inner.for_explicit_type(type_name)), + Applies::OnlyType(_) => None, + }) .collect(), name: self.name, alias: self.alias, @@ -330,9 +339,9 @@ impl<'a> LookAheadMethods for LookAheadSelection<'a> { #[cfg(test)] mod tests { - use std::collections::HashMap; use super::*; use ast::Document; + use std::collections::HashMap; fn extract_fragments<'a>(doc: &'a Document) -> HashMap<&'a str, &'a Fragment<'a>> { let mut fragments = HashMap::new(); @@ -347,44 +356,49 @@ mod tests { #[test] fn check_simple_query() { - let docs = ::parse_document_source(" + let docs = ::parse_document_source( + " query Hero { hero { id name } } -") - .unwrap(); +", + ).unwrap(); let fragments = extract_fragments(&docs); if let ::ast::Definition::Operation(ref op) = docs[0] { let vars = Variables::default(); - let look_ahead = LookAheadSelection::build_from_selection(&op.item.selection_set[0], - &vars, - &fragments); + let look_ahead = LookAheadSelection::build_from_selection( + &op.item.selection_set[0], + &vars, + &fragments, + ); let expected = LookAheadSelection { name: "hero", alias: None, arguments: Vec::new(), - children: vec![ChildSelection { - inner: LookAheadSelection { - name: "id", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::All, - }, - ChildSelection { - inner: LookAheadSelection { - name: "name", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::All, - }], + children: vec![ + ChildSelection { + inner: LookAheadSelection { + name: "id", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::All, + }, + ChildSelection { + inner: LookAheadSelection { + name: "name", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::All, + }, + ], }; assert_eq!(look_ahead, expected); } else { @@ -394,44 +408,49 @@ query Hero { #[test] fn check_query_with_alias() { - let docs = ::parse_document_source(" + let docs = ::parse_document_source( + " query Hero { custom_hero: hero { id my_name: name } } -") - .unwrap(); +", + ).unwrap(); let fragments = extract_fragments(&docs); if let ::ast::Definition::Operation(ref op) = docs[0] { let vars = Variables::default(); - let look_ahead = LookAheadSelection::build_from_selection(&op.item.selection_set[0], - &vars, - &fragments); + let look_ahead = LookAheadSelection::build_from_selection( + &op.item.selection_set[0], + &vars, + &fragments, + ); let expected = LookAheadSelection { name: "hero", alias: Some("custom_hero"), arguments: Vec::new(), - children: vec![ChildSelection { - inner: LookAheadSelection { - name: "id", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::All, - }, - ChildSelection { - inner: LookAheadSelection { - name: "name", - alias: Some("my_name"), - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::All, - }], + children: vec![ + ChildSelection { + inner: LookAheadSelection { + name: "id", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::All, + }, + ChildSelection { + inner: LookAheadSelection { + name: "name", + alias: Some("my_name"), + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::All, + }, + ], }; assert_eq!(look_ahead, expected); } else { @@ -441,7 +460,8 @@ query Hero { #[test] fn check_query_with_child() { - let docs = ::parse_document_source(" + let docs = ::parse_document_source( + " query Hero { hero { id @@ -452,63 +472,69 @@ query Hero { } } } -") - .unwrap(); +", + ).unwrap(); let fragments = extract_fragments(&docs); if let ::ast::Definition::Operation(ref op) = docs[0] { let vars = Variables::default(); - let look_ahead = LookAheadSelection::build_from_selection(&op.item.selection_set[0], - &vars, - &fragments); + let look_ahead = LookAheadSelection::build_from_selection( + &op.item.selection_set[0], + &vars, + &fragments, + ); let expected = LookAheadSelection { name: "hero", alias: None, arguments: Vec::new(), - children: vec![ChildSelection { - inner: LookAheadSelection { - name: "id", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::All, - }, - ChildSelection { - inner: LookAheadSelection { - name: "name", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::All, - }, - ChildSelection { - inner: LookAheadSelection { - name: "friends", - alias: None, - arguments: Vec::new(), - children: vec![ChildSelection { - inner: LookAheadSelection { - name: "name", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::All, - }, - ChildSelection { - inner: LookAheadSelection { - name: "id", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::All, - }], - }, - applies_for: Applies::All, - }], + children: vec![ + ChildSelection { + inner: LookAheadSelection { + name: "id", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::All, + }, + ChildSelection { + inner: LookAheadSelection { + name: "name", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::All, + }, + ChildSelection { + inner: LookAheadSelection { + name: "friends", + alias: None, + arguments: Vec::new(), + children: vec![ + ChildSelection { + inner: LookAheadSelection { + name: "name", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::All, + }, + ChildSelection { + inner: LookAheadSelection { + name: "id", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::All, + }, + ], + }, + applies_for: Applies::All, + }, + ], }; assert_eq!(look_ahead, expected); } else { @@ -518,50 +544,55 @@ query Hero { #[test] fn check_query_with_argument() { - let docs = ::parse_document_source(" + let docs = ::parse_document_source( + " query Hero { hero(episode: EMPIRE) { id name(uppercase: true) } } -") - .unwrap(); +", + ).unwrap(); let fragments = extract_fragments(&docs); if let ::ast::Definition::Operation(ref op) = docs[0] { let vars = Variables::default(); - let look_ahead = LookAheadSelection::build_from_selection(&op.item.selection_set[0], - &vars, - &fragments); + let look_ahead = LookAheadSelection::build_from_selection( + &op.item.selection_set[0], + &vars, + &fragments, + ); let expected = LookAheadSelection { name: "hero", alias: None, arguments: vec![LookAheadArgument { - name: "episode", - value: LookAheadValue::Enum("EMPIRE"), - }], - children: vec![ChildSelection { - inner: LookAheadSelection { - name: "id", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::All, - }, - ChildSelection { - inner: LookAheadSelection { - name: "name", - alias: None, - arguments: vec![LookAheadArgument { - name: "uppercase", - value: LookAheadValue::Boolean(true), - }], - children: Vec::new(), - }, - applies_for: Applies::All, - }], + name: "episode", + value: LookAheadValue::Enum("EMPIRE"), + }], + children: vec![ + ChildSelection { + inner: LookAheadSelection { + name: "id", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::All, + }, + ChildSelection { + inner: LookAheadSelection { + name: "name", + alias: None, + arguments: vec![LookAheadArgument { + name: "uppercase", + value: LookAheadValue::Boolean(true), + }], + children: Vec::new(), + }, + applies_for: Applies::All, + }, + ], }; assert_eq!(look_ahead, expected); } else { @@ -571,48 +602,53 @@ query Hero { #[test] fn check_query_with_variable() { - let docs = ::parse_document_source(" + let docs = ::parse_document_source( + " query Hero($episode: Episode) { hero(episode: $episode) { id name } } -") - .unwrap(); +", + ).unwrap(); let fragments = extract_fragments(&docs); if let ::ast::Definition::Operation(ref op) = docs[0] { let mut vars = Variables::default(); vars.insert("episode".into(), InputValue::Enum("JEDI".into())); - let look_ahead = LookAheadSelection::build_from_selection(&op.item.selection_set[0], - &vars, - &fragments); + let look_ahead = LookAheadSelection::build_from_selection( + &op.item.selection_set[0], + &vars, + &fragments, + ); let expected = LookAheadSelection { name: "hero", alias: None, arguments: vec![LookAheadArgument { - name: "episode", - value: LookAheadValue::Enum("JEDI"), - }], - children: vec![ChildSelection { - inner: LookAheadSelection { - name: "id", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::All, - }, - ChildSelection { - inner: LookAheadSelection { - name: "name", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::All, - }], + name: "episode", + value: LookAheadValue::Enum("JEDI"), + }], + children: vec![ + ChildSelection { + inner: LookAheadSelection { + name: "id", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::All, + }, + ChildSelection { + inner: LookAheadSelection { + name: "name", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::All, + }, + ], }; assert_eq!(look_ahead, expected); } else { @@ -622,7 +658,8 @@ query Hero($episode: Episode) { #[test] fn check_query_with_fragment() { - let docs = ::parse_document_source(" + let docs = ::parse_document_source( + " query Hero { hero { id @@ -634,46 +671,50 @@ fragment commonFields on Character { name appearsIn } -") - .unwrap(); +", + ).unwrap(); let fragments = extract_fragments(&docs); if let ::ast::Definition::Operation(ref op) = docs[0] { let vars = Variables::default(); - let look_ahead = LookAheadSelection::build_from_selection(&op.item.selection_set[0], - &vars, - &fragments); + let look_ahead = LookAheadSelection::build_from_selection( + &op.item.selection_set[0], + &vars, + &fragments, + ); let expected = LookAheadSelection { name: "hero", alias: None, arguments: Vec::new(), - children: vec![ChildSelection { - inner: LookAheadSelection { - name: "id", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::All, - }, - ChildSelection { - inner: LookAheadSelection { - name: "name", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::All, - }, - ChildSelection { - inner: LookAheadSelection { - name: "appearsIn", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::All, - }], + children: vec![ + ChildSelection { + inner: LookAheadSelection { + name: "id", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::All, + }, + ChildSelection { + inner: LookAheadSelection { + name: "name", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::All, + }, + ChildSelection { + inner: LookAheadSelection { + name: "appearsIn", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::All, + }, + ], }; assert_eq!(look_ahead, expected); } else { @@ -683,7 +724,8 @@ fragment commonFields on Character { #[test] fn check_query_with_directives() { - let docs = ::parse_document_source(" + let docs = ::parse_document_source( + " query Hero { hero { id @include(if: true) @@ -691,37 +733,41 @@ query Hero { appearsIn @skip(if: true) height @skip(if: false) } -}") - .unwrap(); +}", + ).unwrap(); let fragments = extract_fragments(&docs); if let ::ast::Definition::Operation(ref op) = docs[0] { let vars = Variables::default(); - let look_ahead = LookAheadSelection::build_from_selection(&op.item.selection_set[0], - &vars, - &fragments); + let look_ahead = LookAheadSelection::build_from_selection( + &op.item.selection_set[0], + &vars, + &fragments, + ); let expected = LookAheadSelection { name: "hero", alias: None, arguments: Vec::new(), - children: vec![ChildSelection { - inner: LookAheadSelection { - name: "id", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::All, - }, - ChildSelection { - inner: LookAheadSelection { - name: "height", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::All, - }], + children: vec![ + ChildSelection { + inner: LookAheadSelection { + name: "id", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::All, + }, + ChildSelection { + inner: LookAheadSelection { + name: "height", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::All, + }, + ], }; assert_eq!(look_ahead, expected); } else { @@ -731,7 +777,8 @@ query Hero { #[test] fn check_query_with_inline_fragments() { - let docs = ::parse_document_source(" + let docs = ::parse_document_source( + " query Hero { hero { name @@ -742,46 +789,50 @@ query Hero { height } } -}") - .unwrap(); +}", + ).unwrap(); let fragments = extract_fragments(&docs); if let ::ast::Definition::Operation(ref op) = docs[0] { let vars = Variables::default(); - let look_ahead = LookAheadSelection::build_from_selection(&op.item.selection_set[0], - &vars, - &fragments); + let look_ahead = LookAheadSelection::build_from_selection( + &op.item.selection_set[0], + &vars, + &fragments, + ); let expected = LookAheadSelection { name: "hero", alias: None, arguments: Vec::new(), - children: vec![ChildSelection { - inner: LookAheadSelection { - name: "name", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::All, - }, - ChildSelection { - inner: LookAheadSelection { - name: "primaryFunction", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::OnlyType("Droid"), - }, - ChildSelection { - inner: LookAheadSelection { - name: "height", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::OnlyType("Human"), - }], + children: vec![ + ChildSelection { + inner: LookAheadSelection { + name: "name", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::All, + }, + ChildSelection { + inner: LookAheadSelection { + name: "primaryFunction", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::OnlyType("Droid"), + }, + ChildSelection { + inner: LookAheadSelection { + name: "height", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::OnlyType("Human"), + }, + ], }; assert_eq!(look_ahead, expected); } else { @@ -791,7 +842,8 @@ query Hero { #[test] fn check_complex_query() { - let docs = ::parse_document_source(" + let docs = ::parse_document_source( + " query HeroNameAndFriends($id: Integer!, $withFriends: Boolean! = true) { hero(id: $id) { id @@ -809,8 +861,8 @@ fragment comparisonFields on Character { appearsIn ... on Droid { primaryFunction } ... on Human { height } -}") - .unwrap(); +}", + ).unwrap(); let fragments = extract_fragments(&docs); if let ::ast::Definition::Operation(ref op) = docs[0] { @@ -818,123 +870,129 @@ fragment comparisonFields on Character { vars.insert("id".into(), InputValue::Int(42)); // This will normally be there vars.insert("withFriends".into(), InputValue::Boolean(true)); - let look_ahead = LookAheadSelection::build_from_selection(&op.item.selection_set[0], - &vars, - &fragments); + let look_ahead = LookAheadSelection::build_from_selection( + &op.item.selection_set[0], + &vars, + &fragments, + ); let expected = LookAheadSelection { name: "hero", alias: None, arguments: vec![LookAheadArgument { - name: "id", - value: LookAheadValue::Int(42), - }], - children: vec![ChildSelection { - inner: LookAheadSelection { - name: "id", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::All, - }, - ChildSelection { - inner: LookAheadSelection { - name: "__typename", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::All, - }, - ChildSelection { - inner: LookAheadSelection { - name: "name", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::All, - }, - ChildSelection { - inner: LookAheadSelection { - name: "appearsIn", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::All, - }, - ChildSelection { - inner: LookAheadSelection { - name: "primaryFunction", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::OnlyType("Droid"), - }, - ChildSelection { - inner: LookAheadSelection { - name: "height", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::OnlyType("Human"), - }, - ChildSelection { - inner: LookAheadSelection { - name: "friends", - alias: None, - arguments: Vec::new(), - children: vec![ChildSelection { - inner: LookAheadSelection { - name: "__typename", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::All, - }, - ChildSelection { - inner: LookAheadSelection { - name: "name", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::All, - }, - ChildSelection { - inner: LookAheadSelection { - name: "appearsIn", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::All, - }, - ChildSelection { - inner: LookAheadSelection { - name: "primaryFunction", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::OnlyType("Droid"), - }, - ChildSelection { - inner: LookAheadSelection { - name: "height", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::OnlyType("Human"), - }], - }, - applies_for: Applies::All, - }], + name: "id", + value: LookAheadValue::Int(42), + }], + children: vec![ + ChildSelection { + inner: LookAheadSelection { + name: "id", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::All, + }, + ChildSelection { + inner: LookAheadSelection { + name: "__typename", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::All, + }, + ChildSelection { + inner: LookAheadSelection { + name: "name", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::All, + }, + ChildSelection { + inner: LookAheadSelection { + name: "appearsIn", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::All, + }, + ChildSelection { + inner: LookAheadSelection { + name: "primaryFunction", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::OnlyType("Droid"), + }, + ChildSelection { + inner: LookAheadSelection { + name: "height", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::OnlyType("Human"), + }, + ChildSelection { + inner: LookAheadSelection { + name: "friends", + alias: None, + arguments: Vec::new(), + children: vec![ + ChildSelection { + inner: LookAheadSelection { + name: "__typename", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::All, + }, + ChildSelection { + inner: LookAheadSelection { + name: "name", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::All, + }, + ChildSelection { + inner: LookAheadSelection { + name: "appearsIn", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::All, + }, + ChildSelection { + inner: LookAheadSelection { + name: "primaryFunction", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::OnlyType("Droid"), + }, + ChildSelection { + inner: LookAheadSelection { + name: "height", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::OnlyType("Human"), + }, + ], + }, + applies_for: Applies::All, + }, + ], }; assert_eq!(look_ahead, expected); } else { @@ -944,7 +1002,8 @@ fragment comparisonFields on Character { #[test] fn check_resolve_concrete_type() { - let docs = ::parse_document_source(" + let docs = ::parse_document_source( + " query Hero { hero { name @@ -955,32 +1014,35 @@ query Hero { height } } -}") - .unwrap(); +}", + ).unwrap(); let fragments = extract_fragments(&docs); if let ::ast::Definition::Operation(ref op) = docs[0] { let vars = Variables::default(); - let look_ahead = LookAheadSelection::build_from_selection(&op.item.selection_set[0], - &vars, - &fragments) - .for_explicit_type("Human"); + let look_ahead = LookAheadSelection::build_from_selection( + &op.item.selection_set[0], + &vars, + &fragments, + ).for_explicit_type("Human"); let expected = ConcreteLookAheadSelection { name: "hero", alias: None, arguments: Vec::new(), - children: vec![ConcreteLookAheadSelection { - name: "name", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - ConcreteLookAheadSelection { - name: "height", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }], + children: vec![ + ConcreteLookAheadSelection { + name: "name", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + ConcreteLookAheadSelection { + name: "height", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + ], }; assert_eq!(look_ahead, expected); } else { @@ -994,41 +1056,45 @@ query Hero { name: "hero", alias: None, arguments: Vec::new(), - children: vec![ChildSelection { - inner: LookAheadSelection { - name: "id", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::All, - }, - ChildSelection { - inner: LookAheadSelection { - name: "friends", - alias: None, - arguments: Vec::new(), - children: vec![ChildSelection { - inner: LookAheadSelection { - name: "id", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::All, - }, - ChildSelection { - inner: LookAheadSelection { - name: "name", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::All, - }], - }, - applies_for: Applies::All, - }], + children: vec![ + ChildSelection { + inner: LookAheadSelection { + name: "id", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::All, + }, + ChildSelection { + inner: LookAheadSelection { + name: "friends", + alias: None, + arguments: Vec::new(), + children: vec![ + ChildSelection { + inner: LookAheadSelection { + name: "id", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::All, + }, + ChildSelection { + inner: LookAheadSelection { + name: "name", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::All, + }, + ], + }, + applies_for: Applies::All, + }, + ], }; let concret_query = lookahead.for_explicit_type("does not matter"); @@ -1041,8 +1107,10 @@ query Hero { children: Vec::new(), }; assert_eq!(id, Some(&expected)); - assert_eq!(concrete_id, - Some(&expected.for_explicit_type("does not matter"))); + assert_eq!( + concrete_id, + Some(&expected.for_explicit_type("does not matter")) + ); let friends = lookahead.select_child("friends"); let concrete_friends = concret_query.select_child("friends"); @@ -1050,28 +1118,32 @@ query Hero { name: "friends", alias: None, arguments: Vec::new(), - children: vec![ChildSelection { - inner: LookAheadSelection { - name: "id", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::All, - }, - ChildSelection { - inner: LookAheadSelection { - name: "name", - alias: None, - arguments: Vec::new(), - children: Vec::new(), - }, - applies_for: Applies::All, - }], + children: vec![ + ChildSelection { + inner: LookAheadSelection { + name: "id", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::All, + }, + ChildSelection { + inner: LookAheadSelection { + name: "name", + alias: None, + arguments: Vec::new(), + children: Vec::new(), + }, + applies_for: Applies::All, + }, + ], }; assert_eq!(friends, Some(&expected)); - assert_eq!(concrete_friends, - Some(&expected.for_explicit_type("does not matter"))); + assert_eq!( + concrete_friends, + Some(&expected.for_explicit_type("does not matter")) + ); } } diff --git a/juniper/src/executor/mod.rs b/juniper/src/executor/mod.rs index 92795fff..7b13299b 100644 --- a/juniper/src/executor/mod.rs +++ b/juniper/src/executor/mod.rs @@ -6,14 +6,18 @@ use std::sync::RwLock; use fnv::FnvHashMap; -use ast::{Definition, Document, Fragment, FromInputValue, InputValue, OperationType, Selection, - ToInputValue, Type}; -use GraphQLError; +use ast::{ + Definition, Document, Fragment, FromInputValue, InputValue, OperationType, Selection, + ToInputValue, Type, +}; use parser::SourcePosition; use value::Value; +use GraphQLError; -use schema::meta::{Argument, EnumMeta, EnumValue, Field, InputObjectMeta, InterfaceMeta, ListMeta, - MetaType, NullableMeta, ObjectMeta, PlaceholderMeta, ScalarMeta, UnionMeta}; +use schema::meta::{ + Argument, EnumMeta, EnumValue, Field, InputObjectMeta, InterfaceMeta, ListMeta, MetaType, + NullableMeta, ObjectMeta, PlaceholderMeta, ScalarMeta, UnionMeta, +}; use schema::model::{RootNode, SchemaType, TypeType}; use types::base::GraphQLType; @@ -21,7 +25,10 @@ use types::name::Name; mod look_ahead; -pub use self::look_ahead::{Applies, LookAheadArgument, LookAheadSelection, LookAheadValue, LookAheadMethods, ChildSelection, ConcreteLookAheadSelection}; +pub use self::look_ahead::{ + Applies, ChildSelection, ConcreteLookAheadSelection, LookAheadArgument, LookAheadMethods, + LookAheadSelection, LookAheadValue, +}; /// A type registry used to build schemas /// @@ -462,19 +469,29 @@ impl<'a, CtxT> Executor<'a, CtxT> { /// This allows to see the whole selection and preform operations /// affecting the childs pub fn look_ahead(&'a self) -> LookAheadSelection<'a> { - self.parent_selection_set.map(|p| { - LookAheadSelection::build_from_selection(&p[0], self.variables, self.fragments) - }).unwrap_or_else(||{ - LookAheadSelection{ + self.parent_selection_set + .map(|p| { + LookAheadSelection::build_from_selection(&p[0], self.variables, self.fragments) + }) + .unwrap_or_else(|| LookAheadSelection { name: self.current_type.innermost_concrete().name().unwrap_or(""), alias: None, arguments: Vec::new(), - children: self.current_selection_set.map(|s| s.iter().map(|s| ChildSelection { - inner: LookAheadSelection::build_from_selection(s, self.variables, self.fragments), - applies_for: Applies::All - }).collect()).unwrap_or_else(Vec::new) - } - }) + children: self.current_selection_set + .map(|s| { + s.iter() + .map(|s| ChildSelection { + inner: LookAheadSelection::build_from_selection( + s, + self.variables, + self.fragments, + ), + applies_for: Applies::All, + }) + .collect() + }) + .unwrap_or_else(Vec::new), + }) } } diff --git a/juniper/src/executor_tests/executor.rs b/juniper/src/executor_tests/executor.rs index 95e03fe5..ad8d2b24 100644 --- a/juniper/src/executor_tests/executor.rs +++ b/juniper/src/executor_tests/executor.rs @@ -686,7 +686,7 @@ mod propagates_errors_to_nullable_fields { struct Inner; enum CustomError { - NotFound + NotFound, } impl IntoFieldError for CustomError { @@ -696,8 +696,8 @@ mod propagates_errors_to_nullable_fields { "Not Found", graphql_value!({ "type": "NOT_FOUND" - }) - ) + }), + ), } } } diff --git a/juniper/src/http/mod.rs b/juniper/src/http/mod.rs index 6a32dfa6..8319b83b 100644 --- a/juniper/src/http/mod.rs +++ b/juniper/src/http/mod.rs @@ -262,15 +262,19 @@ pub mod tests { } fn test_batched_post<T: HTTPIntegration>(integration: &T) { - let response = integration.post("/", r#"[{"query": "{hero{name}}"}, {"query": "{hero{name}}"}]"#); + let response = integration.post( + "/", + r#"[{"query": "{hero{name}}"}, {"query": "{hero{name}}"}]"#, + ); assert_eq!(response.status_code, 200); assert_eq!(response.content_type, "application/json"); assert_eq!( unwrap_json_response(&response), - serde_json::from_str::<Json>(r#"[{"data": {"hero": {"name": "R2-D2"}}}, {"data": {"hero": {"name": "R2-D2"}}}]"#) - .expect("Invalid JSON constant in test") + serde_json::from_str::<Json>( + r#"[{"data": {"hero": {"name": "R2-D2"}}}, {"data": {"hero": {"name": "R2-D2"}}}]"# + ).expect("Invalid JSON constant in test") ); } } diff --git a/juniper/src/integrations/serde.rs b/juniper/src/integrations/serde.rs index e4eb46c8..12952997 100644 --- a/juniper/src/integrations/serde.rs +++ b/juniper/src/integrations/serde.rs @@ -49,22 +49,16 @@ impl<'a> ser::Serialize for GraphQLError<'a> { match *self { GraphQLError::ParseError(ref err) => vec![err].serialize(serializer), GraphQLError::ValidationError(ref errs) => errs.serialize(serializer), - GraphQLError::NoOperationProvided => { - [ - SerializeHelper { message: "Must provide an operation" } - ].serialize(serializer) - } - GraphQLError::MultipleOperationsProvided => { - [SerializeHelper { - message: "Must provide operation name \ - if query contains multiple operations", - }].serialize(serializer) - } - GraphQLError::UnknownOperationName => { - [ - SerializeHelper { message: "Unknown operation" } - ].serialize(serializer) - } + GraphQLError::NoOperationProvided => [SerializeHelper { + message: "Must provide an operation", + }].serialize(serializer), + GraphQLError::MultipleOperationsProvided => [SerializeHelper { + message: "Must provide operation name \ + if query contains multiple operations", + }].serialize(serializer), + GraphQLError::UnknownOperationName => [SerializeHelper { + message: "Unknown operation", + }].serialize(serializer), } } } @@ -275,29 +269,37 @@ impl ser::Serialize for Value { #[cfg(test)] mod tests { + use super::GraphQLError; + use ast::InputValue; use serde_json::from_str; use serde_json::to_string; - use ast::InputValue; - use super::GraphQLError; #[test] fn int() { - assert_eq!(from_str::<InputValue>("1235").unwrap(), - InputValue::int(1235)); + assert_eq!( + from_str::<InputValue>("1235").unwrap(), + InputValue::int(1235) + ); } #[test] fn float() { - assert_eq!(from_str::<InputValue>("2.0").unwrap(), - InputValue::float(2.0)); + assert_eq!( + from_str::<InputValue>("2.0").unwrap(), + InputValue::float(2.0) + ); // large value without a decimal part is also float - assert_eq!(from_str::<InputValue>("123567890123").unwrap(), - InputValue::float(123567890123.0)); + assert_eq!( + from_str::<InputValue>("123567890123").unwrap(), + InputValue::float(123567890123.0) + ); } #[test] fn errors() { - assert_eq!(to_string(&GraphQLError::UnknownOperationName).unwrap(), - r#"[{"message":"Unknown operation"}]"#); + assert_eq!( + to_string(&GraphQLError::UnknownOperationName).unwrap(), + r#"[{"message":"Unknown operation"}]"# + ); } } diff --git a/juniper/src/lib.rs b/juniper/src/lib.rs index f3a75fbb..cb7b470a 100644 --- a/juniper/src/lib.rs +++ b/juniper/src/lib.rs @@ -151,9 +151,13 @@ use parser::{parse_document_source, ParseError, Spanning}; use validation::{validate_input_values, visit_all_rules, ValidatorContext}; pub use ast::{FromInputValue, InputValue, Selection, ToInputValue, Type}; -pub use executor::{Context, ExecutionError, ExecutionResult, Executor, FieldError, FieldResult, - FromContext, IntoResolvable, Registry, Variables, IntoFieldError}; -pub use executor::{Applies, LookAheadArgument, LookAheadSelection, LookAheadValue, LookAheadMethods}; +pub use executor::{ + Applies, LookAheadArgument, LookAheadMethods, LookAheadSelection, LookAheadValue, +}; +pub use executor::{ + Context, ExecutionError, ExecutionResult, Executor, FieldError, FieldResult, FromContext, + IntoFieldError, IntoResolvable, Registry, Variables, +}; pub use schema::model::RootNode; pub use types::base::{Arguments, GraphQLType, TypeKind}; pub use types::scalars::{EmptyMutation, ID}; diff --git a/juniper/src/parser/document.rs b/juniper/src/parser/document.rs index d2a59a3b..b54b0234 100644 --- a/juniper/src/parser/document.rs +++ b/juniper/src/parser/document.rs @@ -1,12 +1,15 @@ use std::borrow::Cow; -use ast::{Arguments, Definition, Directive, Document, Field, Fragment, FragmentSpread, - InlineFragment, InputValue, Operation, OperationType, Selection, Type, - VariableDefinition, VariableDefinitions}; +use ast::{ + Arguments, Definition, Directive, Document, Field, Fragment, FragmentSpread, InlineFragment, + InputValue, Operation, OperationType, Selection, Type, VariableDefinition, VariableDefinitions, +}; use parser::value::parse_value_literal; -use parser::{Lexer, OptionParseResult, ParseError, ParseResult, Parser, Spanning, Token, - UnlocatedParseResult}; +use parser::{ + Lexer, OptionParseResult, ParseError, ParseResult, Parser, Spanning, Token, + UnlocatedParseResult, +}; #[doc(hidden)] pub fn parse_document_source(s: &str) -> UnlocatedParseResult<Document> { diff --git a/juniper/src/parser/tests/document.rs b/juniper/src/parser/tests/document.rs index 6cbb618f..5b559bee 100644 --- a/juniper/src/parser/tests/document.rs +++ b/juniper/src/parser/tests/document.rs @@ -1,4 +1,6 @@ -use ast::{Arguments, Definition, Document, Field, InputValue, Operation, OperationType, Selection}; +use ast::{ + Arguments, Definition, Document, Field, InputValue, Operation, OperationType, Selection, +}; use parser::document::parse_document_source; use parser::{ParseError, SourcePosition, Spanning, Token}; diff --git a/juniper/src/schema/schema.rs b/juniper/src/schema/schema.rs index ce8b894e..6934ced2 100644 --- a/juniper/src/schema/schema.rs +++ b/juniper/src/schema/schema.rs @@ -1,8 +1,10 @@ use executor::{ExecutionResult, Executor, Registry}; use types::base::{Arguments, GraphQLType, TypeKind}; -use schema::meta::{Argument, EnumMeta, EnumValue, Field, InputObjectMeta, InterfaceMeta, MetaType, - ObjectMeta, UnionMeta}; +use schema::meta::{ + Argument, EnumMeta, EnumValue, Field, InputObjectMeta, InterfaceMeta, MetaType, ObjectMeta, + UnionMeta, +}; use schema::model::{DirectiveLocation, DirectiveType, RootNode, SchemaType, TypeType}; impl<'a, CtxT, QueryT, MutationT> GraphQLType for RootNode<'a, QueryT, MutationT> diff --git a/juniper/src/types/pointers.rs b/juniper/src/types/pointers.rs index 7434dd2e..1563c7cf 100644 --- a/juniper/src/types/pointers.rs +++ b/juniper/src/types/pointers.rs @@ -1,5 +1,5 @@ -use std::sync::Arc; use ast::{FromInputValue, InputValue, Selection, ToInputValue}; +use std::sync::Arc; use value::Value; use executor::{ExecutionResult, Executor, Registry}; diff --git a/juniper/src/validation/mod.rs b/juniper/src/validation/mod.rs index a7adae53..eb9f6808 100644 --- a/juniper/src/validation/mod.rs +++ b/juniper/src/validation/mod.rs @@ -18,5 +18,7 @@ pub use self::traits::Visitor; pub use self::visitor::visit; #[cfg(test)] -pub use self::test_harness::{expect_fails_rule, expect_fails_rule_with_schema, expect_passes_rule, - expect_passes_rule_with_schema}; +pub use self::test_harness::{ + expect_fails_rule, expect_fails_rule_with_schema, expect_passes_rule, + expect_passes_rule_with_schema, +}; diff --git a/juniper/src/validation/multi_visitor.rs b/juniper/src/validation/multi_visitor.rs index a5e294dc..6fe400ad 100644 --- a/juniper/src/validation/multi_visitor.rs +++ b/juniper/src/validation/multi_visitor.rs @@ -1,5 +1,7 @@ -use ast::{Directive, Document, Field, Fragment, FragmentSpread, InlineFragment, InputValue, - Operation, Selection, VariableDefinition}; +use ast::{ + Directive, Document, Field, Fragment, FragmentSpread, InlineFragment, InputValue, Operation, + Selection, VariableDefinition, +}; use parser::Spanning; use validation::{ValidatorContext, Visitor}; diff --git a/juniper/src/validation/rules/overlapping_fields_can_be_merged.rs b/juniper/src/validation/rules/overlapping_fields_can_be_merged.rs index 1ddeab94..5afdc532 100644 --- a/juniper/src/validation/rules/overlapping_fields_can_be_merged.rs +++ b/juniper/src/validation/rules/overlapping_fields_can_be_merged.rs @@ -342,7 +342,8 @@ impl<'a> OverlappingFieldsCanBeMerged<'a> { let AstAndDef(ref parent_type2, ast2, ref def2) = *field2; let mutually_exclusive = parents_mutually_exclusive - || (parent_type1 != parent_type2 && self.is_object_type(ctx, *parent_type1) + || (parent_type1 != parent_type2 + && self.is_object_type(ctx, *parent_type1) && self.is_object_type(ctx, *parent_type2)); if !mutually_exclusive { @@ -717,8 +718,10 @@ mod tests { use types::scalars::ID; use parser::SourcePosition; - use validation::{expect_fails_rule, expect_fails_rule_with_schema, expect_passes_rule, - expect_passes_rule_with_schema, RuleError}; + use validation::{ + expect_fails_rule, expect_fails_rule_with_schema, expect_passes_rule, + expect_passes_rule_with_schema, RuleError, + }; #[test] fn unique_fields() { diff --git a/juniper/src/validation/traits.rs b/juniper/src/validation/traits.rs index 66c021d6..624d1778 100644 --- a/juniper/src/validation/traits.rs +++ b/juniper/src/validation/traits.rs @@ -1,5 +1,7 @@ -use ast::{Directive, Document, Field, Fragment, FragmentSpread, InlineFragment, InputValue, - Operation, Selection, VariableDefinition}; +use ast::{ + Directive, Document, Field, Fragment, FragmentSpread, InlineFragment, InputValue, Operation, + Selection, VariableDefinition, +}; use parser::Spanning; use validation::ValidatorContext; diff --git a/juniper/src/validation/visitor.rs b/juniper/src/validation/visitor.rs index fccfd34e..f7f9a786 100644 --- a/juniper/src/validation/visitor.rs +++ b/juniper/src/validation/visitor.rs @@ -1,8 +1,9 @@ use std::borrow::Cow; -use ast::{Arguments, Definition, Directive, Document, Field, Fragment, FragmentSpread, - InlineFragment, InputValue, Operation, OperationType, Selection, Type, - VariableDefinitions}; +use ast::{ + Arguments, Definition, Directive, Document, Field, Fragment, FragmentSpread, InlineFragment, + InputValue, Operation, OperationType, Selection, Type, VariableDefinitions, +}; use parser::Spanning; use schema::meta::Argument; use validation::{ValidatorContext, Visitor}; diff --git a/juniper_codegen/src/derive_enum.rs b/juniper_codegen/src/derive_enum.rs index 5fef7d4b..e7c0fbe4 100644 --- a/juniper_codegen/src/derive_enum.rs +++ b/juniper_codegen/src/derive_enum.rs @@ -1,14 +1,6 @@ -use syn; -use syn::{ - DeriveInput, - Meta, - NestedMeta, - Data, - Fields, - Ident, - Variant, -}; use quote::Tokens; +use syn; +use syn::{Data, DeriveInput, Fields, Ident, Meta, NestedMeta, Variant}; use util::*; @@ -39,8 +31,10 @@ impl EnumAttrs { res.name = Some(val); continue; } else { - panic!("Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but \"{}\" does not", - &*val); + panic!( + "Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but \"{}\" does not", + &*val + ); } } if let Some(val) = keyed_item_value(&item, "description", true) { @@ -88,8 +82,10 @@ impl EnumVariantAttrs { res.name = Some(val); continue; } else { - panic!("Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but \"{}\" does not", - &*val); + panic!( + "Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but \"{}\" does not", + &*val + ); } } if let Some(val) = keyed_item_value(&item, "description", true) { @@ -135,14 +131,14 @@ pub fn impl_enum(ast: &syn::DeriveInput) -> Tokens { for variant in variants { match variant.fields { - Fields::Unit => {}, + Fields::Unit => {} _ => { panic!(format!( "Invalid enum variant {}.\nGraphQL enums may only contain unit variants.", variant.ident )); } - } ; + }; let var_attrs = EnumVariantAttrs::from_input(variant); let var_ident = &variant.ident; diff --git a/juniper_codegen/src/derive_input_object.rs b/juniper_codegen/src/derive_input_object.rs index f01c28b3..53f25cf9 100644 --- a/juniper_codegen/src/derive_input_object.rs +++ b/juniper_codegen/src/derive_input_object.rs @@ -1,16 +1,7 @@ use std::str::FromStr; -use syn::{ - self, - DeriveInput, - NestedMeta, - Meta, - Field, - Fields, - Data, - Ident, -}; -use quote::{Tokens, ToTokens}; +use quote::{ToTokens, Tokens}; +use syn::{self, Data, DeriveInput, Field, Fields, Ident, Meta, NestedMeta}; use util::*; @@ -36,8 +27,10 @@ impl ObjAttrs { res.name = Some(val); continue; } else { - panic!("Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but \"{}\" does not", - &*val); + panic!( + "Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but \"{}\" does not", + &*val + ); } } if let Some(val) = keyed_item_value(&item, "description", true) { @@ -86,8 +79,10 @@ impl ObjFieldAttrs { res.name = Some(val); continue; } else { - panic!("Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but \"{}\" does not", - &*val); + panic!( + "Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but \"{}\" does not", + &*val + ); } } if let Some(val) = keyed_item_value(&item, "description", true) { @@ -173,14 +168,10 @@ pub fn impl_input_object(ast: &syn::DeriveInput) -> Tokens { } else { match field_attrs.default_expr { Some(ref def) => match ::proc_macro::TokenStream::from_str(def) { - Ok(t) => { - match syn::parse::<syn::Expr>(t) { - Ok(e) => { - Some(e.into_tokens()) - }, - Err(_) => { - panic!("#graphql(default = ?) must be a valid Rust expression inside a string"); - }, + Ok(t) => match syn::parse::<syn::Expr>(t) { + Ok(e) => Some(e.into_tokens()), + Err(_) => { + panic!("#graphql(default = ?) must be a valid Rust expression inside a string"); } }, Err(_) => { diff --git a/juniper_codegen/src/derive_object.rs b/juniper_codegen/src/derive_object.rs index 98d32f75..5b0912e8 100644 --- a/juniper_codegen/src/derive_object.rs +++ b/juniper_codegen/src/derive_object.rs @@ -1,11 +1,6 @@ -use syn; -use syn::{ - DeriveInput, - Data, - Fields, - Field, -}; use quote::Tokens; +use syn; +use syn::{Data, DeriveInput, Field, Fields}; use util::*; @@ -30,8 +25,10 @@ impl ObjAttrs { res.name = Some(val); continue; } else { - panic!("Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but \"{}\" does not", - &*val); + panic!( + "Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but \"{}\" does not", + &*val + ); } } if let Some(val) = keyed_item_value(&item, "description", true) { @@ -70,8 +67,10 @@ impl ObjFieldAttrs { res.name = Some(val); continue; } else { - panic!("Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but \"{}\" does not", - &*val); + panic!( + "Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but \"{}\" does not", + &*val + ); } } if let Some(val) = keyed_item_value(&item, "description", true) { diff --git a/juniper_codegen/src/lib.rs b/juniper_codegen/src/lib.rs index 97b6ddfd..40f0e4a1 100644 --- a/juniper_codegen/src/lib.rs +++ b/juniper_codegen/src/lib.rs @@ -14,10 +14,10 @@ extern crate syn; extern crate lazy_static; extern crate regex; -mod util; mod derive_enum; mod derive_input_object; mod derive_object; +mod util; use proc_macro::TokenStream; diff --git a/juniper_codegen/src/util.rs b/juniper_codegen/src/util.rs index 95669041..d4fbd940 100644 --- a/juniper_codegen/src/util.rs +++ b/juniper_codegen/src/util.rs @@ -99,8 +99,7 @@ pub fn to_camel_case(s: &str) -> String { if i > 0 && part.len() == 1 { dest.push_str(&part.to_uppercase()); } else if i > 0 && part.len() > 1 { - let first = part - .chars() + let first = part.chars() .next() .unwrap() .to_uppercase() diff --git a/juniper_iron/examples/iron_server.rs b/juniper_iron/examples/iron_server.rs index 884a9646..1939c5af 100644 --- a/juniper_iron/examples/iron_server.rs +++ b/juniper_iron/examples/iron_server.rs @@ -7,12 +7,12 @@ extern crate serde; use std::env; -use mount::Mount; -use logger::Logger; use iron::prelude::*; +use juniper::tests::model::Database; use juniper::EmptyMutation; use juniper_iron::{GraphQLHandler, GraphiQLHandler}; -use juniper::tests::model::Database; +use logger::Logger; +use mount::Mount; fn context_factory(_: &mut Request) -> IronResult<Database> { Ok(Database::new()) diff --git a/juniper_iron/src/lib.rs b/juniper_iron/src/lib.rs index b6968d0a..a35bb998 100644 --- a/juniper_iron/src/lib.rs +++ b/juniper_iron/src/lib.rs @@ -253,8 +253,7 @@ where } fn handle_get(&self, req: &mut Request) -> IronResult<GraphQLBatchRequest> { - let url_query_string = req - .get_mut::<UrlEncodedQuery>() + let url_query_string = req.get_mut::<UrlEncodedQuery>() .map_err(GraphQLIronError::Url)?; let input_query = parse_url_param(url_query_string.remove("query"))? @@ -398,8 +397,7 @@ mod tests { // and newer `hyper` doesn't allow unescaped "{" or "}". fn fixup_url(url: &str) -> String { let url = Url::parse(&format!("http://localhost:3000{}", url)).expect("url to parse"); - let path: String = url - .path() + let path: String = url.path() .iter() .map(|x| x.to_string()) .collect::<Vec<String>>() diff --git a/juniper_rocket/src/lib.rs b/juniper_rocket/src/lib.rs index a204d212..aa27fdab 100644 --- a/juniper_rocket/src/lib.rs +++ b/juniper_rocket/src/lib.rs @@ -45,22 +45,22 @@ extern crate serde_json; #[macro_use] extern crate serde_derive; -use std::io::{Cursor, Read}; use std::error::Error; +use std::io::{Cursor, Read}; -use rocket::Request; -use rocket::request::{FormItems, FromForm}; use rocket::data::{FromData, Outcome as FromDataOutcome}; -use rocket::response::{content, Responder, Response}; use rocket::http::{ContentType, Status}; +use rocket::request::{FormItems, FromForm}; +use rocket::response::{content, Responder, Response}; use rocket::Data; use rocket::Outcome::{Failure, Forward, Success}; +use rocket::Request; -use juniper::InputValue; use juniper::http; +use juniper::InputValue; -use juniper::GraphQLType; use juniper::FieldError; +use juniper::GraphQLType; use juniper::RootNode; #[derive(Debug, Deserialize, PartialEq)] @@ -88,10 +88,15 @@ impl GraphQLBatchRequest { MutationT: GraphQLType<Context = CtxT>, { match self { - &GraphQLBatchRequest::Single(ref request) => - GraphQLBatchResponse::Single(request.execute(root_node, context)), - &GraphQLBatchRequest::Batch(ref requests) => - GraphQLBatchResponse::Batch(requests.iter().map(|request| request.execute(root_node, context)).collect()), + &GraphQLBatchRequest::Single(ref request) => { + GraphQLBatchResponse::Single(request.execute(root_node, context)) + } + &GraphQLBatchRequest::Batch(ref requests) => GraphQLBatchResponse::Batch( + requests + .iter() + .map(|request| request.execute(root_node, context)) + .collect(), + ), } } } @@ -100,7 +105,9 @@ impl<'a> GraphQLBatchResponse<'a> { fn is_ok(&self) -> bool { match self { &GraphQLBatchResponse::Single(ref response) => response.is_ok(), - &GraphQLBatchResponse::Batch(ref responses) => responses.iter().fold(true, |ok, response| ok && response.is_ok()), + &GraphQLBatchResponse::Batch(ref responses) => responses + .iter() + .fold(true, |ok, response| ok && response.is_ok()), } } } @@ -222,8 +229,9 @@ impl<'f> FromForm<'f> for GraphQLRequest { } "operation_name" => { if operation_name.is_some() { - return Err("Operation name parameter must not occur more than once" - .to_owned()); + return Err( + "Operation name parameter must not occur more than once".to_owned() + ); } else { match value.url_decode() { Ok(v) => operation_name = Some(v), @@ -253,11 +261,9 @@ impl<'f> FromForm<'f> for GraphQLRequest { } if let Some(query) = query { - Ok(GraphQLRequest(GraphQLBatchRequest::Single(http::GraphQLRequest::new( - query, - operation_name, - variables, - )))) + Ok(GraphQLRequest(GraphQLBatchRequest::Single( + http::GraphQLRequest::new(query, operation_name, variables), + ))) } else { Err("Query parameter missing".to_owned()) } @@ -299,9 +305,9 @@ impl<'r> Responder<'r> for GraphQLResponse { #[cfg(test)] mod fromform_tests { use super::*; - use std::str; use juniper::InputValue; use rocket::request::{FormItems, FromForm}; + use std::str; fn check_error(input: &str, error: &str, strict: bool) { let mut items = FormItems::from(input); @@ -410,15 +416,15 @@ mod fromform_tests { mod tests { use rocket; - use rocket::Rocket; use rocket::http::ContentType; - use rocket::State; use rocket::local::{Client, LocalRequest}; + use rocket::Rocket; + use rocket::State; - use juniper::RootNode; - use juniper::tests::model::Database; use juniper::http::tests as http_tests; + use juniper::tests::model::Database; use juniper::EmptyMutation; + use juniper::RootNode; type Schema = RootNode<'static, Database, EmptyMutation<Database>>; diff --git a/juniper_tests/src/codegen/derive_enum.rs b/juniper_tests/src/codegen/derive_enum.rs index 25a50ef8..84329a63 100644 --- a/juniper_tests/src/codegen/derive_enum.rs +++ b/juniper_tests/src/codegen/derive_enum.rs @@ -8,7 +8,8 @@ use juniper::{self, FromInputValue, GraphQLType, InputValue, ToInputValue}; #[graphql(name = "Some", description = "enum descr")] enum SomeEnum { Regular, - #[graphql(name = "FULL", description = "field descr", deprecated = "depr")] Full, + #[graphql(name = "FULL", description = "field descr", deprecated = "depr")] + Full, } /// Enum doc. @@ -82,7 +83,10 @@ fn test_doc_comment() { fn test_multi_doc_comment() { let mut registry = juniper::Registry::new(FnvHashMap::default()); let meta = MultiDocEnum::meta(&(), &mut registry); - assert_eq!(meta.description(), Some(&"Doc 1. Doc 2.\nDoc 4.".to_string())); + assert_eq!( + meta.description(), + Some(&"Doc 1. Doc 2.\nDoc 4.".to_string()) + ); } #[test] @@ -90,5 +94,4 @@ fn test_doc_comment_override() { let mut registry = juniper::Registry::new(FnvHashMap::default()); let meta = OverrideDocEnum::meta(&(), &mut registry); assert_eq!(meta.description(), Some(&"enum override".to_string())); - } diff --git a/juniper_tests/src/codegen/derive_input_object.rs b/juniper_tests/src/codegen/derive_input_object.rs index e1c7bc68..698c60da 100644 --- a/juniper_tests/src/codegen/derive_input_object.rs +++ b/juniper_tests/src/codegen/derive_input_object.rs @@ -8,9 +8,11 @@ use juniper::{self, FromInputValue, GraphQLType, InputValue}; #[graphql(name = "MyInput", description = "input descr")] struct Input { regular_field: String, - #[graphql(name = "haha", default = "33", description = "haha descr")] c: i32, + #[graphql(name = "haha", default = "33", description = "haha descr")] + c: i32, - #[graphql(default)] other: Option<bool>, + #[graphql(default)] + other: Option<bool>, } /// Object comment. @@ -96,7 +98,10 @@ fn test_doc_comment() { fn test_multi_doc_comment() { let mut registry = juniper::Registry::new(FnvHashMap::default()); let meta = MultiDocComment::meta(&(), &mut registry); - assert_eq!(meta.description(), Some(&"Doc 1. Doc 2.\nDoc 4.".to_string())); + assert_eq!( + meta.description(), + Some(&"Doc 1. Doc 2.\nDoc 4.".to_string()) + ); } #[test] diff --git a/juniper_tests/src/codegen/derive_object.rs b/juniper_tests/src/codegen/derive_object.rs index 016d3c1c..e35474b4 100644 --- a/juniper_tests/src/codegen/derive_object.rs +++ b/juniper_tests/src/codegen/derive_object.rs @@ -10,7 +10,8 @@ use juniper::{self, execute, EmptyMutation, GraphQLType, RootNode, Value, Variab #[graphql(name = "MyObj", description = "obj descr")] struct Obj { regular_field: bool, - #[graphql(name = "renamedField", description = "descr", deprecation = "field descr")] c: i32, + #[graphql(name = "renamedField", description = "descr", deprecation = "field descr")] + c: i32, } #[derive(GraphQLObject, Debug, PartialEq)] @@ -101,7 +102,10 @@ fn test_doc_comment() { fn test_multi_doc_comment() { let mut registry = juniper::Registry::new(FnvHashMap::default()); let meta = MultiDocComment::meta(&(), &mut registry); - assert_eq!(meta.description(), Some(&"Doc 1. Doc 2.\nDoc 4.".to_string())); + assert_eq!( + meta.description(), + Some(&"Doc 1. Doc 2.\nDoc 4.".to_string()) + ); check_descriptions( "MultiDocComment", @@ -150,18 +154,16 @@ fn test_derived_object() { execute(doc, None, &schema, &Variables::new(), &()), Ok(( Value::object( - vec![ - ( - "obj", - Value::object( - vec![ - ("regularField", Value::boolean(true)), - ("renamedField", Value::int(22)), - ].into_iter() - .collect(), - ), + vec![( + "obj", + Value::object( + vec![ + ("regularField", Value::boolean(true)), + ("renamedField", Value::int(22)), + ].into_iter() + .collect(), ), - ].into_iter() + )].into_iter() .collect() ), vec![] @@ -187,26 +189,22 @@ fn test_derived_object_nested() { execute(doc, None, &schema, &Variables::new(), &()), Ok(( Value::object( - vec![ - ( - "nested", - Value::object( - vec![ - ( - "obj", - Value::object( - vec![ - ("regularField", Value::boolean(false)), - ("renamedField", Value::int(333)), - ].into_iter() - .collect(), - ), - ), - ].into_iter() - .collect(), - ), + vec![( + "nested", + Value::object( + vec![( + "obj", + Value::object( + vec![ + ("regularField", Value::boolean(false)), + ("renamedField", Value::int(333)), + ].into_iter() + .collect(), + ), + )].into_iter() + .collect(), ), - ].into_iter() + )].into_iter() .collect() ), vec![] @@ -215,8 +213,14 @@ fn test_derived_object_nested() { } #[cfg(test)] -fn check_descriptions(object_name: &str, object_description: &Value, field_name: &str, field_value: &Value ) { - let doc = format!(r#" +fn check_descriptions( + object_name: &str, + object_description: &Value, + field_name: &str, + field_value: &Value, +) { + let doc = format!( + r#" {{ __type(name: "{}") {{ name, @@ -227,7 +231,9 @@ fn check_descriptions(object_name: &str, object_description: &Value, field_name: }} }} }} - "#, object_name); + "#, + object_name + ); run_type_info_query(&doc, |(type_info, values)| { assert_eq!(type_info.get("name"), Some(&Value::string(object_name))); assert_eq!(type_info.get("description"), Some(object_description));