forked from awslabs/llrt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmkdir.rs
79 lines (64 loc) · 2.3 KB
/
mkdir.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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
use crate::chmod::{set_mode, set_mode_sync};
use llrt_utils::result::ResultExt;
use ring::rand::{SecureRandom, SystemRandom};
use rquickjs::{function::Opt, Ctx, Object, Result};
use tokio::fs;
pub async fn mkdir<'js>(ctx: Ctx<'js>, path: String, options: Opt<Object<'js>>) -> Result<String> {
let (recursive, mode) = get_params(options);
if recursive {
fs::create_dir_all(&path).await
} else {
fs::create_dir(&path).await
}
.or_throw_msg(&ctx, &["Can't create dir \"", &path, "\""].concat())?;
set_mode(ctx, &path, mode).await?;
Ok(path)
}
pub fn mkdir_sync<'js>(ctx: Ctx<'js>, path: String, options: Opt<Object<'js>>) -> Result<String> {
let (recursive, mode) = get_params(options);
if recursive {
std::fs::create_dir_all(&path)
} else {
std::fs::create_dir(&path)
}
.or_throw_msg(&ctx, &["Can't create dir \"", &path, "\""].concat())?;
set_mode_sync(ctx, &path, mode)?;
Ok(path)
}
fn get_params(options: Opt<Object>) -> (bool, u32) {
let mut recursive = false;
let mut mode = 0o777;
if let Some(options) = options.0 {
recursive = options.get("recursive").unwrap_or_default();
mode = options.get("mode").unwrap_or(0o777);
}
(recursive, mode)
}
const CHARS: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
fn random_chars(len: usize) -> String {
let random = SystemRandom::new();
let mut bytes = vec![0u8; len];
random.fill(&mut bytes).unwrap();
bytes
.iter()
.map(|&byte| {
let idx = (byte as usize) % CHARS.len();
CHARS[idx] as char
})
.collect::<String>()
}
pub async fn mkdtemp(ctx: Ctx<'_>, prefix: String) -> Result<String> {
let path = [prefix.as_str(), random_chars(6).as_str()].join(",");
fs::create_dir_all(&path)
.await
.or_throw_msg(&ctx, &["Can't create dir \"", &path, "\""].concat())?;
Ok(path)
}
pub fn mkdtemp_sync(ctx: Ctx<'_>, prefix: String) -> Result<String> {
let path = [prefix.as_str(), random_chars(6).as_str()].join(",");
std::fs::create_dir_all(&path)
.or_throw_msg(&ctx, &["Can't create dir \"", &path, "\""].concat())?;
Ok(path)
}