forked from denoland/deno
/
files.rs
217 lines (197 loc) · 5.06 KB
/
files.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
use super::dispatch_json::{Deserialize, JsonOp, Value};
use super::io::{FileMetadata, StreamResource};
use crate::fs as deno_fs;
use crate::op_error::OpError;
use crate::state::State;
use deno_core::*;
use futures::future::FutureExt;
use std;
use std::convert::From;
use std::io::SeekFrom;
use std::path::Path;
use tokio;
pub fn init(i: &mut Isolate, s: &State) {
i.register_op("op_open", s.stateful_json_op(op_open));
i.register_op("op_close", s.stateful_json_op(op_close));
i.register_op("op_seek", s.stateful_json_op(op_seek));
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct OpenArgs {
promise_id: Option<u64>,
path: String,
options: Option<OpenOptions>,
mode: Option<String>,
}
#[derive(Deserialize, Default, Debug)]
#[serde(rename_all = "camelCase")]
#[serde(default)]
struct OpenOptions {
read: bool,
write: bool,
create: bool,
truncate: bool,
append: bool,
create_new: bool,
}
fn op_open(
state: &State,
args: Value,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<JsonOp, OpError> {
let args: OpenArgs = serde_json::from_value(args)?;
let path = deno_fs::resolve_from_cwd(Path::new(&args.path))?;
let state_ = state.clone();
let mut open_options = tokio::fs::OpenOptions::new();
if let Some(options) = args.options {
if options.read {
state.check_read(&path)?;
}
if options.write || options.append {
state.check_write(&path)?;
}
open_options
.read(options.read)
.create(options.create)
.write(options.write)
.truncate(options.truncate)
.append(options.append)
.create_new(options.create_new);
} else if let Some(mode) = args.mode {
let mode = mode.as_ref();
match mode {
"r" => {
state.check_read(&path)?;
}
"w" | "a" | "x" => {
state.check_write(&path)?;
}
&_ => {
state.check_read(&path)?;
state.check_write(&path)?;
}
};
match mode {
"r" => {
open_options.read(true);
}
"r+" => {
open_options.read(true).write(true);
}
"w" => {
open_options.create(true).write(true).truncate(true);
}
"w+" => {
open_options
.read(true)
.create(true)
.write(true)
.truncate(true);
}
"a" => {
open_options.create(true).append(true);
}
"a+" => {
open_options.read(true).create(true).append(true);
}
"x" => {
open_options.create_new(true).write(true);
}
"x+" => {
open_options.create_new(true).read(true).write(true);
}
&_ => {
// TODO: this should be type error
return Err(OpError::other("Unknown open mode.".to_string()));
}
}
} else {
return Err(OpError::other(
"Open requires either mode or options.".to_string(),
));
};
let is_sync = args.promise_id.is_none();
let fut = async move {
let fs_file = open_options.open(path).await?;
let mut state = state_.borrow_mut();
let rid = state.resource_table.add(
"fsFile",
Box::new(StreamResource::FsFile(fs_file, FileMetadata::default())),
);
Ok(json!(rid))
};
if is_sync {
let buf = futures::executor::block_on(fut)?;
Ok(JsonOp::Sync(buf))
} else {
Ok(JsonOp::Async(fut.boxed_local()))
}
}
#[derive(Deserialize)]
struct CloseArgs {
rid: i32,
}
fn op_close(
state: &State,
args: Value,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<JsonOp, OpError> {
let args: CloseArgs = serde_json::from_value(args)?;
let mut state = state.borrow_mut();
state
.resource_table
.close(args.rid as u32)
.ok_or_else(OpError::bad_resource_id)?;
Ok(JsonOp::Sync(json!({})))
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct SeekArgs {
promise_id: Option<u64>,
rid: i32,
offset: i32,
whence: i32,
}
fn op_seek(
state: &State,
args: Value,
_zero_copy: Option<ZeroCopyBuf>,
) -> Result<JsonOp, OpError> {
let args: SeekArgs = serde_json::from_value(args)?;
let rid = args.rid as u32;
let offset = args.offset;
let whence = args.whence as u32;
// Translate seek mode to Rust repr.
let seek_from = match whence {
0 => SeekFrom::Start(offset as u64),
1 => SeekFrom::Current(i64::from(offset)),
2 => SeekFrom::End(i64::from(offset)),
_ => {
return Err(OpError::type_error(format!(
"Invalid seek mode: {}",
whence
)));
}
};
let state = state.borrow();
let resource = state
.resource_table
.get::<StreamResource>(rid)
.ok_or_else(OpError::bad_resource_id)?;
let tokio_file = match resource {
StreamResource::FsFile(ref file, _) => file,
_ => return Err(OpError::bad_resource_id()),
};
let mut file = futures::executor::block_on(tokio_file.try_clone())?;
let fut = async move {
let pos = file.seek(seek_from).await?;
Ok(json!(pos))
};
if args.promise_id.is_none() {
let buf = futures::executor::block_on(fut)?;
Ok(JsonOp::Sync(buf))
} else {
Ok(JsonOp::Async(fut.boxed_local()))
}
}