<commit_before>// The MIT License (MIT)
//
// Copyright (c) 2016 Marvin Böcker
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

use edcert::certificate::Certificate;
use edcert::signature::Signature;
use edcert::validator::Validatable;
use edcert::validator::Validator;

/// Use this type to sign content.
pub struct Letter<T: AsRef<[u8]>> {
    content: T,
    signature: Signature,
}

impl<T: AsRef<[u8]>> Letter<T> {
    /// This method creates a Letter from its parts: A piece of content (which must be
    /// convertable to a &[u8] (must implement AsRef<[u8]>)) and a Signature.
    pub fn new(content: T, signature: Signature) -> Letter<T> {
        Letter {
            content: content,
            signature: signature,
        }
    }

    /// This method creates a Letter by signing itself with the given private key
    pub fn with_private_key(content: T, private_key: &[u8]) -> Letter<T> {
        use edcert::ed25519;
        let signature = Signature::new(ed25519::sign(content.as_ref(), &private_key));
        Letter::new(content, signature)
    }

    /// This method creates a Letter by signing itself with the given certificate. The certificate
    /// must have a private key.
    pub fn with_certificate(content: T, cert: &Certificate) -> Letter<T> {
        let hash = cert.sign(content.as_ref())
                       .expect("Failed to sign content. Maybe private key missing?");
        let signature = Signature::with_parent(Box::new(cert.clone()), hash);
        Letter::new(content, signature)
    }

    pub fn get(&self) -> &T {
        &self.content
    }

    pub fn get_mut(&mut self) -> &mut T {
        &mut self.content
    }
}

impl<T: AsRef<[u8]>> Validatable for Letter<T> {
    fn is_valid<V: Validator>(&self, cv: &V) -> Result<(), &'static str> {
        let sig = &self.signature;
        let bytes = self.content.as_ref();

        if sig.is_signed_by_master() {
            use edcert::ed25519;
            let res = ed25519::verify(&bytes, sig.hash(), cv.get_master_public_key());
            if res {
                Ok(())
            } else {
                Err("Master signature invalid")
            }
        } else {
            let parent = sig.parent().unwrap();

            if cv.is_valid(parent).is_ok() {
                if parent.verify(bytes, sig.hash()) {
                    Ok(())
                } else {
                    Err("Invalid signature")
                }
            } else {
                Err("My parent isn't valid.")
            }
        }
    }

    fn is_revokable(&self) -> bool {
        false
    }

    fn get_key_id(&self) -> String {
        panic!();
    }

    fn get_certificate_id(&self) -> String {
        "".to_string()
    }
}

#[test]
fn test_simple() {
    use edcert::ed25519;
    use edcert::root_validator::RootValidator;
    use edcert::revoker::NoRevoker;

    let (mpk, msk) = ed25519::generate_keypair();

    let test_str = "hello world";

    let mut letter = Letter::with_private_key(test_str, &msk);

    let cv = RootValidator::new(&mpk, NoRevoker);

    assert_eq!(true, cv.is_valid(&letter).is_ok());

    letter.content = "world hello";

    assert_eq!(false, cv.is_valid(&letter).is_ok());
}

#[test]
fn test_certificate() {
    use edcert::ed25519;
    use edcert::meta::Meta;
    use edcert::root_validator::RootValidator;
    use edcert::revoker::NoRevoker;

    use chrono::Timelike;
    use chrono::UTC;
    use chrono::Duration;

    let (mpk, msk) = ed25519::generate_keypair();

    let meta = Meta::new_empty();
    let expires = UTC::now()
                      .checked_add(Duration::days(90))
                      .expect("Failed to add a day to expiration date.")
                      .with_nanosecond(0)
                      .unwrap();

    let mut cert = Certificate::generate_random(meta, expires);

    cert.sign_with_master(&msk);

    let test_str = "hello world";

    let cv = RootValidator::new(&mpk, NoRevoker);

    let mut letter = Letter::with_certificate(test_str, &cert);

    assert_eq!(true, cv.is_valid(&letter).is_ok());

    letter.content = "world hello";

    assert_eq!(false, cv.is_valid(&letter).is_ok());
}
<commit_msg>implemented Deref for Letter<T><commit_after>// The MIT License (MIT)
//
// Copyright (c) 2016 Marvin Böcker
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

use std::ops::Deref;

use edcert::certificate::Certificate;
use edcert::signature::Signature;
use edcert::validator::Validatable;
use edcert::validator::Validator;

/// Use this type to sign content.
#[derive(PartialEq, Debug)]
pub struct Letter<T: AsRef<[u8]>> {
    content: T,
    signature: Signature,
}

impl<T: AsRef<[u8]>> Letter<T> {
    /// This method creates a Letter from its parts: A piece of content (which must be
    /// convertable to a &[u8] (must implement AsRef<[u8]>)) and a Signature.
    pub fn new(content: T, signature: Signature) -> Letter<T> {
        Letter {
            content: content,
            signature: signature,
        }
    }

    /// This method creates a Letter by signing itself with the given private key
    pub fn with_private_key(content: T, private_key: &[u8]) -> Letter<T> {
        use edcert::ed25519;
        let signature = Signature::new(ed25519::sign(content.as_ref(), &private_key));
        Letter::new(content, signature)
    }

    /// This method creates a Letter by signing itself with the given certificate. The certificate
    /// must have a private key.
    pub fn with_certificate(content: T, cert: &Certificate) -> Letter<T> {
        let hash = cert.sign(content.as_ref())
                       .expect("Failed to sign content. Maybe private key missing?");
        let signature = Signature::with_parent(Box::new(cert.clone()), hash);
        Letter::new(content, signature)
    }

    pub fn get(&self) -> &T {
        &self.content
    }

    pub fn get_mut(&mut self) -> &mut T {
        &mut self.content
    }
}

impl<T: AsRef<[u8]>> Validatable for Letter<T> {
    fn is_valid<V: Validator>(&self, cv: &V) -> Result<(), &'static str> {
        let sig = &self.signature;
        let bytes = self.content.as_ref();

        if sig.is_signed_by_master() {
            use edcert::ed25519;
            let res = ed25519::verify(&bytes, sig.hash(), cv.get_master_public_key());
            if res {
                Ok(())
            } else {
                Err("Master signature invalid")
            }
        } else {
            let parent = sig.parent().unwrap();

            if cv.is_valid(parent).is_ok() {
                if parent.verify(bytes, sig.hash()) {
                    Ok(())
                } else {
                    Err("Invalid signature")
                }
            } else {
                Err("My parent isn't valid.")
            }
        }
    }

    fn is_revokable(&self) -> bool {
        false
    }

    fn get_key_id(&self) -> String {
        panic!();
    }

    fn get_certificate_id(&self) -> String {
        "".to_string()
    }
}

impl<T: AsRef<[u8]>> Deref for Letter<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.get()
    }
}

#[test]
fn test_simple() {
    use edcert::ed25519;
    use edcert::root_validator::RootValidator;
    use edcert::revoker::NoRevoker;

    let (mpk, msk) = ed25519::generate_keypair();

    let test_str = "hello world";

    let mut letter = Letter::with_private_key(test_str, &msk);

    let cv = RootValidator::new(&mpk, NoRevoker);

    assert_eq!(true, cv.is_valid(&letter).is_ok());

    letter.content = "world hello";

    assert_eq!(false, cv.is_valid(&letter).is_ok());
}

#[test]
fn test_certificate() {
    use edcert::ed25519;
    use edcert::meta::Meta;
    use edcert::root_validator::RootValidator;
    use edcert::revoker::NoRevoker;

    use chrono::Timelike;
    use chrono::UTC;
    use chrono::Duration;

    let (mpk, msk) = ed25519::generate_keypair();

    let meta = Meta::new_empty();
    let expires = UTC::now()
                      .checked_add(Duration::days(90))
                      .expect("Failed to add a day to expiration date.")
                      .with_nanosecond(0)
                      .unwrap();

    let mut cert = Certificate::generate_random(meta, expires);

    cert.sign_with_master(&msk);

    let test_str = "hello world";

    let cv = RootValidator::new(&mpk, NoRevoker);

    let mut letter = Letter::with_certificate(test_str, &cert);

    assert_eq!(true, cv.is_valid(&letter).is_ok());

    letter.content = "world hello";

    assert_eq!(false, cv.is_valid(&letter).is_ok());
}

