🏡 index : ~doyle/bin.git

author Jordan Johnson-Doyle <jordan@doyle.la> 2019-02-15 22:01:22.0 +00:00:00
committer Jordan Johnson-Doyle <jordan@doyle.la> 2019-02-15 22:01:22.0 +00:00:00
commit
09e411739a043ba69c9527cb9a97b3bde34361ef [patch]
tree
a974e77eaad7a59a8674c566218bb94c0ad1f9fe
parent
b32010f9051cc328e4f20000d3b2166f6f4ef272
download
09e411739a043ba69c9527cb9a97b3bde34361ef.tar.gz

Run cargo fmt



Diff

 src/highlight.rs | 11 +++++++----
 src/io.rs        | 34 ++++++++++++++++++++++++++--------
 src/main.rs      | 32 ++++++++++++++++----------------
 src/params.rs    | 16 +++++++++++-----
 4 files changed, 60 insertions(+), 33 deletions(-)

diff --git a/src/highlight.rs b/src/highlight.rs
index e0e5ae1..0dc3cba 100644
--- a/src/highlight.rs
+++ b/src/highlight.rs
@@ -1,9 +1,9 @@
extern crate syntect;

use syntect::parsing::SyntaxSet;
use syntect::highlighting::ThemeSet;
use syntect::easy::HighlightLines;
use syntect::highlighting::ThemeSet;
use syntect::html::{styled_line_to_highlighted_html, IncludeBackground};
use syntect::parsing::SyntaxSet;

/// Takes the content of a paste and the extension passed in by the viewer and will return the content
/// highlighted in the appropriate format in HTML.
@@ -19,5 +19,8 @@ pub fn highlight(content: &str, ext: &str) -> Option<String> {
    let mut h = HighlightLines::new(syntax, &TS.themes["base16-ocean.dark"]);
    let regions = h.highlight(content, &SS);

    Some(styled_line_to_highlighted_html(&regions[..], IncludeBackground::No))
}
\ No newline at end of file
    Some(styled_line_to_highlighted_html(
        &regions[..],
        IncludeBackground::No,
    ))
}
diff --git a/src/io.rs b/src/io.rs
index 31ce6f2..8f66f3a 100644
--- a/src/io.rs
+++ b/src/io.rs
@@ -2,18 +2,22 @@ extern crate gpw;
extern crate linked_hash_map;
extern crate rand;

use rand::{Rng, thread_rng};
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};

use linked_hash_map::LinkedHashMap;

use std::sync::RwLock;
use std::env;
use std::cell::RefCell;
use std::env;
use std::sync::RwLock;

lazy_static! {
    static ref ENTRIES: RwLock<LinkedHashMap<String, String>> = RwLock::new(LinkedHashMap::new());
    static ref BUFFER_SIZE: usize = env::var("BIN_BUFFER_SIZE").map(|f| f.parse::<usize>().expect("Failed to parse value of BIN_BUFFER_SIZE")).unwrap_or(1000usize);
    static ref BUFFER_SIZE: usize = env::var("BIN_BUFFER_SIZE")
        .map(|f| f
            .parse::<usize>()
            .expect("Failed to parse value of BIN_BUFFER_SIZE"))
        .unwrap_or(1000usize);
}

/// Ensures `ENTRIES` is less than the size of `BIN_BUFFER_SIZE`. If it isn't then
@@ -37,18 +41,32 @@ fn purge_old() {
/// Generates a 'pronounceable' random ID using gpw
pub fn generate_id() -> String {
    thread_local!(static KEYGEN: RefCell<gpw::PasswordGenerator> = RefCell::new(gpw::PasswordGenerator::default()));
    KEYGEN.with(|k| k.borrow_mut().next().unwrap_or_else(|| thread_rng().sample_iter(&Alphanumeric).take(6).collect::<String>()))
    KEYGEN.with(|k| {
        k.borrow_mut().next().unwrap_or_else(|| {
            thread_rng()
                .sample_iter(&Alphanumeric)
                .take(6)
                .collect::<String>()
        })
    })
}

/// Stores a paste under the given id
pub fn store_paste(id: String, content: String) {
    purge_old();
    ENTRIES.write().unwrap_or_else(|p| p.into_inner()).insert(id, content);
    ENTRIES
        .write()
        .unwrap_or_else(|p| p.into_inner())
        .insert(id, content);
}

/// Get a paste by id.
///
/// Returns `None` if the paste doesn't exist.
pub fn get_paste(id: &str) -> Option<String> {
    ENTRIES.read().unwrap_or_else(|p| p.into_inner()).get(id).cloned()
}
\ No newline at end of file
    ENTRIES
        .read()
        .unwrap_or_else(|p| p.into_inner())
        .get(id)
        .cloned()
}
diff --git a/src/main.rs b/src/main.rs
index bbefa83..4da138b 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,29 +1,31 @@
#![feature(proc_macro_hygiene, decl_macro)]
#![feature(type_alias_enum_variants)]

