rqjs_ext/modules/
os.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3use std::env;
4
5use once_cell::sync::Lazy;
6use rquickjs::{
7    module::{Declarations, Exports, ModuleDef},
8    prelude::Func,
9    Ctx, Result,
10};
11
12use crate::modules::module::export_default;
13
14pub fn get_platform() -> &'static str {
15    let platform = env::consts::OS;
16    match platform {
17        "macos" => "darwin",
18        "windows" => "win32",
19        _ => platform,
20    }
21}
22
23static OS_INFO: Lazy<(String, String, String)> = Lazy::new(|| {
24    if let Ok(uts) = cross_uname::uname() {
25        return (uts.sysname, uts.release, uts.version);
26    }
27    (
28        String::from("n/a"),
29        String::from("n/a"),
30        String::from("n/a"),
31    )
32});
33
34fn get_type() -> &'static str {
35    &OS_INFO.0
36}
37
38fn get_release() -> &'static str {
39    &OS_INFO.1
40}
41
42fn get_version() -> &'static str {
43    &OS_INFO.2
44}
45
46fn get_tmp_dir() -> String {
47    env::temp_dir().to_string_lossy().to_string()
48}
49
50pub struct OsModule;
51
52impl ModuleDef for OsModule {
53    fn declare(declare: &Declarations<'_>) -> Result<()> {
54        declare.declare("type")?;
55        declare.declare("release")?;
56        declare.declare("tmpdir")?;
57        declare.declare("platform")?;
58        declare.declare("version")?;
59
60        declare.declare("default")?;
61
62        Ok(())
63    }
64
65    fn evaluate<'js>(ctx: &Ctx<'js>, exports: &Exports<'js>) -> Result<()> {
66        export_default(ctx, exports, |default| {
67            default.set("type", Func::from(get_type))?;
68            default.set("release", Func::from(get_release))?;
69            default.set("tmpdir", Func::from(get_tmp_dir))?;
70            default.set("platform", Func::from(get_platform))?;
71            default.set("version", Func::from(get_version))?;
72
73            Ok(())
74        })
75    }
76}
77
78// impl From<OsModule> for ModuleInfo<OsModule> {
79//     fn from(val: OsModule) -> Self {
80//         ModuleInfo {
81//             name: "os",
82//             module: val,
83//         }
84//     }
85// }