#[test]
fn test_deref() {
    use edcert::ed25519;

    let (_, msk) = ed25519::generate_keypair();
    let test_str = "hello world";
    let letter = Letter::with_private_key(test_str, &msk);

    let deref_str: &str = *letter;
    assert_eq!(deref_str, test_str);
}
<|endoftext|>


<commit_before>use super::utils::LspPositionConversion;
use crate::{
    compiler::{
        ast_to_hir::AstToHir,
        hir::{self, Expression, HirDb, Lambda},
    },
    discover::{result::DiscoverResult, run::Discover, value::Value},
    input::{Input, InputDb},
    language_server::utils::TupleToPosition,
};
use itertools::Itertools;
use lsp_types::{notification::Notification, Position};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

#[derive(PartialEq, Eq, Debug, Clone, Serialize, Deserialize)]
pub struct Hint {
    kind: HintKind,
    text: String,
    position: Position,
}
#[derive(PartialEq, Eq, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum HintKind {
    Value,
    Panic,
}

#[derive(Serialize, Deserialize)]
pub struct HintsNotification {
    pub uri: String,
    pub hints: Vec<Hint>,
}
impl Notification for HintsNotification {
    const METHOD: &'static str = "candy/textDocument/publishHints";

    type Params = Self;
}

#[salsa::query_group(HintsDbStorage)]
pub trait HintsDb: AstToHir + Discover + HirDb + InputDb + LspPositionConversion {
    fn hints(&self, input: Input) -> Vec<Hint>;
}

fn hints(db: &dyn HintsDb, input: Input) -> Vec<Hint> {
    log::debug!("Calculating hints for {input}");

    let (hir, _) = db.hir(input.clone()).unwrap();
    let discover_results: HashMap<hir::Id, DiscoverResult> = HashMap::new(); // db.run_all(input.clone(), vec![]);

    collect_hir_ids_for_hints_list(db, hir.expressions.keys().cloned().collect())
        .into_iter()
        .filter_map(|id| {
            let (kind, value) = match discover_results.get(&id).unwrap() {
                DiscoverResult::Value(value) if value != &Value::nothing() => {
                    (HintKind::Value, value.to_owned())
                }
                DiscoverResult::Panic(value) => (HintKind::Panic, value.to_owned()),
                DiscoverResult::CircularImport(import_chain) => (
                    HintKind::Panic,
                    Value::Text(format!(
                        "Circular import detected: {}",
                        import_chain.iter().map(|it| format!("{it}")).join(" → ")
                    )),
                ),
                _ => return None,
            };

            let span = db.hir_id_to_display_span(id)?;

            let line = db
                .offset_to_lsp(input.clone(), span.start)
                .to_position()
                .line;
            let line_start_offsets = db.line_start_utf8_byte_offsets(input.clone());
            let last_characer_of_line = if line as usize == line_start_offsets.len() - 1 {
                db.get_input(input.clone()).unwrap().len()
            } else {
                line_start_offsets[(line + 1) as usize] - 1
            };
            let position = db
                .offset_to_lsp(input.clone(), last_characer_of_line)
                .to_position();

            None as Option<Hint>
            // TODO: Include more hints
            // Some(Hint {
            //     kind,
            //     text: format!(" # {}", db.value_to_display_string(value.to_owned())),
            //     position,
            // })
        })
        // If multiple hints are on the same line, only show the last one.
        .group_by(|hint| hint.position.line)
        .into_iter()
        .map(|(_, hints)| hints.into_iter().last().unwrap())
        .collect()
}

fn collect_hir_ids_for_hints_list(db: &dyn HintsDb, ids: Vec<hir::Id>) -> Vec<hir::Id> {
    ids.into_iter()
        .flat_map(|id| collect_hir_ids_for_hints(db, id))
        .collect()
}
fn collect_hir_ids_for_hints(db: &dyn HintsDb, id: hir::Id) -> Vec<hir::Id> {
    match db.find_expression(id.clone()).unwrap() {
        Expression::Int(_) => vec![],
        Expression::Text(_) => vec![],
        Expression::Reference(_) => vec![id],
        Expression::Symbol(_) => vec![],
        Expression::Struct(_) => vec![], // Handled separately // TODO
        Expression::Lambda(Lambda { body, .. }) => {
            collect_hir_ids_for_hints_list(db, body.expressions.keys().cloned().collect())
        }
        Expression::Call { arguments, .. } => {
            let mut ids = vec![id.to_owned()];
            for argument_id in arguments {
                let argument = match db.find_expression(argument_id.clone()) {
                    Some(argument) => argument,
                    None => continue, // Generated code
                };
                if let Expression::Reference(_) = argument {
                    continue;
                }

                ids.extend(collect_hir_ids_for_hints(db, argument_id));
            }
            ids
        }
        Expression::Builtin(_) => vec![],
        Expression::Needs { .. } => vec![],
        Expression::Error { .. } => vec![],
    }
}
<commit_msg>Disable broken LSP hints temporarily<commit_after>use super::utils::LspPositionConversion;
use crate::{
    compiler::{
        ast_to_hir::AstToHir,
        hir::{self, Expression, HirDb, Lambda},
    },
    discover::{result::DiscoverResult, run::Discover, value::Value},
    input::{Input, InputDb},
    language_server::utils::TupleToPosition,
};
use itertools::Itertools;
use lsp_types::{notification::Notification, Position};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

#[derive(PartialEq, Eq, Debug, Clone, Serialize, Deserialize)]
pub struct Hint {
    kind: HintKind,
    text: String,
    position: Position,
}
#[derive(PartialEq, Eq, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum HintKind {
    Value,
    Panic,
}

#[derive(Serialize, Deserialize)]
pub struct HintsNotification {
    pub uri: String,
    pub hints: Vec<Hint>,
}
impl Notification for HintsNotification {
    const METHOD: &'static str = "candy/textDocument/publishHints";

    type Params = Self;
}

#[salsa::query_group(HintsDbStorage)]
pub trait HintsDb: AstToHir + Discover + HirDb + InputDb + LspPositionConversion {
    fn hints(&self, input: Input) -> Vec<Hint>;
}

fn hints(db: &dyn HintsDb, input: Input) -> Vec<Hint> {
    log::debug!("Calculating hints for {input}");

    // TODO: migrate LSP hints to use VM
    return vec![];

    let (hir, _) = db.hir(input.clone()).unwrap();
    let discover_results: HashMap<hir::Id, DiscoverResult> = HashMap::new(); // db.run_all(input.clone(), vec![]);

    collect_hir_ids_for_hints_list(db, hir.expressions.keys().cloned().collect())
        .into_iter()
        .filter_map(|id| {
            let (kind, value) = match discover_results.get(&id).unwrap() {
                DiscoverResult::Value(value) if value != &Value::nothing() => {
                    (HintKind::Value, value.to_owned())
                }
                DiscoverResult::Panic(value) => (HintKind::Panic, value.to_owned()),
                DiscoverResult::CircularImport(import_chain) => (
                    HintKind::Panic,
                    Value::Text(format!(
                        "Circular import detected: {}",
                        import_chain.iter().map(|it| format!("{it}")).join(" → ")
                    )),
                ),
                _ => return None,
            };

            let span = db.hir_id_to_display_span(id)?;

            let line = db
                .offset_to_lsp(input.clone(), span.start)
                .to_position()
                .line;
            let line_start_offsets = db.line_start_utf8_byte_offsets(input.clone());
            let last_characer_of_line = if line as usize == line_start_offsets.len() - 1 {
                db.get_input(input.clone()).unwrap().len()
            } else {
                line_start_offsets[(line + 1) as usize] - 1
            };
            let position = db
                .offset_to_lsp(input.clone(), last_characer_of_line)
                .to_position();

            None as Option<Hint>
            // TODO: Include more hints
            // Some(Hint {
            //     kind,
            //     text: format!(" # {}", db.value_to_display_string(value.to_owned())),
            //     position,
            // })
        })
        // If multiple hints are on the same line, only show the last one.
        .group_by(|hint| hint.position.line)
        .into_iter()
        .map(|(_, hints)| hints.into_iter().last().unwrap())
        .collect()
}