#[macro_use] extern crate lazy_static;
#[macro_use]
extern crate lazy_static;

#[macro_use] extern crate rocket;
#[macro_use]
extern crate rocket;

extern crate askama;
extern crate askama_escape;

mod io;
mod highlight;
mod io;
mod params;

use io::{store_paste, get_paste, generate_id};
use highlight::highlight;
use params::{IsPlaintextRequest, HostHeader};
use io::{generate_id, get_paste, store_paste};
use params::{HostHeader, IsPlaintextRequest};

use askama::Template;
use askama_escape::{MarkupDisplay, Html};
use askama_escape::{Html, MarkupDisplay};

use rocket::Data;
use rocket::http::{ContentType, Status};
use rocket::request::Form;
use rocket::response::Redirect;
use rocket::response::content::Content;
use rocket::http::{ContentType, Status};
use rocket::response::Redirect;
use rocket::Data;

use std::io::Read;

@@ -40,14 +42,13 @@ fn index() -> Index {
    Index {}
}


///
/// Submit Paste
///

#[derive(FromForm)]
struct IndexForm {
    val: String
    val: String,
}

#[post("/", data = "<input>")]
@@ -67,11 +68,10 @@ fn submit_raw(input: Data, host: HostHeader) -> std::io::Result<String> {

    match *host {
        Some(host) => Ok(format!("https://{}/{}", host, id)),
        None => Ok(id)
        None => Ok(id),
    }
}


///
/// Show paste page
///
@@ -100,17 +100,17 @@ fn render(key: String, plaintext: IsPlaintextRequest) -> Result<Content<String>,
                None => MarkupDisplay::new_unsafe(entry, Html),
                Some(extension) => highlight(&entry, extension)
                    .map(|h| MarkupDisplay::new_safe(h, Html))
                    .ok_or_else(|| Status::NotFound)?
                    .ok_or_else(|| Status::NotFound)?,
            },
        };

        template.render()
        template
            .render()
            .map(|html| Content(ContentType::HTML, html))
            .map_err(|_| Status::InternalServerError)
    }
}


fn main() {
    rocket::ignite()
        .mount("/", routes![index, submit, submit_raw, render])
diff --git a/src/params.rs b/src/params.rs
index 7e8902a..1d6ceb1 100644
--- a/src/params.rs
+++ b/src/params.rs
@@ -1,7 +1,7 @@
use std::ops::Deref;

use rocket::Request;
use rocket::request::{FromRequest, Outcome};
use rocket::Request;

/// Holds a value that determines whether or not this request wanted a plaintext response.
///
@@ -27,9 +27,15 @@ impl<'a, 'r> FromRequest<'a, 'r> for IsPlaintextRequest {
            }
        }

        match request.headers().get_one("User-Agent").and_then(|u| u.splitn(2, '/').next()) {
            None | Some("Wget") | Some("curl") | Some("HTTPie") => Outcome::Success(IsPlaintextRequest(true)),
            _ => Outcome::Success(IsPlaintextRequest(false))
        match request
            .headers()
            .get_one("User-Agent")
            .and_then(|u| u.splitn(2, '/').next())
        {
            None | Some("Wget") | Some("curl") | Some("HTTPie") => {
                Outcome::Success(IsPlaintextRequest(true))
            }
            _ => Outcome::Success(IsPlaintextRequest(false)),
        }
    }
}
@@ -54,4 +60,4 @@ impl<'a, 'r> FromRequest<'a, 'r> for HostHeader<'a> {
    fn from_request(request: &'a Request<'r>) -> Outcome<HostHeader<'a>, ()> {
        Outcome::Success(HostHeader(request.headers().get_one("Host")))
    }
}
\ No newline at end of file
}