-
Notifications
You must be signed in to change notification settings - Fork 5.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: fs events #3452
Merged
Merged
feat: fs events #3452
Changes from all commits
Commits
Show all changes
37 commits
Select commit
Hold shift + click to select a range
3385a59
prototype file watching
bartlomieju 775be5a
add test
bartlomieju b2762df
Merge branch 'master' into feat-fs_events
bartlomieju 1ba4acb
fixes for new notify
bartlomieju 551c122
fixes
bartlomieju 05a31a3
remove debounce
bartlomieju 7bb79e6
add EventType enum
bartlomieju 630603f
debug tests
bartlomieju 849ff0b
more debug logs
bartlomieju 4dee826
fmt
bartlomieju 98aa812
Merge branch 'master' into feat-fs_events
bartlomieju e6e264d
Merge branch 'master' into feat-fs_events
bartlomieju 4d67c97
update to latest State
bartlomieju 008a8be
Merge branch 'master' into feat-fs_events
ry ba283b6
WIP
ry e46d2e9
WIP
ry 5bc320e
progress
ry afcc388
fmt
ry 1bf1429
rename to Deno.fsEvents()
ry 100b8f8
fix
ry 5bb2cad
fix
ry 2bdf5a8
fix
ry 2964026
cleanup
ry c7314f2
lint
ry 8d094f2
fmt
ry 72a217b
fix
ry 744f383
manual
ry 62ada69
Merge branch 'master' into feat-fs_events
ry d4bfd61
x
ry ac8e48f
test
ry 22add5e
use AsyncIterableIterator return method to close
ry 648fbac
fix
ry 63da3c7
remove delay
ry b477372
Merge branch 'master' into feat-fs_events
ry b22e093
fix
ry f6efa52
fmt
ry f670d5e
try removing Deno.runTests()
ry File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
// Copyright 2019 the Deno authors. All rights reserved. MIT license. | ||
import { sendSync, sendAsync } from "./dispatch_json.ts"; | ||
import * as dispatch from "./dispatch.ts"; | ||
import { close } from "./files.ts"; | ||
|
||
export interface FsEvent { | ||
kind: "any" | "access" | "create" | "modify" | "remove"; | ||
paths: string[]; | ||
} | ||
|
||
class FsEvents implements AsyncIterableIterator<FsEvent> { | ||
readonly rid: number; | ||
|
||
constructor(paths: string[], options: { recursive: boolean }) { | ||
const { recursive } = options; | ||
this.rid = sendSync(dispatch.OP_FS_EVENTS_OPEN, { recursive, paths }); | ||
} | ||
|
||
async next(): Promise<IteratorResult<FsEvent>> { | ||
return await sendAsync(dispatch.OP_FS_EVENTS_POLL, { | ||
rid: this.rid | ||
}); | ||
} | ||
|
||
async return(value?: FsEvent): Promise<IteratorResult<FsEvent>> { | ||
close(this.rid); | ||
return { value, done: true }; | ||
} | ||
|
||
[Symbol.asyncIterator](): AsyncIterableIterator<FsEvent> { | ||
return this; | ||
} | ||
} | ||
|
||
export function fsEvents( | ||
paths: string | string[], | ||
options = { recursive: true } | ||
): AsyncIterableIterator<FsEvent> { | ||
return new FsEvents(Array.isArray(paths) ? paths : [paths], options); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. | ||
import { testPerm, assert } from "./test_util.ts"; | ||
|
||
// TODO(ry) Add more tests to specify format. | ||
|
||
testPerm({ read: false }, function fsEventsPermissions() { | ||
let thrown = false; | ||
try { | ||
Deno.fsEvents("."); | ||
} catch (err) { | ||
assert(err instanceof Deno.Err.PermissionDenied); | ||
thrown = true; | ||
} | ||
assert(thrown); | ||
}); | ||
|
||
async function getTwoEvents( | ||
iter: AsyncIterableIterator<Deno.FsEvent> | ||
): Promise<Deno.FsEvent[]> { | ||
const events = []; | ||
for await (const event of iter) { | ||
console.log(">>>> event", event); | ||
events.push(event); | ||
if (events.length > 2) break; | ||
} | ||
return events; | ||
} | ||
|
||
testPerm({ read: true, write: true }, async function fsEventsBasic(): Promise< | ||
void | ||
> { | ||
const testDir = await Deno.makeTempDir(); | ||
const iter = Deno.fsEvents(testDir); | ||
|
||
// Asynchornously capture two fs events. | ||
const eventsPromise = getTwoEvents(iter); | ||
|
||
// Make some random file system activity. | ||
const file1 = testDir + "/file1.txt"; | ||
const file2 = testDir + "/file2.txt"; | ||
Deno.writeFileSync(file1, new Uint8Array([0, 1, 2])); | ||
Deno.writeFileSync(file2, new Uint8Array([0, 1, 2])); | ||
|
||
// We should have gotten two fs events. | ||
const events = await eventsPromise; | ||
console.log("events", events); | ||
assert(events.length >= 2); | ||
assert(events[0].kind == "create"); | ||
assert(events[0].paths[0].includes(testDir)); | ||
assert(events[1].kind == "create" || events[1].kind == "modify"); | ||
assert(events[1].paths[0].includes(testDir)); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,129 @@ | ||
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. | ||
use super::dispatch_json::{Deserialize, JsonOp, Value}; | ||
use crate::deno_error::bad_resource; | ||
use crate::ops::json_op; | ||
use crate::state::State; | ||
use deno_core::*; | ||
use futures::future::poll_fn; | ||
use futures::future::FutureExt; | ||
use notify::event::Event as NotifyEvent; | ||
use notify::Error as NotifyError; | ||
use notify::EventKind; | ||
use notify::RecommendedWatcher; | ||
use notify::RecursiveMode; | ||
use notify::Watcher; | ||
use serde::Serialize; | ||
use std::convert::From; | ||
use std::path::PathBuf; | ||
use tokio::sync::mpsc; | ||
|
||
pub fn init(i: &mut Isolate, s: &State) { | ||
i.register_op( | ||
"fs_events_open", | ||
s.core_op(json_op(s.stateful_op(op_fs_events_open))), | ||
); | ||
i.register_op( | ||
"fs_events_poll", | ||
s.core_op(json_op(s.stateful_op(op_fs_events_poll))), | ||
); | ||
} | ||
|
||
struct FsEventsResource { | ||
#[allow(unused)] | ||
watcher: RecommendedWatcher, | ||
receiver: mpsc::Receiver<Result<FsEvent, ErrBox>>, | ||
} | ||
|
||
/// Represents a file system event. | ||
/// | ||
/// We do not use the event directly from the notify crate. We flatten | ||
/// the structure into this simpler structure. We want to only make it more | ||
/// complex as needed. | ||
/// | ||
/// Feel free to expand this struct as long as you can add tests to demonstrate | ||
/// the complexity. | ||
#[derive(Serialize, Debug)] | ||
struct FsEvent { | ||
kind: String, | ||
paths: Vec<PathBuf>, | ||
} | ||
|
||
impl From<NotifyEvent> for FsEvent { | ||
fn from(e: NotifyEvent) -> Self { | ||
let kind = match e.kind { | ||
EventKind::Any => "any", | ||
EventKind::Access(_) => "access", | ||
EventKind::Create(_) => "create", | ||
EventKind::Modify(_) => "modify", | ||
EventKind::Remove(_) => "remove", | ||
EventKind::Other => todo!(), // What's this for? Leaving it out for now. | ||
} | ||
.to_string(); | ||
FsEvent { | ||
kind, | ||
paths: e.paths, | ||
} | ||
} | ||
} | ||
|
||
pub fn op_fs_events_open( | ||
state: &State, | ||
args: Value, | ||
_zero_copy: Option<ZeroCopyBuf>, | ||
) -> Result<JsonOp, ErrBox> { | ||
#[derive(Deserialize)] | ||
struct OpenArgs { | ||
recursive: bool, | ||
paths: Vec<String>, | ||
} | ||
let args: OpenArgs = serde_json::from_value(args)?; | ||
let (sender, receiver) = mpsc::channel::<Result<FsEvent, ErrBox>>(16); | ||
let sender = std::sync::Mutex::new(sender); | ||
let mut watcher: RecommendedWatcher = | ||
Watcher::new_immediate(move |res: Result<NotifyEvent, NotifyError>| { | ||
let res2 = res.map(FsEvent::from).map_err(ErrBox::from); | ||
let mut sender = sender.lock().unwrap(); | ||
futures::executor::block_on(sender.send(res2)).expect("fs events error"); | ||
})?; | ||
let recursive_mode = if args.recursive { | ||
RecursiveMode::Recursive | ||
} else { | ||
RecursiveMode::NonRecursive | ||
}; | ||
for path in &args.paths { | ||
state.check_read(&PathBuf::from(path))?; | ||
watcher.watch(path, recursive_mode)?; | ||
} | ||
let resource = FsEventsResource { watcher, receiver }; | ||
let table = &mut state.borrow_mut().resource_table; | ||
let rid = table.add("fsEvents", Box::new(resource)); | ||
Ok(JsonOp::Sync(json!(rid))) | ||
} | ||
|
||
pub fn op_fs_events_poll( | ||
state: &State, | ||
args: Value, | ||
_zero_copy: Option<ZeroCopyBuf>, | ||
) -> Result<JsonOp, ErrBox> { | ||
#[derive(Deserialize)] | ||
struct PollArgs { | ||
rid: u32, | ||
} | ||
let PollArgs { rid } = serde_json::from_value(args)?; | ||
let state = state.clone(); | ||
let f = poll_fn(move |cx| { | ||
let resource_table = &mut state.borrow_mut().resource_table; | ||
let watcher = resource_table | ||
.get_mut::<FsEventsResource>(rid) | ||
.ok_or_else(bad_resource)?; | ||
watcher | ||
.receiver | ||
.poll_recv(cx) | ||
.map(|maybe_result| match maybe_result { | ||
Some(Ok(value)) => Ok(json!({ "value": value, "done": false })), | ||
ry marked this conversation as resolved.
Show resolved
Hide resolved
|
||
Some(Err(err)) => Err(err), | ||
None => Ok(json!({ "done": true })), | ||
}) | ||
}); | ||
Ok(JsonOp::Async(f.boxed_local())) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This should be written as
for full robustness.