fn collect_hir_ids_for_hints_list(db: &dyn HintsDb, ids: Vec<hir::Id>) -> Vec<hir::Id> {
    ids.into_iter()
        .flat_map(|id| collect_hir_ids_for_hints(db, id))
        .collect()
}
fn collect_hir_ids_for_hints(db: &dyn HintsDb, id: hir::Id) -> Vec<hir::Id> {
    match db.find_expression(id.clone()).unwrap() {
        Expression::Int(_) => vec![],
        Expression::Text(_) => vec![],
        Expression::Reference(_) => vec![id],
        Expression::Symbol(_) => vec![],
        Expression::Struct(_) => vec![], // Handled separately // TODO
        Expression::Lambda(Lambda { body, .. }) => {
            collect_hir_ids_for_hints_list(db, body.expressions.keys().cloned().collect())
        }
        Expression::Call { arguments, .. } => {
            let mut ids = vec![id.to_owned()];
            for argument_id in arguments {
                let argument = match db.find_expression(argument_id.clone()) {
                    Some(argument) => argument,
                    None => continue, // Generated code
                };
                if let Expression::Reference(_) = argument {
                    continue;
                }

                ids.extend(collect_hir_ids_for_hints(db, argument_id));
            }
            ids
        }
        Expression::Builtin(_) => vec![],
        Expression::Needs { .. } => vec![],
        Expression::Error { .. } => vec![],
    }
}
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

//! Liberally derived from the [Firefox JS implementation]
//! (http://mxr.mozilla.org/mozilla-central/source/toolkit/devtools/server/actors/webconsole.js).
//! Mediates interaction between the remote web console and equivalent functionality (object
//! inspection, JS evaluation, autocompletion) in Servo.

use crate::actor::{Actor, ActorMessageStatus, ActorRegistry};
use crate::actors::browsing_context::BrowsingContextActor;
use crate::actors::object::ObjectActor;
use crate::protocol::JsonPacketStream;
use crate::{ConsoleAPICall, ConsoleMessage, ConsoleMsg, PageErrorMsg};
use devtools_traits::CachedConsoleMessage;
use devtools_traits::EvaluateJSReply::{ActorValue, BooleanValue, StringValue};
use devtools_traits::EvaluateJSReply::{NullValue, NumberValue, VoidValue};
use devtools_traits::{
    CachedConsoleMessageTypes, ConsoleAPI, DevtoolScriptControlMsg, LogLevel, PageError,
};
use ipc_channel::ipc;
use msg::constellation_msg::PipelineId;
use serde_json::{self, Map, Number, Value};
use std::cell::RefCell;
use std::collections::HashMap;
use std::net::TcpStream;
use time::precise_time_ns;
use uuid::Uuid;

trait EncodableConsoleMessage {
    fn encode(&self) -> serde_json::Result<String>;
}

impl EncodableConsoleMessage for CachedConsoleMessage {
    fn encode(&self) -> serde_json::Result<String> {
        match *self {
            CachedConsoleMessage::PageError(ref a) => serde_json::to_string(a),
            CachedConsoleMessage::ConsoleAPI(ref a) => serde_json::to_string(a),
        }
    }
}

#[derive(Serialize)]
struct StartedListenersTraits;

#[derive(Serialize)]
struct StartedListenersReply {
    from: String,
    nativeConsoleAPI: bool,
    startedListeners: Vec<String>,
    traits: StartedListenersTraits,
}

#[derive(Serialize)]
struct GetCachedMessagesReply {
    from: String,
    messages: Vec<Map<String, Value>>,
}

#[derive(Serialize)]
struct StopListenersReply {
    from: String,
    stoppedListeners: Vec<String>,
}

#[derive(Serialize)]
struct AutocompleteReply {
    from: String,
    matches: Vec<String>,
    matchProp: String,
}

#[derive(Serialize)]
struct EvaluateJSReply {
    from: String,
    input: String,
    result: Value,
    timestamp: u64,
    exception: Value,
    exceptionMessage: Value,
    helperResult: Value,
}

#[derive(Serialize)]
struct EvaluateJSEvent {
    from: String,
    r#type: String,
    input: String,
    result: Value,
    timestamp: u64,
    resultID: String,
    exception: Value,
    exceptionMessage: Value,
    helperResult: Value,
}

#[derive(Serialize)]
struct EvaluateJSAsyncReply {
    from: String,
    resultID: String,
}

#[derive(Serialize)]
struct SetPreferencesReply {
    from: String,
    updated: Vec<String>,
}

pub struct ConsoleActor {
    pub name: String,
    pub browsing_context: String,
    pub cached_events: RefCell<HashMap<PipelineId, Vec<CachedConsoleMessage>>>,
}

impl ConsoleActor {
    fn evaluateJS(
        &self,
        registry: &ActorRegistry,
        msg: &Map<String, Value>,
    ) -> Result<EvaluateJSReply, ()> {
        let browsing_context = registry.find::<BrowsingContextActor>(&self.browsing_context);
        let input = msg.get("text").unwrap().as_str().unwrap().to_owned();
        let (chan, port) = ipc::channel().unwrap();
        browsing_context
            .script_chan
            .send(DevtoolScriptControlMsg::EvaluateJS(
                browsing_context.active_pipeline.get(),
                input.clone(),
                chan,
            ))
            .unwrap();

        //TODO: extract conversion into protocol module or some other useful place
        let result = match port.recv().map_err(|_| ())? {
            VoidValue => {
                let mut m = Map::new();
                m.insert("type".to_owned(), Value::String("undefined".to_owned()));
                Value::Object(m)
            },
            NullValue => {
                let mut m = Map::new();
                m.insert("type".to_owned(), Value::String("null".to_owned()));
                Value::Object(m)
            },
            BooleanValue(val) => Value::Bool(val),
            NumberValue(val) => {
                if val.is_nan() {
                    let mut m = Map::new();
                    m.insert("type".to_owned(), Value::String("NaN".to_owned()));
                    Value::Object(m)
                } else if val.is_infinite() {
                    let mut m = Map::new();
                    if val < 0. {
                        m.insert("type".to_owned(), Value::String("-Infinity".to_owned()));
                    } else {
                        m.insert("type".to_owned(), Value::String("Infinity".to_owned()));
                    }
                    Value::Object(m)
                } else if val == 0. && val.is_sign_negative() {
                    let mut m = Map::new();
                    m.insert("type".to_owned(), Value::String("-0".to_owned()));
                    Value::Object(m)
                } else {
                    Value::Number(Number::from_f64(val).unwrap())
                }
            },
            StringValue(s) => Value::String(s),
            ActorValue { class, uuid } => {
                //TODO: make initial ActorValue message include these properties?
                let mut m = Map::new();
                let actor = ObjectActor::new(registry, uuid);

                m.insert("type".to_owned(), Value::String("object".to_owned()));
                m.insert("class".to_owned(), Value::String(class));
                m.insert("actor".to_owned(), Value::String(actor));
                m.insert("extensible".to_owned(), Value::Bool(true));
                m.insert("frozen".to_owned(), Value::Bool(false));
                m.insert("sealed".to_owned(), Value::Bool(false));
                Value::Object(m)
            },
        };

        //TODO: catch and return exception values from JS evaluation
        let reply = EvaluateJSReply {
            from: self.name(),
            input: input,
            result: result,
            timestamp: 0,
            exception: Value::Null,
            exceptionMessage: Value::Null,
            helperResult: Value::Null,
        };
        std::result::Result::Ok(reply)
    }

