files.rs 5.5 KB
Newer Older
B
Bartek Iwańczuk 已提交
1
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
R
Ryan Dahl 已提交
2
use super::dispatch_flatbuffers::serialize_response;
3
use super::dispatch_json::{Deserialize, JsonOp, Value};
R
Ryan Dahl 已提交
4
use super::utils::*;
B
Bartek Iwańczuk 已提交
5 6 7 8 9
use crate::deno_error;
use crate::fs as deno_fs;
use crate::msg;
use crate::resources;
use crate::state::ThreadSafeState;
10
use crate::tokio_write;
B
Bartek Iwańczuk 已提交
11 12 13 14 15 16 17
use deno::*;
use flatbuffers::FlatBufferBuilder;
use futures::Future;
use std;
use std::convert::From;
use tokio;

18 19 20 21 22 23 24 25
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct OpenArgs {
  promise_id: Option<u64>,
  filename: String,
  mode: String,
}

B
Bartek Iwańczuk 已提交
26 27
pub fn op_open(
  state: &ThreadSafeState,
28 29 30 31 32 33
  args: Value,
  _zero_copy: Option<PinnedBuf>,
) -> Result<JsonOp, ErrBox> {
  let args: OpenArgs = serde_json::from_value(args)?;
  let (filename, filename_) = deno_fs::resolve_from_cwd(&args.filename)?;
  let mode = args.mode.as_ref();
B
Bartek Iwańczuk 已提交
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

  let mut open_options = tokio::fs::OpenOptions::new();

  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);
    }
    &_ => {
      panic!("Unknown file open mode.");
    }
  }

  match mode {
    "r" => {
      state.check_read(&filename_)?;
    }
    "w" | "a" | "x" => {
      state.check_write(&filename_)?;
    }
    &_ => {
      state.check_read(&filename_)?;
      state.check_write(&filename_)?;
    }
  }

84
  let is_sync = args.promise_id.is_none();
B
Bartek Iwańczuk 已提交
85 86 87
  let op = open_options.open(filename).map_err(ErrBox::from).and_then(
    move |fs_file| {
      let resource = resources::add_fs_file(fs_file);
88
      futures::future::ok(json!(resource.rid))
B
Bartek Iwańczuk 已提交
89 90
    },
  );
91 92

  if is_sync {
B
Bartek Iwańczuk 已提交
93
    let buf = op.wait()?;
94
    Ok(JsonOp::Sync(buf))
B
Bartek Iwańczuk 已提交
95
  } else {
96
    Ok(JsonOp::Async(Box::new(op)))
B
Bartek Iwańczuk 已提交
97 98 99
  }
}

100 101 102 103 104
#[derive(Deserialize)]
struct CloseArgs {
  rid: i32,
}

B
Bartek Iwańczuk 已提交
105 106
pub fn op_close(
  _state: &ThreadSafeState,
107 108 109 110 111 112
  args: Value,
  _zero_copy: Option<PinnedBuf>,
) -> Result<JsonOp, ErrBox> {
  let args: CloseArgs = serde_json::from_value(args)?;

  match resources::lookup(args.rid as u32) {
B
Bartek Iwańczuk 已提交
113 114 115
    None => Err(deno_error::bad_resource()),
    Some(resource) => {
      resource.close();
116
      Ok(JsonOp::Sync(json!({})))
B
Bartek Iwańczuk 已提交
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
pub fn op_read(
  _state: &ThreadSafeState,
  base: &msg::Base<'_>,
  data: Option<PinnedBuf>,
) -> CliOpResult {
  let cmd_id = base.cmd_id();
  let inner = base.inner_as_read().unwrap();
  let rid = inner.rid();

  match resources::lookup(rid) {
    None => Err(deno_error::bad_resource()),
    Some(resource) => {
      let op = tokio::io::read(resource, data.unwrap())
        .map_err(ErrBox::from)
        .and_then(move |(_resource, _buf, nread)| {
          let builder = &mut FlatBufferBuilder::new();
          let inner = msg::ReadRes::create(
            builder,
            &msg::ReadResArgs {
              nread: nread as u32,
              eof: nread == 0,
            },
          );
          Ok(serialize_response(
            cmd_id,
            builder,
            msg::BaseArgs {
              inner: Some(inner.as_union_value()),
              inner_type: msg::Any::ReadRes,
              ..Default::default()
            },
          ))
        });
      if base.sync() {
        let buf = op.wait()?;
        Ok(Op::Sync(buf))
      } else {
        Ok(Op::Async(Box::new(op)))
      }
    }
  }
}

pub fn op_write(
  _state: &ThreadSafeState,
  base: &msg::Base<'_>,
  data: Option<PinnedBuf>,
) -> CliOpResult {
  let cmd_id = base.cmd_id();
  let inner = base.inner_as_write().unwrap();
  let rid = inner.rid();

  match resources::lookup(rid) {
    None => Err(deno_error::bad_resource()),
    Some(resource) => {
      let op = tokio_write::write(resource, data.unwrap())
        .map_err(ErrBox::from)
        .and_then(move |(_resource, _buf, nwritten)| {
          let builder = &mut FlatBufferBuilder::new();
          let inner = msg::WriteRes::create(
            builder,
            &msg::WriteResArgs {
              nbyte: nwritten as u32,
            },
          );
          Ok(serialize_response(
            cmd_id,
            builder,
            msg::BaseArgs {
              inner: Some(inner.as_union_value()),
              inner_type: msg::Any::WriteRes,
              ..Default::default()
            },
          ))
        });
      if base.sync() {
        let buf = op.wait()?;
        Ok(Op::Sync(buf))
      } else {
        Ok(Op::Async(Box::new(op)))
      }
    }
  }
}

206 207 208 209 210 211 212 213 214
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct SeekArgs {
  promise_id: Option<u64>,
  rid: i32,
  offset: i32,
  whence: i32,
}

B
Bartek Iwańczuk 已提交
215 216
pub fn op_seek(
  _state: &ThreadSafeState,
217 218 219 220
  args: Value,
  _zero_copy: Option<PinnedBuf>,
) -> Result<JsonOp, ErrBox> {
  let args: SeekArgs = serde_json::from_value(args)?;
B
Bartek Iwańczuk 已提交
221

222
  match resources::lookup(args.rid as u32) {
B
Bartek Iwańczuk 已提交
223 224
    None => Err(deno_error::bad_resource()),
    Some(resource) => {
225 226 227
      let op = resources::seek(resource, args.offset, args.whence as u32)
        .and_then(move |_| futures::future::ok(json!({})));
      if args.promise_id.is_none() {
B
Bartek Iwańczuk 已提交
228
        let buf = op.wait()?;
229
        Ok(JsonOp::Sync(buf))
B
Bartek Iwańczuk 已提交
230
      } else {
231
        Ok(JsonOp::Async(Box::new(op)))
B
Bartek Iwańczuk 已提交
232 233 234 235
      }
    }
  }
}