From c60d05cb8c5ce48cb44ec6766533a166d3a82fe5 Mon Sep 17 00:00:00 2001 From: KmolYuan Date: Mon, 18 Apr 2022 19:22:24 +0800 Subject: [PATCH] Simplify codebase. --- src/bin/rym.rs | 5 ++--- src/pack.rs | 29 ++++++++++++++--------------- src/serve/edit_mode.rs | 32 +++++++++++--------------------- src/serve/mod.rs | 18 +++++++----------- src/update.rs | 10 +++------- 5 files changed, 37 insertions(+), 57 deletions(-) diff --git a/src/bin/rym.rs b/src/bin/rym.rs index 08f4209..4df1de0 100644 --- a/src/bin/rym.rs +++ b/src/bin/rym.rs @@ -73,8 +73,7 @@ enum Subcommand { } fn main() -> Result<(), Error> { - let args = Entry::parse(); - match args.subcommand { + match Entry::parse().subcommand { Subcommand::Update => update(), Subcommand::New { dir } => blank(dir, true), Subcommand::Init { dir } => blank(dir, false), @@ -84,7 +83,7 @@ fn main() -> Result<(), Error> { name, edit, no_open, - } => serve(port, dir, &name, edit, !no_open), + } => serve(port, dir, name, edit, !no_open), Subcommand::Fmt { dir, name, dry_run } => fmt(dir, dry_run, &name), Subcommand::Pack { dir, name, out } => pack(dir, out, &name), } diff --git a/src/pack.rs b/src/pack.rs index fcd871d..b73c9fa 100644 --- a/src/pack.rs +++ b/src/pack.rs @@ -3,8 +3,7 @@ use crate::{ update::{archive, update}, }; use std::{ - env::{current_exe, set_current_dir}, - fs::{copy, create_dir, read_dir, read_to_string, remove_dir_all, rename, write, File}, + fs, io::Result, path::{Path, PathBuf}, }; @@ -17,10 +16,10 @@ where { let path = path.as_ref(); let dist = dist.as_ref(); - for entry in read_dir(path)? { + for entry in fs::read_dir(path)? { let path = entry?.path(); if !dist.is_dir() { - create_dir(dist)?; + fs::create_dir(dist)?; } let file_name = path.file_name().unwrap(); let dist = dist.join(file_name); @@ -28,7 +27,7 @@ where if path.is_dir() { copy_dir(&path, dist)?; } else if path.is_file() { - copy(path, dist)?; + fs::copy(path, dist)?; } } Ok(()) @@ -38,11 +37,11 @@ pub(crate) fn extract(d: D) -> Result<()> where D: AsRef, { - let path = current_exe()?.with_file_name(concat!(archive!(), ".zip")); + let path = std::env::current_exe()?.with_file_name(concat!(archive!(), ".zip")); if !path.exists() { update()?; } - ZipArchive::new(File::open(path)?) + ZipArchive::new(fs::File::open(path)?) .unwrap() .extract(d.as_ref()) .unwrap(); @@ -54,7 +53,7 @@ where P: AsRef, { let mut list = Vec::new(); - for entry in read_dir(path)? { + for entry in fs::read_dir(path)? { let path = entry?.path(); if !path.file_name().unwrap().to_str().unwrap().starts_with('.') { list.push(path); @@ -69,26 +68,26 @@ where P: AsRef, D: AsRef, { - set_current_dir(path.as_ref())?; + std::env::set_current_dir(path.as_ref())?; let dist = dist.as_ref(); if dist.is_dir() { println!("Remove {:?}", dist); - remove_dir_all(dist)?; + fs::remove_dir_all(dist)?; } extract(".")?; pack_inner(project).map_err(|e| { - remove_dir_all(archive!()).unwrap_or_default(); + fs::remove_dir_all(archive!()).unwrap_or_default(); e })?; - rename(archive!(), dist)?; + fs::rename(archive!(), dist)?; println!("Done"); Ok(()) } fn pack_inner(project: &str) -> Result<()> { let archive = Path::new(archive!()); - let contents = load(&read_to_string(project)?, "", false)?; - write(archive.join("index.html"), &contents)?; + let contents = load(&fs::read_to_string(project)?, "", false)?; + fs::write(archive.join("index.html"), &contents)?; for assets in listdir(".")? { let name = assets.file_name().unwrap().to_str().unwrap(); if name == archive!() || name.starts_with('.') { @@ -97,7 +96,7 @@ fn pack_inner(project: &str) -> Result<()> { if assets.is_dir() { let dist = archive.join(name); if !dist.is_dir() { - create_dir(&dist)?; + fs::create_dir(&dist)?; } println!("{:?} > {:?}", &assets, &dist); copy_dir(assets, dist)?; diff --git a/src/serve/edit_mode.rs b/src/serve/edit_mode.rs index 10101b4..cb59165 100644 --- a/src/serve/edit_mode.rs +++ b/src/serve/edit_mode.rs @@ -1,20 +1,10 @@ use actix::{Actor, Addr, AsyncContext, Context, Handler, Message, StreamHandler}; use actix_web::{get, web, Error, HttpRequest, HttpResponse}; use actix_web_actors::ws; -use std::{ - fs::metadata, - time::{Duration, SystemTime}, -}; +use std::time::{Duration, SystemTime}; -const INTERVAL: Duration = Duration::from_millis(500); - -fn file_date(path: &str) -> Duration { - metadata(path) - .unwrap() - .modified() - .unwrap() - .duration_since(SystemTime::UNIX_EPOCH) - .unwrap() +fn file_date(path: &str) -> SystemTime { + std::fs::metadata(path).unwrap().modified().unwrap() } struct Ws; @@ -26,17 +16,17 @@ impl Actor for Ws { impl Handler for Ws { type Result = (); - fn handle(&mut self, msg: Event, ctx: &mut Self::Context) { - ctx.text(msg.0); + fn handle(&mut self, _msg: Event, ctx: &mut Self::Context) { + ctx.text("changed!"); } } impl StreamHandler> for Ws { - fn handle(&mut self, _item: Result, _ctx: &mut Self::Context) {} + fn handle(&mut self, _msg: Result, _ctx: &mut Self::Context) {} } pub(super) struct Monitor { - last: Duration, + last: SystemTime, project: String, listeners: Vec>, } @@ -56,12 +46,12 @@ impl Actor for Monitor { type Context = Context; fn started(&mut self, ctx: &mut Self::Context) { - ctx.run_interval(INTERVAL, |act, _| { + ctx.run_interval(Duration::from_millis(500), |act, _| { let last = file_date(&act.project); if last != act.last { // Broadcast - for l in &act.listeners { - l.do_send(Event("changed!".to_string())); + for listener in &act.listeners { + listener.do_send(Event); } act.last = last; } @@ -79,7 +69,7 @@ impl Handler for Monitor { #[derive(Message)] #[rtype(result = "()")] -struct Event(String); +struct Event; #[derive(Message)] #[rtype(result = "()")] diff --git a/src/serve/mod.rs b/src/serve/mod.rs index fc52216..5ef9307 100644 --- a/src/serve/mod.rs +++ b/src/serve/mod.rs @@ -5,12 +5,8 @@ use crate::{ update::archive, }; use actix_files::Files; -use actix_web::{ - web::{self, Data}, - App, HttpServer, -}; +use actix_web::{web, App, HttpServer}; use std::{ - env::set_current_dir, fs::{canonicalize, read_to_string}, io::{Error, ErrorKind, Result}, path::Path, @@ -31,11 +27,11 @@ struct Cache { } /// Launch function. -pub fn serve

(port: u16, path: P, project: &str, edit: bool, open: bool) -> Result<()> +pub fn serve

(port: u16, path: P, project: String, edit: bool, open: bool) -> Result<()> where P: AsRef, { - set_current_dir(path.as_ref())?; + std::env::set_current_dir(path.as_ref())?; let temp = TempDir::new().map_err(|s| Error::new(ErrorKind::PermissionDenied, s))?; // Expand Reveal.js extract(temp.path())?; @@ -47,20 +43,20 @@ where println!("Edit mode: {}", edit); println!("Press Ctrl+C to close the server..."); let assets = listdir(".")?; - let cache = Data::new(Cache { - project: project.to_string(), + let cache = web::Data::new(Cache { doc: if edit { String::new() } else { - load(&read_to_string(project)?, "/static/", edit).unwrap_or_else(error_page) + load(&read_to_string(&project)?, "/static/", edit).unwrap_or_else(error_page) }, + project, help_doc: load(HELP_DOC, "/static/", false)?, reload: edit, }); let server = HttpServer::new(move || { let app = App::new() .app_data(cache.clone()) - .app_data(Data::new(Monitor::new(cache.project.clone()))) + .app_data(web::Data::new(Monitor::new(cache.project.clone()))) .service(site::index) .service(site::help_page) .default_service(web::route().to(site::not_found)) diff --git a/src/update.rs b/src/update.rs index f497780..9e71773 100644 --- a/src/update.rs +++ b/src/update.rs @@ -1,8 +1,4 @@ -use std::{ - env::current_exe, - fs::File, - io::{Cursor, Result}, -}; +use std::io::{Cursor, Result}; use zip::{ZipArchive, ZipWriter}; macro_rules! archive { @@ -30,9 +26,9 @@ pub fn update() -> Result<()> { .await .unwrap() }); - let archive = current_exe()?.with_file_name(concat!(archive!(), ".zip")); + let archive = std::env::current_exe()?.with_file_name(concat!(archive!(), ".zip")); let mut r = ZipArchive::new(Cursor::new(b))?; - let mut w = ZipWriter::new(File::create(archive)?); + let mut w = ZipWriter::new(std::fs::File::create(archive)?); for i in 0..r.len() { let file = r.by_index(i)?; if file.is_dir() {