    pub(crate) fn handle_page_error(
        &self,
        page_error: PageError,
        pipeline: PipelineId,
        browsing_context: &BrowsingContextActor,
    ) {
        self.cached_events
            .borrow_mut()
            .entry(pipeline)
            .or_insert(vec![])
            .push(CachedConsoleMessage::PageError(page_error.clone()));
        if browsing_context.active_pipeline.get() == pipeline {
            let msg = PageErrorMsg {
                from: self.name(),
                type_: "pageError".to_owned(),
                pageError: page_error,
            };
            for stream in &mut *browsing_context.streams.borrow_mut() {
                stream.write_json_packet(&msg);
            }
        }
    }

    pub(crate) fn handle_console_api(
        &self,
        console_message: ConsoleMessage,
        pipeline: PipelineId,
        browsing_context: &BrowsingContextActor,
    ) {
        let level = match console_message.logLevel {
            LogLevel::Debug => "debug",
            LogLevel::Info => "info",
            LogLevel::Warn => "warn",
            LogLevel::Error => "error",
            _ => "log",
        }
        .to_owned();
        self.cached_events
            .borrow_mut()
            .entry(pipeline)
            .or_insert(vec![])
            .push(CachedConsoleMessage::ConsoleAPI(ConsoleAPI {
                type_: "ConsoleAPI".to_owned(),
                level: level.clone(),
                filename: console_message.filename.clone(),
                lineNumber: console_message.lineNumber as u32,
                functionName: "".to_string(), //TODO
                timeStamp: precise_time_ns(),
                private: false,
                arguments: vec![console_message.message.clone()],
            }));
        if browsing_context.active_pipeline.get() == pipeline {
            let msg = ConsoleAPICall {
                from: self.name(),
                type_: "consoleAPICall".to_owned(),
                message: ConsoleMsg {
                    level: level,
                    timeStamp: precise_time_ns(),
                    arguments: vec![console_message.message],
                    filename: console_message.filename,
                    lineNumber: console_message.lineNumber,
                    columnNumber: console_message.columnNumber,
                },
            };
            for stream in &mut *browsing_context.streams.borrow_mut() {
                stream.write_json_packet(&msg);
            }
        }
    }
}

impl Actor for ConsoleActor {
    fn name(&self) -> String {
        self.name.clone()
    }

    fn handle_message(
        &self,
        registry: &ActorRegistry,
        msg_type: &str,
        msg: &Map<String, Value>,
        stream: &mut TcpStream,
    ) -> Result<ActorMessageStatus, ()> {
        Ok(match msg_type {
            "getCachedMessages" => {
                let str_types = msg
                    .get("messageTypes")
                    .unwrap()
                    .as_array()
                    .unwrap()
                    .into_iter()
                    .map(|json_type| json_type.as_str().unwrap());
                let mut message_types = CachedConsoleMessageTypes::empty();
                for str_type in str_types {
                    match str_type {
                        "PageError" => message_types.insert(CachedConsoleMessageTypes::PAGE_ERROR),
                        "ConsoleAPI" => {
                            message_types.insert(CachedConsoleMessageTypes::CONSOLE_API)
                        },
                        s => debug!("unrecognized message type requested: \"{}\"", s),
                    };
                }
                let browsing_context =
                    registry.find::<BrowsingContextActor>(&self.browsing_context);
                let mut messages = vec![];
                for event in self
                    .cached_events
                    .borrow()
                    .get(&browsing_context.active_pipeline.get())
                    .unwrap_or(&vec![])
                    .iter()
                {
                    let include = match event {
                        CachedConsoleMessage::PageError(_)
                            if message_types.contains(CachedConsoleMessageTypes::PAGE_ERROR) =>
                        {
                            true
                        },
                        CachedConsoleMessage::ConsoleAPI(_)
                            if message_types.contains(CachedConsoleMessageTypes::CONSOLE_API) =>
                        {
                            true
                        },
                        _ => false,
                    };
                    if include {
                        let json_string = event.encode().unwrap();
                        let json = serde_json::from_str::<Value>(&json_string).unwrap();
                        messages.push(json.as_object().unwrap().to_owned())
                    }
                }

                let msg = GetCachedMessagesReply {
                    from: self.name(),
                    messages: messages,
                };
                stream.write_json_packet(&msg);
                ActorMessageStatus::Processed
            },

            "startListeners" => {
                //TODO: actually implement listener filters that support starting/stopping
                let listeners = msg.get("listeners").unwrap().as_array().unwrap().to_owned();
                let msg = StartedListenersReply {
                    from: self.name(),
                    nativeConsoleAPI: true,
                    startedListeners: listeners
                        .into_iter()
                        .map(|s| s.as_str().unwrap().to_owned())
                        .collect(),
                    traits: StartedListenersTraits,
                };
                stream.write_json_packet(&msg);
                ActorMessageStatus::Processed
            },

            "stopListeners" => {
                //TODO: actually implement listener filters that support starting/stopping
                let msg = StopListenersReply {
                    from: self.name(),
                    stoppedListeners: msg
                        .get("listeners")
                        .unwrap()
                        .as_array()
                        .unwrap_or(&vec![])
                        .iter()
                        .map(|listener| listener.as_str().unwrap().to_owned())
                        .collect(),
                };
                stream.write_json_packet(&msg);
                ActorMessageStatus::Processed
            },

            //TODO: implement autocompletion like onAutocomplete in
            //      http://mxr.mozilla.org/mozilla-central/source/toolkit/devtools/server/actors/webconsole.js
            "autocomplete" => {
                let msg = AutocompleteReply {
                    from: self.name(),
                    matches: vec![],
                    matchProp: "".to_owned(),
                };
                stream.write_json_packet(&msg);
                ActorMessageStatus::Processed
            },

            "evaluateJS" => {
                let msg = self.evaluateJS(&registry, &msg);
                stream.write_json_packet(&msg);
                ActorMessageStatus::Processed
            },

            "evaluateJSAsync" => {
                let resultID = Uuid::new_v4().to_string();
                let early_reply = EvaluateJSAsyncReply {
                    from: self.name(),
                    resultID: resultID.clone(),
                };
                // Emit an eager reply so that the client starts listening
                // for an async event with the resultID
                stream.write_json_packet(&early_reply);
                let reply = self.evaluateJS(&registry, &msg).unwrap();
                let msg = EvaluateJSEvent {
                    from: self.name(),
                    r#type: "evaluationResult".to_owned(),
                    input: reply.input,
                    result: reply.result,
                    timestamp: reply.timestamp,
                    resultID: resultID,
                    exception: reply.exception,
                    exceptionMessage: reply.exceptionMessage,
                    helperResult: reply.helperResult,
                };
                // Send the data from evaluateJS along with a resultID
                stream.write_json_packet(&msg);
                ActorMessageStatus::Processed
            },

            "setPreferences" => {
                let msg = SetPreferencesReply {
                    from: self.name(),
                    updated: vec![],
                };
                stream.write_json_packet(&msg);
                ActorMessageStatus::Processed
            },

            _ => ActorMessageStatus::Ignored,
        })
    }
}
<commit_msg>Support clearing cached events in console actor.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

//! Liberally derived from the [Firefox JS implementation]
//! (http://mxr.mozilla.org/mozilla-central/source/toolkit/devtools/server/actors/webconsole.js).
//! Mediates interaction between the remote web console and equivalent functionality (object
//! inspection, JS evaluation, autocompletion) in Servo.

