Skip to content

Commit

Permalink
Simplify codebase.
Browse files Browse the repository at this point in the history
  • Loading branch information
KmolYuan committed Apr 18, 2022
1 parent 7e5140c commit c60d05c
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 57 deletions.
5 changes: 2 additions & 3 deletions src/bin/rym.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand All @@ -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),
}
Expand Down
29 changes: 14 additions & 15 deletions src/pack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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},
};
Expand All @@ -17,18 +16,18 @@ 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);
println!("{:?} > {:?}", &path, &dist);
if path.is_dir() {
copy_dir(&path, dist)?;
} else if path.is_file() {
copy(path, dist)?;
fs::copy(path, dist)?;
}
}
Ok(())
Expand All @@ -38,11 +37,11 @@ pub(crate) fn extract<D>(d: D) -> Result<()>
where
D: AsRef<Path>,
{
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();
Expand All @@ -54,7 +53,7 @@ where
P: AsRef<Path>,
{
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);
Expand All @@ -69,26 +68,26 @@ where
P: AsRef<Path>,
D: AsRef<Path>,
{
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('.') {
Expand All @@ -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)?;
Expand Down
32 changes: 11 additions & 21 deletions src/serve/edit_mode.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -26,17 +16,17 @@ impl Actor for Ws {
impl Handler<Event> 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<Result<ws::Message, ws::ProtocolError>> for Ws {
fn handle(&mut self, _item: Result<ws::Message, ws::ProtocolError>, _ctx: &mut Self::Context) {}
fn handle(&mut self, _msg: Result<ws::Message, ws::ProtocolError>, _ctx: &mut Self::Context) {}
}

pub(super) struct Monitor {
last: Duration,
last: SystemTime,
project: String,
listeners: Vec<Addr<Ws>>,
}
Expand All @@ -56,12 +46,12 @@ impl Actor for Monitor {
type Context = Context<Self>;

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;
}
Expand All @@ -79,7 +69,7 @@ impl Handler<Client> for Monitor {

#[derive(Message)]
#[rtype(result = "()")]
struct Event(String);
struct Event;

#[derive(Message)]
#[rtype(result = "()")]
Expand Down
18 changes: 7 additions & 11 deletions src/serve/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -31,11 +27,11 @@ struct Cache {
}

/// Launch function.
pub fn serve<P>(port: u16, path: P, project: &str, edit: bool, open: bool) -> Result<()>
pub fn serve<P>(port: u16, path: P, project: String, edit: bool, open: bool) -> Result<()>
where
P: AsRef<Path>,
{
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())?;
Expand All @@ -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))
Expand Down
10 changes: 3 additions & 7 deletions src/update.rs
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -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() {
Expand Down

0 comments on commit c60d05c

Please sign in to comment.