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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
use std::env;

use once_cell::sync::Lazy;
use rquickjs::{
    module::{Declarations, Exports, ModuleDef},
    prelude::Func,
    Ctx, Result,
};

use crate::modules::module::export_default;

pub fn get_platform() -> &'static str {
    let platform = env::consts::OS;
    match platform {
        "macos" => "darwin",
        "windows" => "win32",
        _ => platform,
    }
}

static OS_INFO: Lazy<(String, String, String)> = Lazy::new(|| {
    if let Ok(uts) = cross_uname::uname() {
        return (uts.sysname, uts.release, uts.version);
    }
    (
        String::from("n/a"),
        String::from("n/a"),
        String::from("n/a"),
    )
});

fn get_type() -> &'static str {
    &OS_INFO.0
}

fn get_release() -> &'static str {
    &OS_INFO.1
}

fn get_version() -> &'static str {
    &OS_INFO.2
}

fn get_tmp_dir() -> String {
    env::temp_dir().to_string_lossy().to_string()
}

pub struct OsModule;

impl ModuleDef for OsModule {
    fn declare(declare: &Declarations<'_>) -> Result<()> {
        declare.declare("type")?;
        declare.declare("release")?;
        declare.declare("tmpdir")?;
        declare.declare("platform")?;
        declare.declare("version")?;

        declare.declare("default")?;

        Ok(())
    }

    fn evaluate<'js>(ctx: &Ctx<'js>, exports: &Exports<'js>) -> Result<()> {
        export_default(ctx, exports, |default| {
            default.set("type", Func::from(get_type))?;
            default.set("release", Func::from(get_release))?;
            default.set("tmpdir", Func::from(get_tmp_dir))?;
            default.set("platform", Func::from(get_platform))?;
            default.set("version", Func::from(get_version))?;

            Ok(())
        })
    }
}

// impl From<OsModule> for ModuleInfo<OsModule> {
//     fn from(val: OsModule) -> Self {
//         ModuleInfo {
//             name: "os",
//             module: val,
//         }
//     }
// }