use crate::actor::{Actor, ActorMessageStatus, ActorRegistry};
use crate::actors::browsing_context::BrowsingContextActor;
use crate::actors::object::ObjectActor;
use crate::protocol::JsonPacketStream;
use crate::{ConsoleAPICall, ConsoleMessage, ConsoleMsg, PageErrorMsg};
use devtools_traits::CachedConsoleMessage;
use devtools_traits::EvaluateJSReply::{ActorValue, BooleanValue, StringValue};
use devtools_traits::EvaluateJSReply::{NullValue, NumberValue, VoidValue};
use devtools_traits::{
    CachedConsoleMessageTypes, ConsoleAPI, DevtoolScriptControlMsg, LogLevel, PageError,
};
use ipc_channel::ipc;
use msg::constellation_msg::PipelineId;
use serde_json::{self, Map, Number, Value};
use std::cell::RefCell;
use std::collections::HashMap;
use std::net::TcpStream;
use time::precise_time_ns;
use uuid::Uuid;

trait EncodableConsoleMessage {
    fn encode(&self) -> serde_json::Result<String>;
}

impl EncodableConsoleMessage for CachedConsoleMessage {
    fn encode(&self) -> serde_json::Result<String> {
        match *self {
            CachedConsoleMessage::PageError(ref a) => serde_json::to_string(a),
            CachedConsoleMessage::ConsoleAPI(ref a) => serde_json::to_string(a),
        }
    }
}

#[derive(Serialize)]
struct StartedListenersTraits;

#[derive(Serialize)]
struct StartedListenersReply {
    from: String,
    nativeConsoleAPI: bool,
    startedListeners: Vec<String>,
    traits: StartedListenersTraits,
}

#[derive(Serialize)]
struct GetCachedMessagesReply {
    from: String,
    messages: Vec<Map<String, Value>>,
}

#[derive(Serialize)]
struct StopListenersReply {
    from: String,
    stoppedListeners: Vec<String>,
}

#[derive(Serialize)]
struct AutocompleteReply {
    from: String,
    matches: Vec<String>,
    matchProp: String,
}

#[derive(Serialize)]
struct EvaluateJSReply {
    from: String,
    input: String,
    result: Value,
    timestamp: u64,
    exception: Value,
    exceptionMessage: Value,
    helperResult: Value,
}

#[derive(Serialize)]
struct EvaluateJSEvent {
    from: String,
    r#type: String,
    input: String,
    result: Value,
    timestamp: u64,
    resultID: String,
    exception: Value,
    exceptionMessage: Value,
    helperResult: Value,
}

#[derive(Serialize)]
struct EvaluateJSAsyncReply {
    from: String,
    resultID: String,
}

#[derive(Serialize)]
struct SetPreferencesReply {
    from: String,
    updated: Vec<String>,
}

pub struct ConsoleActor {
    pub name: String,
    pub browsing_context: String,
    pub cached_events: RefCell<HashMap<PipelineId, Vec<CachedConsoleMessage>>>,
}

impl ConsoleActor {
    fn evaluateJS(
        &self,
        registry: &ActorRegistry,
        msg: &Map<String, Value>,
    ) -> Result<EvaluateJSReply, ()> {
        let browsing_context = registry.find::<BrowsingContextActor>(&self.browsing_context);
        let input = msg.get("text").unwrap().as_str().unwrap().to_owned();
        let (chan, port) = ipc::channel().unwrap();
        browsing_context
            .script_chan
            .send(DevtoolScriptControlMsg::EvaluateJS(
                browsing_context.active_pipeline.get(),
                input.clone(),
                chan,
            ))
            .unwrap();

        //TODO: extract conversion into protocol module or some other useful place
        let result = match port.recv().map_err(|_| ())? {
            VoidValue => {
                let mut m = Map::new();
                m.insert("type".to_owned(), Value::String("undefined".to_owned()));
                Value::Object(m)
            },
            NullValue => {
                let mut m = Map::new();
                m.insert("type".to_owned(), Value::String("null".to_owned()));
                Value::Object(m)
            },
            BooleanValue(val) => Value::Bool(val),
            NumberValue(val) => {
                if val.is_nan() {
                    let mut m = Map::new();
                    m.insert("type".to_owned(), Value::String("NaN".to_owned()));
                    Value::Object(m)
                } else if val.is_infinite() {
                    let mut m = Map::new();
                    if val < 0. {
                        m.insert("type".to_owned(), Value::String("-Infinity".to_owned()));
                    } else {
                        m.insert("type".to_owned(), Value::String("Infinity".to_owned()));
                    }
                    Value::Object(m)
                } else if val == 0. && val.is_sign_negative() {
                    let mut m = Map::new();
                    m.insert("type".to_owned(), Value::String("-0".to_owned()));
                    Value::Object(m)
                } else {
                    Value::Number(Number::from_f64(val).unwrap())
                }
            },
            StringValue(s) => Value::String(s),
            ActorValue { class, uuid } => {
                //TODO: make initial ActorValue message include these properties?
                let mut m = Map::new();
                let actor = ObjectActor::new(registry, uuid);

                m.insert("type".to_owned(), Value::String("object".to_owned()));
                m.insert("class".to_owned(), Value::String(class));
                m.insert("actor".to_owned(), Value::String(actor));
                m.insert("extensible".to_owned(), Value::Bool(true));
                m.insert("frozen".to_owned(), Value::Bool(false));
                m.insert("sealed".to_owned(), Value::Bool(false));
                Value::Object(m)
            },
        };

        //TODO: catch and return exception values from JS evaluation
        let reply = EvaluateJSReply {
            from: self.name(),
            input: input,
            result: result,
            timestamp: 0,
            exception: Value::Null,
            exceptionMessage: Value::Null,
            helperResult: Value::Null,
        };
        std::result::Result::Ok(reply)
    }

    pub(crate) fn handle_page_error(
        &self,
        page_error: PageError,
        pipeline: PipelineId,
        browsing_context: &BrowsingContextActor,
    ) {
        self.cached_events
            .borrow_mut()
            .entry(pipeline)
            .or_insert(vec![])
            .push(CachedConsoleMessage::PageError(page_error.clone()));
        if browsing_context.active_pipeline.get() == pipeline {
            let msg = PageErrorMsg {
                from: self.name(),
                type_: "pageError".to_owned(),
                pageError: page_error,
            };
            for stream in &mut *browsing_context.streams.borrow_mut() {
                stream.write_json_packet(&msg);
            }
        }
    }

    pub(crate) fn handle_console_api(
        &self,
        console_message: ConsoleMessage,
        pipeline: PipelineId,
        browsing_context: &BrowsingContextActor,
    ) {
        let level = match console_message.logLevel {
            LogLevel::Debug => "debug",
            LogLevel::Info => "info",
            LogLevel::Warn => "warn",
            LogLevel::Error => "error",
            _ => "log",
        }
        .to_owned();
        self.cached_events
            .borrow_mut()
            .entry(pipeline)
            .or_insert(vec![])
            .push(CachedConsoleMessage::ConsoleAPI(ConsoleAPI {
                type_: "ConsoleAPI".to_owned(),
                level: level.clone(),
                filename: console_message.filename.clone(),
                lineNumber: console_message.lineNumber as u32,
                functionName: "".to_string(), //TODO
                timeStamp: precise_time_ns(),
                private: false,
                arguments: vec![console_message.message.clone()],
            }));
        if browsing_context.active_pipeline.get() == pipeline {
            let msg = ConsoleAPICall {
                from: self.name(),
                type_: "consoleAPICall".to_owned(),
                message: ConsoleMsg {
                    level: level,
                    timeStamp: precise_time_ns(),
                    arguments: vec![console_message.message],
                    filename: console_message.filename,
                    lineNumber: console_message.lineNumber,
                    columnNumber: console_message.columnNumber,
                },
            };
            for stream in &mut *browsing_context.streams.borrow_mut() {
                stream.write_json_packet(&msg);
            }
        }
    }
}

