Skip to content

Commit

Permalink
Add option to configure watch debounce time
Browse files Browse the repository at this point in the history
Signed-off-by: trivernis <trivernis@protonmail.com>
  • Loading branch information
Trivernis committed Dec 16, 2020
1 parent b21a6dd commit 31a4abf
Show file tree
Hide file tree
Showing 6 changed files with 63 additions and 46 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "snekdown"
version = "0.31.0"
version = "0.31.1"
authors = ["trivernis <trivernis@protonmail.com>"]
edition = "2018"
license-file = "LICENSE"
Expand Down
33 changes: 28 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,27 +37,50 @@ SUBCOMMANDS:
watch Watch the document and its imports and render on change
```

### Rendering / Watching
### Rendering

```
Parse and render the document
USAGE:
snekdown render [FLAGS] [OPTIONS] <input> <output>
snekdown render [OPTIONS] <input> <output>
FLAGS:
-h, --help Prints help information
--no-cache Don't use the cache
-V, --version Prints version information
-h, --help Prints help information
-V, --version Prints version information
OPTIONS:
-f, --format <format> the output format [default: html]
ARGS:
<input> Path to the input file
<output> Path for the output file
```

### Watching

```
Watch the document and its imports and render on change
USAGE:
snekdown watch [OPTIONS] <input> <output>
FLAGS:
-h, --help Prints help information
-V, --version Prints version information
OPTIONS:
--debounce <debounce> The amount of time in milliseconds to wait after changes before rendering [default:
500]
-f, --format <format> the output format [default: html]
ARGS:
<input> Path to the input file
<output> Path for the output file
```


## Syntax

### Images
Expand Down
36 changes: 20 additions & 16 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,17 @@ use std::sync::mpsc::channel;
use std::time::{Duration, Instant};
use structopt::StructOpt;

#[derive(StructOpt, Debug)]
#[derive(StructOpt, Debug, Clone)]
struct Opt {
#[structopt(subcommand)]
sub_command: SubCommand,
}

#[derive(StructOpt, Debug)]
#[derive(StructOpt, Debug, Clone)]
#[structopt()]
enum SubCommand {
/// Watch the document and its imports and render on change.
Watch(RenderOptions),
Watch(WatchOptions),

/// Parse and render the document.
Render(RenderOptions),
Expand All @@ -35,7 +35,7 @@ enum SubCommand {
ClearCache,
}

#[derive(StructOpt, Debug)]
#[derive(StructOpt, Debug, Clone)]
#[structopt()]
struct RenderOptions {
/// Path to the input file
Expand All @@ -49,10 +49,17 @@ struct RenderOptions {
/// the output format
#[structopt(short, long, default_value = "html")]
format: String,
}

#[derive(StructOpt, Debug, Clone)]
#[structopt()]
struct WatchOptions {
/// The amount of time in milliseconds to wait after changes before rendering
#[structopt(long, default_value = "500")]
debounce: u64,

/// Don't use the cache
#[structopt(long)]
no_cache: bool,
#[structopt(flatten)]
render_options: RenderOptions,
}

fn main() {
Expand Down Expand Up @@ -101,16 +108,17 @@ fn get_level_style(level: Level) -> colored::Color {
}

/// Watches a file with all of its imports and renders on change
fn watch(opt: &RenderOptions) {
let parser = render(opt);
fn watch(opt: &WatchOptions) {
let parser = render(&opt.render_options);
let (tx, rx) = channel();
let mut watcher = watcher(tx, Duration::from_millis(250)).unwrap();
let mut watcher = watcher(tx, Duration::from_millis(opt.debounce)).unwrap();

for path in parser.get_paths() {
watcher.watch(path, RecursiveMode::NonRecursive).unwrap();
}
while let Ok(_) = rx.recv() {
println!("---");
let parser = render(opt);
let parser = render(&opt.render_options);
for path in parser.get_paths() {
watcher.watch(path, RecursiveMode::NonRecursive).unwrap();
}
Expand All @@ -129,11 +137,7 @@ fn render(opt: &RenderOptions) -> Parser {
}
let start = Instant::now();

let mut parser = Parser::with_defaults(
ParserOptions::default()
.add_path(opt.input.clone())
.use_cache(!opt.no_cache),
);
let mut parser = Parser::with_defaults(ParserOptions::default().add_path(opt.input.clone()));
let document = parser.parse();

log::info!("Parsing + Processing took: {:?}", start.elapsed());
Expand Down
31 changes: 12 additions & 19 deletions src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,6 @@ impl ParserOptions {

self
}

/// If external sources should be cached when after downloaded
pub fn use_cache(self, value: bool) -> Self {
self.document.downloads.lock().use_cache = value;

self
}
}

pub struct Parser {
Expand Down Expand Up @@ -159,18 +152,6 @@ impl Parser {
);
return Err(self.ctm.assert_error(None));
}
{
let mut paths = self.options.paths.lock().unwrap();
if paths.iter().find(|item| **item == path) != None {
log::warn!(
"Import of \"{}\" failed: Already imported.\n\t--> {}\n",
path.to_str().unwrap(),
self.get_position_string(),
);
return Err(self.ctm.assert_error(None));
}
paths.push(path.clone());
}
let anchor = Arc::new(RwLock::new(ImportAnchor::new()));
let anchor_clone = Arc::clone(&anchor);
let wg = self.wg.clone();
Expand Down Expand Up @@ -277,6 +258,18 @@ impl Parser {
}
}
}
{
let mut paths = self.options.paths.lock().unwrap();
if paths.iter().find(|item| **item == path).is_some() {
log::warn!(
"Import of \"{}\" failed: Already imported.\n\t--> {}\n",
path.to_str().unwrap(),
self.get_position_string(),
);
return ImportType::None;
}
paths.push(path.clone());
}
match args.get("type").map(|e| e.as_string().to_lowercase()) {
Some(s) if s == "stylesheet".to_string() => {
ImportType::Stylesheet(self.import_stylesheet(path))
Expand Down
5 changes: 1 addition & 4 deletions src/utils/downloads.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,19 @@ use std::sync::Arc;
#[derive(Clone, Debug)]
pub struct DownloadManager {
downloads: Vec<Arc<Mutex<PendingDownload>>>,
pub use_cache: bool,
}

impl DownloadManager {
/// Creates a new download manager
pub fn new() -> Self {
Self {
downloads: Vec::new(),
use_cache: true,
}
}

/// Adds a new pending download
pub fn add_download(&mut self, path: String) -> Arc<Mutex<PendingDownload>> {
let mut download = PendingDownload::new(path.clone());
download.use_cache = self.use_cache;
let download = PendingDownload::new(path.clone());
let pending = Arc::new(Mutex::new(download));
self.downloads.push(Arc::clone(&pending));
log::debug!("Added download {}", path);
Expand Down

0 comments on commit 31a4abf

Please sign in to comment.