summaryrefslogtreecommitdiff
path: root/cli/ops/os.rs
blob: 8def5ac1ef444123b2862ac784fe01a673b736d1 (plain)
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
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
use super::dispatch_json::{Deserialize, JsonOp, Value};
use crate::ops::json_op;
use crate::state::State;
use atty;
use deno_core::*;
use std::collections::HashMap;
use std::env;
use std::io::{Error, ErrorKind};
use sys_info;
use url::Url;

pub fn init(i: &mut Isolate, s: &State) {
  i.register_op("exit", s.core_op(json_op(s.stateful_op(op_exit))));
  i.register_op("is_tty", s.core_op(json_op(s.stateful_op(op_is_tty))));
  i.register_op("env", s.core_op(json_op(s.stateful_op(op_env))));
  i.register_op("exec_path", s.core_op(json_op(s.stateful_op(op_exec_path))));
  i.register_op("set_env", s.core_op(json_op(s.stateful_op(op_set_env))));
  i.register_op("get_env", s.core_op(json_op(s.stateful_op(op_get_env))));
  i.register_op("get_dir", s.core_op(json_op(s.stateful_op(op_get_dir))));
  i.register_op("hostname", s.core_op(json_op(s.stateful_op(op_hostname))));
}

#[derive(Deserialize)]
struct GetDirArgs {
  kind: std::string::String,
}

fn op_get_dir(
  state: &State,
  args: Value,
  _zero_copy: Option<ZeroCopyBuf>,
) -> Result<JsonOp, ErrBox> {
  state.check_env()?;
  let args: GetDirArgs = serde_json::from_value(args)?;

  let path = match args.kind.as_str() {
    "home" => dirs::home_dir(),
    "config" => dirs::config_dir(),
    "cache" => dirs::cache_dir(),
    "executable" => dirs::executable_dir(),
    "data" => dirs::data_dir(),
    "data_local" => dirs::data_local_dir(),
    "audio" => dirs::audio_dir(),
    "desktop" => dirs::desktop_dir(),
    "document" => dirs::document_dir(),
    "download" => dirs::download_dir(),
    "font" => dirs::font_dir(),
    "picture" => dirs::picture_dir(),
    "public" => dirs::public_dir(),
    "template" => dirs::template_dir(),
    "video" => dirs::video_dir(),
    _ => {
      return Err(ErrBox::from(Error::new(
        ErrorKind::InvalidInput,
        format!("Invalid dir type `{}`", args.kind.as_str()),
      )))
    }
  };

  if path == None {
    Err(ErrBox::from(Error::new(
      ErrorKind::NotFound,
      format!("Could not get user {} directory.", args.kind.as_str()),
    )))
  } else {
    Ok(JsonOp::Sync(json!(path
      .unwrap_or_default()
      .into_os_string()
      .into_string()
      .unwrap_or_default())))
  }
}

fn op_exec_path(
  state: &State,
  _args: Value,
  _zero_copy: Option<ZeroCopyBuf>,
) -> Result<JsonOp, ErrBox> {
  state.check_env()?;
  let current_exe = env::current_exe().unwrap();
  // Now apply URL parser to current exe to get fully resolved path, otherwise
  // we might get `./` and `../` bits in `exec_path`
  let exe_url = Url::from_file_path(current_exe).unwrap();
  let path = exe_url.to_file_path().unwrap();
  Ok(JsonOp::Sync(json!(path)))
}

#[derive(Deserialize)]
struct SetEnv {
  key: String,
  value: String,
}

fn op_set_env(
  state: &State,
  args: Value,
  _zero_copy: Option<ZeroCopyBuf>,
) -> Result<JsonOp, ErrBox> {
  let args: SetEnv = serde_json::from_value(args)?;
  state.check_env()?;
  env::set_var(args.key, args.value);
  Ok(JsonOp::Sync(json!({})))
}

fn op_env(
  state: &State,
  _args: Value,
  _zero_copy: Option<ZeroCopyBuf>,
) -> Result<JsonOp, ErrBox> {
  state.check_env()?;
  let v = env::vars().collect::<HashMap<String, String>>();
  Ok(JsonOp::Sync(json!(v)))
}

#[derive(Deserialize)]
struct GetEnv {
  key: String,
}

fn op_get_env(
  state: &State,
  args: Value,
  _zero_copy: Option<ZeroCopyBuf>,
) -> Result<JsonOp, ErrBox> {
  let args: GetEnv = serde_json::from_value(args)?;
  state.check_env()?;
  let r = match env::var(args.key) {
    Err(env::VarError::NotPresent) => json!([]),
    v => json!([v?]),
  };
  Ok(JsonOp::Sync(r))
}

#[derive(Deserialize)]
struct Exit {
  code: i32,
}

fn op_exit(
  _s: &State,
  args: Value,
  _zero_copy: Option<ZeroCopyBuf>,
) -> Result<JsonOp, ErrBox> {
  let args: Exit = serde_json::from_value(args)?;
  std::process::exit(args.code)
}

fn op_is_tty(
  _s: &State,
  _args: Value,
  _zero_copy: Option<ZeroCopyBuf>,
) -> Result<JsonOp, ErrBox> {
  Ok(JsonOp::Sync(json!({
    "stdin": atty::is(atty::Stream::Stdin),
    "stdout": atty::is(atty::Stream::Stdout),
    "stderr": atty::is(atty::Stream::Stderr),
  })))
}

fn op_hostname(
  state: &State,
  _args: Value,
  _zero_copy: Option<ZeroCopyBuf>,
) -> Result<JsonOp, ErrBox> {
  state.check_env()?;
  let hostname = sys_info::hostname().unwrap_or_else(|_| "".to_owned());
  Ok(JsonOp::Sync(json!(hostname)))
}