impl Actor for ConsoleActor {
    fn name(&self) -> String {
        self.name.clone()
    }

    fn handle_message(
        &self,
        registry: &ActorRegistry,
        msg_type: &str,
        msg: &Map<String, Value>,
        stream: &mut TcpStream,
    ) -> Result<ActorMessageStatus, ()> {
        Ok(match msg_type {
            "clearMessagesCache" => {
                let browsing_context =
                    registry.find::<BrowsingContextActor>(&self.browsing_context);
                self.cached_events.borrow_mut().remove(&browsing_context.active_pipeline.get());
                ActorMessageStatus::Processed
            }

            "getCachedMessages" => {
                let str_types = msg
                    .get("messageTypes")
                    .unwrap()
                    .as_array()
                    .unwrap()
                    .into_iter()
                    .map(|json_type| json_type.as_str().unwrap());
                let mut message_types = CachedConsoleMessageTypes::empty();
                for str_type in str_types {
                    match str_type {
                        "PageError" => message_types.insert(CachedConsoleMessageTypes::PAGE_ERROR),
                        "ConsoleAPI" => {
                            message_types.insert(CachedConsoleMessageTypes::CONSOLE_API)
                        },
                        s => debug!("unrecognized message type requested: \"{}\"", s),
                    };
                }
                let browsing_context =
                    registry.find::<BrowsingContextActor>(&self.browsing_context);
                let mut messages = vec![];
                for event in self
                    .cached_events
                    .borrow()
                    .get(&browsing_context.active_pipeline.get())
                    .unwrap_or(&vec![])
                    .iter()
                {
                    let include = match event {
                        CachedConsoleMessage::PageError(_)
                            if message_types.contains(CachedConsoleMessageTypes::PAGE_ERROR) =>
                        {
                            true
                        },
                        CachedConsoleMessage::ConsoleAPI(_)
                            if message_types.contains(CachedConsoleMessageTypes::CONSOLE_API) =>
                        {
                            true
                        },
                        _ => false,
                    };
                    if include {
                        let json_string = event.encode().unwrap();
                        let json = serde_json::from_str::<Value>(&json_string).unwrap();
                        messages.push(json.as_object().unwrap().to_owned())
                    }
                }

                let msg = GetCachedMessagesReply {
                    from: self.name(),
                    messages: messages,
                };
                stream.write_json_packet(&msg);
                ActorMessageStatus::Processed
            },

            "startListeners" => {
                //TODO: actually implement listener filters that support starting/stopping
                let listeners = msg.get("listeners").unwrap().as_array().unwrap().to_owned();
                let msg = StartedListenersReply {
                    from: self.name(),
                    nativeConsoleAPI: true,
                    startedListeners: listeners
                        .into_iter()
                        .map(|s| s.as_str().unwrap().to_owned())
                        .collect(),
                    traits: StartedListenersTraits,
                };
                stream.write_json_packet(&msg);
                ActorMessageStatus::Processed
            },

            "stopListeners" => {
                //TODO: actually implement listener filters that support starting/stopping
                let msg = StopListenersReply {
                    from: self.name(),
                    stoppedListeners: msg
                        .get("listeners")
                        .unwrap()
                        .as_array()
                        .unwrap_or(&vec![])
                        .iter()
                        .map(|listener| listener.as_str().unwrap().to_owned())
                        .collect(),
                };
                stream.write_json_packet(&msg);
                ActorMessageStatus::Processed
            },

            //TODO: implement autocompletion like onAutocomplete in
            //      http://mxr.mozilla.org/mozilla-central/source/toolkit/devtools/server/actors/webconsole.js
            "autocomplete" => {
                let msg = AutocompleteReply {
                    from: self.name(),
                    matches: vec![],
                    matchProp: "".to_owned(),
                };
                stream.write_json_packet(&msg);
                ActorMessageStatus::Processed
            },

            "evaluateJS" => {
                let msg = self.evaluateJS(&registry, &msg);
                stream.write_json_packet(&msg);
                ActorMessageStatus::Processed
            },

            "evaluateJSAsync" => {
                let resultID = Uuid::new_v4().to_string();
                let early_reply = EvaluateJSAsyncReply {
                    from: self.name(),
                    resultID: resultID.clone(),
                };
                // Emit an eager reply so that the client starts listening
                // for an async event with the resultID
                stream.write_json_packet(&early_reply);
                let reply = self.evaluateJS(&registry, &msg).unwrap();
                let msg = EvaluateJSEvent {
                    from: self.name(),
                    r#type: "evaluationResult".to_owned(),
                    input: reply.input,
                    result: reply.result,
                    timestamp: reply.timestamp,
                    resultID: resultID,
                    exception: reply.exception,
                    exceptionMessage: reply.exceptionMessage,
                    helperResult: reply.helperResult,
                };
                // Send the data from evaluateJS along with a resultID
                stream.write_json_packet(&msg);
                ActorMessageStatus::Processed
            },

            "setPreferences" => {
                let msg = SetPreferencesReply {
                    from: self.name(),
                    updated: vec![],
                };
                stream.write_json_packet(&msg);
                ActorMessageStatus::Processed
            },

            _ => ActorMessageStatus::Ignored,
        })
    }
}
<|endoftext|>


<commit_before>extern crate walkdir;

use self::walkdir::{DirEntry as WalkDirEntry, WalkDir, WalkDirIterator};

use std::collections::BTreeSet;
use std::ffi::OsString;
use std::fs;
use std::io::Error as IoError;
use std::path::{Path, PathBuf};
use std::result::Result;

macro_rules! path_buf {
    ($($x: expr),+) => {
        PathBuf::new()
            $(.join($x))+
    };
}

pub fn ls<P: AsRef<Path>>(path: P) -> Result<Vec<String>, IoError> {
    let dirs = try!(fs::read_dir(path));
    let dirs = dirs
        .filter_map(Result::ok)
        .map(|d| d.file_name())
        .map(OsString::into_string)
        .filter_map(Result::ok)
        .collect::<Vec<String>>();
    Ok(dirs)
}

pub fn is_empty_dir<P: AsRef<Path>>(path: P) -> bool {
    match fs::read_dir(path) {
        Ok(rd) => rd.count() == 0,
        Err(_) => false,
    }
}

fn is_hidden_name(file_name: &str) -> bool {
    file_name.starts_with(".") && file_name.len() > 1 && file_name != ".."
}
#[test]
fn is_hidden_name_should_return_true() {
    let file_names = [
        ".a",
        ".ab",
        ".abc",
        "..a",
        "...",
    ];
    for file_name in &file_names {
        assert!(is_hidden_name(file_name));
    }
}
#[test]
fn is_hidden_name_should_return_false() {
    let file_names = [
        "",

        ".",
        "..",
        "a",
        "ab",
        "abc",
    ];
    for file_name in &file_names {
        assert!(!is_hidden_name(file_name));
    }
}

fn is_hidden(entry: &WalkDirEntry) -> bool {
    entry
        .file_name()
        .to_str()
        .map_or(false, is_hidden_name)
}

pub fn walk_dir<P: AsRef<Path>>(root: P) -> BTreeSet<String> {
    let walker = WalkDir::new(root)
        .into_iter()
        .filter_entry(|e| !is_hidden(e))
        .filter_map(Result::ok)
        .filter(|e| !e.file_type().is_dir())
        .collect::<Vec<WalkDirEntry>>();

    walker
        .into_iter()
        .filter_map(|e| e.path().to_str().map(|s| s.to_string()))
        .collect::<BTreeSet<String>>()
}

pub fn dirs_ordered_by_descending_depth<P: AsRef<Path>>(root: P) -> Vec<PathBuf> {
    let mut walker = WalkDir::new(root)
        .into_iter()
        .filter_entry(|e| !is_hidden(e))
        .filter_entry(|e| e.file_type().is_dir())
        .filter_map(Result::ok)
        .collect::<Vec<WalkDirEntry>>();

    walker.sort_by(|l, r| {
        let l_depth = &l.depth();
        let r_depth = &r.depth();
        r_depth.cmp(l_depth)
    });

    walker
        .into_iter()
        .map(|e| e.path().to_path_buf())
        .collect::<Vec<PathBuf>>()
}

#[cfg(test)]
mod tests {
    use super::*;

    use std::fs::{self, File};
    use std::io::Write;
    use std::path::{Path, PathBuf};

    struct Helper;
    impl Helper {
        fn d1() -> String { "directory1".to_string() }
        fn d2() -> String { "directory2".to_string() }
        fn d3() -> String { "directory3".to_string() }

        fn f1() -> String { "file1".to_string() }
        fn f2() -> String { "file2".to_string() }

        fn path_to_d1() -> PathBuf {
            PathBuf::new().join(Self::d1())
        }
        fn path_to_d2() -> PathBuf {
            Self::path_to_d1().join(Self::d2())
        }
        fn path_to_d3() -> PathBuf {
            Self::path_to_d2().join(Self::d3())
        }

        fn path_to_f1() -> PathBuf {
            Self::path_to_d1().join(Self::f1())
        }
        fn path_to_f2() -> PathBuf {
            Self::path_to_d2().join(Self::f2())
        }

        fn remove_dirs_and_files() {
            fs::remove_dir_all(Self::path_to_d1()).ok();
        }

        fn create_dirs_and_files() {
            Self::remove_dirs_and_files();

            fs::create_dir_all(Self::path_to_d3()).ok();

            let mut f = File::create(Self::path_to_f1()).unwrap();
            f.write("\n".as_ref()).ok();
            fs::copy(Self::path_to_f1(), Self::path_to_f2()).ok();
        }
    }

    #[test]
    fn path_buf_macro_should_create_path_buf() {
        let paths = [
            (Path::new("path").to_path_buf()          , path_buf!["path"              ]),
            (Path::new("path").join("to")             , path_buf!["path", "to"        ]),
            (Path::new("path").join("to").join("file"), path_buf!["path", "to", "file"]),
        ];
        for &(ref correct, ref calculated) in &paths {
            assert_eq!(correct, calculated);
        }
    }

    #[test]
    fn ls_should_return_ok() {
        Helper::create_dirs_and_files();

        let empty_vec: Vec<String> = Vec::new();

        assert_eq!(vec![Helper::d2(), Helper::f1()], ls(Helper::path_to_d1()).unwrap());
        assert_eq!(vec![Helper::d3(), Helper::f2()], ls(Helper::path_to_d2()).unwrap());
        assert_eq!(empty_vec                       , ls(Helper::path_to_d3()).unwrap());

        Helper::remove_dirs_and_files();
    }

    #[test]
    fn is_empty_dir_should_return_true() {
    }
    #[test]
    fn is_empty_dir_should_return_false() {
    }

    #[test]
    fn walk_dir_should_return_b_tree_set() {
    }

    #[test]
    fn dirs_ordered_by_descending_depth_should_return_vec() {
    }
}
<commit_msg>[Test] Add tests for is_empty_dir()<commit_after>extern crate walkdir;

use self::walkdir::{DirEntry as WalkDirEntry, WalkDir, WalkDirIterator};

use std::collections::BTreeSet;
use std::ffi::OsString;
use std::fs;
use std::io::Error as IoError;
use std::path::{Path, PathBuf};
use std::result::Result;

macro_rules! path_buf {
    ($($x: expr),+) => {
        PathBuf::new()
            $(.join($x))+
    };
}

pub fn ls<P: AsRef<Path>>(path: P) -> Result<Vec<String>, IoError> {
    let dirs = try!(fs::read_dir(path));
    let dirs = dirs
        .filter_map(Result::ok)
        .map(|d| d.file_name())
        .map(OsString::into_string)
        .filter_map(Result::ok)
        .collect::<Vec<String>>();
    Ok(dirs)
}

pub fn is_empty_dir<P: AsRef<Path>>(path: P) -> bool {
    match fs::read_dir(path) {
        Ok(rd) => rd.count() == 0,
        Err(_) => false,
    }
}

fn is_hidden_name(file_name: &str) -> bool {
    file_name.starts_with(".") && file_name.len() > 1 && file_name != ".."
}
#[test]
fn is_hidden_name_should_return_true() {
    let file_names = [
        ".a",
        ".ab",
        ".abc",
        "..a",
        "...",
    ];
    for file_name in &file_names {
        assert!(is_hidden_name(file_name));
    }
}
#[test]
fn is_hidden_name_should_return_false() {
    let file_names = [
        "",

        ".",
        "..",
        "a",
        "ab",
        "abc",
    ];
    for file_name in &file_names {
        assert!(!is_hidden_name(file_name));
    }
}

fn is_hidden(entry: &WalkDirEntry) -> bool {
    entry
        .file_name()
        .to_str()
        .map_or(false, is_hidden_name)
}

pub fn walk_dir<P: AsRef<Path>>(root: P) -> BTreeSet<String> {
    let walker = WalkDir::new(root)
        .into_iter()
        .filter_entry(|e| !is_hidden(e))
        .filter_map(Result::ok)
        .filter(|e| !e.file_type().is_dir())
        .collect::<Vec<WalkDirEntry>>();

    walker
        .into_iter()
        .filter_map(|e| e.path().to_str().map(|s| s.to_string()))
        .collect::<BTreeSet<String>>()
}

pub fn dirs_ordered_by_descending_depth<P: AsRef<Path>>(root: P) -> Vec<PathBuf> {
    let mut walker = WalkDir::new(root)
        .into_iter()
        .filter_entry(|e| !is_hidden(e))
        .filter_entry(|e| e.file_type().is_dir())
        .filter_map(Result::ok)
        .collect::<Vec<WalkDirEntry>>();

    walker.sort_by(|l, r| {
        let l_depth = &l.depth();
        let r_depth = &r.depth();
        r_depth.cmp(l_depth)
    });

    walker
        .into_iter()
        .map(|e| e.path().to_path_buf())
        .collect::<Vec<PathBuf>>()
}

#[cfg(test)]
mod tests {
    use super::*;

    use std::fs::{self, File};
    use std::io::Write;
    use std::path::{Path, PathBuf};

    struct Helper;
    impl Helper {
        fn d1() -> String { "directory1".to_string() }
        fn d2() -> String { "directory2".to_string() }
        fn d3() -> String { "directory3".to_string() }

        fn f1() -> String { "file1".to_string() }
        fn f2() -> String { "file2".to_string() }

        fn path_to_d1() -> PathBuf {
            PathBuf::new().join(Self::d1())
        }
        fn path_to_d2() -> PathBuf {
            Self::path_to_d1().join(Self::d2())
        }
        fn path_to_d3() -> PathBuf {
            Self::path_to_d2().join(Self::d3())
        }

        fn path_to_f1() -> PathBuf {
            Self::path_to_d1().join(Self::f1())
        }
        fn path_to_f2() -> PathBuf {
            Self::path_to_d2().join(Self::f2())
        }

        fn remove_dirs_and_files() {
            fs::remove_dir_all(Self::path_to_d1()).ok();
        }

        fn create_dirs_and_files() {
            Self::remove_dirs_and_files();

            fs::create_dir_all(Self::path_to_d3()).ok();

            let mut f = File::create(Self::path_to_f1()).unwrap();
            f.write("\n".as_ref()).ok();
            fs::copy(Self::path_to_f1(), Self::path_to_f2()).ok();
        }
    }

    #[test]
    fn path_buf_macro_should_create_path_buf() {
        let paths = [
            (Path::new("path").to_path_buf()          , path_buf!["path"              ]),
            (Path::new("path").join("to")             , path_buf!["path", "to"        ]),
            (Path::new("path").join("to").join("file"), path_buf!["path", "to", "file"]),
        ];
        for &(ref correct, ref calculated) in &paths {
            assert_eq!(correct, calculated);
        }
    }

    #[test]
    fn ls_should_return_ok() {
        Helper::create_dirs_and_files();

        let empty_vec: Vec<String> = Vec::new();

        assert_eq!(vec![Helper::d2(), Helper::f1()], ls(Helper::path_to_d1()).unwrap());
        assert_eq!(vec![Helper::d3(), Helper::f2()], ls(Helper::path_to_d2()).unwrap());
        assert_eq!(empty_vec                       , ls(Helper::path_to_d3()).unwrap());

        Helper::remove_dirs_and_files();
    }

    #[test]
    fn is_empty_dir_should_return_true() {
        Helper::create_dirs_and_files();

        assert!(is_empty_dir(Helper::path_to_d3()));

        Helper::remove_dirs_and_files();
    }
    #[test]
    fn is_empty_dir_should_return_false() {
        Helper::create_dirs_and_files();

        assert!(!is_empty_dir(Helper::path_to_d1()));
        assert!(!is_empty_dir(Helper::path_to_d2()));

        Helper::remove_dirs_and_files();
    }

    #[test]
    fn walk_dir_should_return_b_tree_set() {
    }

    #[test]
    fn dirs_ordered_by_descending_depth_should_return_vec() {
    }
}
<|endoftext|>


<commit_before>//! Defines a series of convenience modifiers for editing Responses

use std::str::StrAllocating;
use std::io::{File, MemReader};
use std::path::Path;

use modifier::Modifier;
use http::headers::content_type::MediaType;
use content_type::get_content_type;
use {status, Response};

/// A response modifier for setting the content-type header.
pub struct ContentType(pub MediaType);

impl ContentType {
    /// Create a new ContentType modifier from the parts of a content-type header value.
    #[inline]
    pub fn new<S: StrAllocating, S1: StrAllocating>(type_: S, subtype: S1) -> ContentType {
        ContentType(MediaType::new(type_.into_string(), subtype.into_string(), vec![]))
    }
}

impl Modifier<Response> for ContentType {
    #[inline]
    fn modify(self, mut res: Response) -> Response {
        let ContentType(media) = self;
        res.headers.content_type = Some(media);
        res
    }
}

/// A response modifier for seeting the body of a response.
pub struct Body<B: Bodyable>(B);

impl<B: Bodyable> Modifier<Response> for Body<B> {
    #[inline]
    fn modify(self, mut res: Response) -> Response {
        let Body(b) = self;
        b.set_body(&mut res);
        res
    }
}

/// A modifier that can be used to set the body of a response.
pub trait Bodyable {
    /// Set the body of this response, possibly also setting headers.
    fn set_body(self, res: &mut Response);
}

impl Bodyable for Box<Reader + Send> {
    #[inline]
    fn set_body(self, res: &mut Response) {
        res.body = Some(self);
    }
}

impl Bodyable for String {
    #[inline]
    fn set_body(self, res: &mut Response) {
        self.into_bytes().set_body(res);
    }
}

impl Bodyable for Vec<u8> {
    #[inline]
    fn set_body(self, res: &mut Response) {
        res.headers.content_length = Some(self.len());
        res.body = Some(box MemReader::new(self) as Box<Reader + Send>);
    }
}

impl<'a> Bodyable for &'a str {
    #[inline]
    fn set_body(self, res: &mut Response) {
        self.into_string().set_body(res);
    }
}

impl<'a> Bodyable for &'a [u8] {
    #[inline]
    fn set_body(self, res: &mut Response) {
        self.to_vec().set_body(res);
    }
}

impl Bodyable for File {
    #[inline]
    fn set_body(self, res: &mut Response) {
        // Also set the content type.
        res.headers.content_type = self.path().extension_str().and_then(get_content_type);
        res.body = Some(box self as Box<Reader + Send>);
    }
}

impl Bodyable for Path {
    /// Set the body to the contents of the File at this path.
    ///
    /// ## Panics
    ///
    /// Panics if there is no file at the passed-in Path.
    fn set_body(self, res: &mut Response) {
        File::open(&self)
            .ok().expect(format!("No such file: {}", self.display()).as_slice())
            .set_body(res);
    }
}

/// A modifier for setting the status of a response.
pub struct Status(pub status::Status);

impl Modifier<Response> for Status {
    fn modify(self, mut res: Response) -> Response {
        let Status(status) = self;
        res.status = Some(status);
        res
    }
}

<commit_msg>(feat) Added Redirect, a modifier for setting the location header.<commit_after>//! Defines a series of convenience modifiers for editing Responses

use std::str::StrAllocating;
use std::io::{File, MemReader};
use std::path::Path;

use modifier::Modifier;
use http::headers::content_type::MediaType;
use content_type::get_content_type;
use {status, Response, Url};

/// A response modifier for setting the content-type header.
pub struct ContentType(pub MediaType);

impl ContentType {
    /// Create a new ContentType modifier from the parts of a content-type header value.
    #[inline]
    pub fn new<S: StrAllocating, S1: StrAllocating>(type_: S, subtype: S1) -> ContentType {
        ContentType(MediaType::new(type_.into_string(), subtype.into_string(), vec![]))
    }
}

impl Modifier<Response> for ContentType {
    #[inline]
    fn modify(self, mut res: Response) -> Response {
        let ContentType(media) = self;
        res.headers.content_type = Some(media);
        res
    }
}

/// A response modifier for seeting the body of a response.
pub struct Body<B: Bodyable>(B);

impl<B: Bodyable> Modifier<Response> for Body<B> {
    #[inline]
    fn modify(self, mut res: Response) -> Response {
        let Body(b) = self;
        b.set_body(&mut res);
        res
    }
}

/// A modifier that can be used to set the body of a response.
pub trait Bodyable {
    /// Set the body of this response, possibly also setting headers.
    fn set_body(self, res: &mut Response);
}

impl Bodyable for Box<Reader + Send> {
    #[inline]
    fn set_body(self, res: &mut Response) {
        res.body = Some(self);
    }
}

impl Bodyable for String {
    #[inline]
    fn set_body(self, res: &mut Response) {
        self.into_bytes().set_body(res);
    }
}

impl Bodyable for Vec<u8> {
    #[inline]
    fn set_body(self, res: &mut Response) {
        res.headers.content_length = Some(self.len());
        res.body = Some(box MemReader::new(self) as Box<Reader + Send>);
    }
}

impl<'a> Bodyable for &'a str {
    #[inline]
    fn set_body(self, res: &mut Response) {
        self.into_string().set_body(res);
    }
}

impl<'a> Bodyable for &'a [u8] {
    #[inline]
    fn set_body(self, res: &mut Response) {
        self.to_vec().set_body(res);
    }
}

impl Bodyable for File {
    #[inline]
    fn set_body(self, res: &mut Response) {
        // Also set the content type.
        res.headers.content_type = self.path().extension_str().and_then(get_content_type);
        res.body = Some(box self as Box<Reader + Send>);
    }
}

impl Bodyable for Path {
    /// Set the body to the contents of the File at this path.
    ///
    /// ## Panics
    ///
    /// Panics if there is no file at the passed-in Path.
    fn set_body(self, res: &mut Response) {
        File::open(&self)
            .ok().expect(format!("No such file: {}", self.display()).as_slice())
            .set_body(res);
    }
}

/// A modifier for setting the status of a response.
pub struct Status(pub status::Status);

impl Modifier<Response> for Status {
    fn modify(self, mut res: Response) -> Response {
        let Status(status) = self;
        res.status = Some(status);
        res
    }
}

/// A modifier for creating redirect responses.
pub struct Redirect(pub Url);

impl Modifier<Response> for Redirect {
    fn modify(self, mut res: Response) -> Response {
        let Redirect(url) = self;
        res.headers.location = Some(url.into_generic_url());
        res
    }
}

<|endoftext|>