aboutsummaryrefslogtreecommitdiff
path: root/src/gleam/os.gleam
blob: af67e35f1138fac9af6e3b7af566900240c3cd7c (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
//// Function to interact with the host operating system.

if erlang {
  import gleam/list
  import gleam/map.{Map}
  import gleam/string

  // Internal type for erlang interop.
  external type CharList

  external fn os_getenv() -> List(CharList) =
    "os" "getenv"

  external fn os_putenv(key: CharList, value: CharList) -> Bool =
    "os" "putenv"

  external fn os_unsetenv(key: CharList) -> Bool =
    "os" "unsetenv"

  external fn char_list_to_string(CharList) -> String =
    "unicode" "characters_to_binary"

  external fn string_to_char_list(String) -> CharList =
    "unicode" "characters_to_list"

  /// Returns all environment variables set on the system.
  pub fn get_env() -> Map(String, String) {
    list.map(
      os_getenv(),
      fn(char_list) {
        assert Ok(value) =
          string.split_once(char_list_to_string(char_list), "=")
        value
      },
    )
    |> map.from_list()
  }

  /// Sets an environment variable.
  pub fn insert_env(key: String, value: String) -> Nil {
    os_putenv(string_to_char_list(key), string_to_char_list(value))
    Nil
  }

  /// Deletes an environment variable.
  pub fn delete_env(key: String) -> Nil {
    os_unsetenv(string_to_char_list(key))
    Nil
  }

  pub type TimeUnit {
    Second
    Millisecond
    Microsecond
    Nanosecond
  }

  /// Returns the current OS system time.
  ///
  /// https://erlang.org/doc/apps/erts/time_correction.html#OS_System_Time
  pub external fn system_time(TimeUnit) -> Int =
    "os" "system_time"

  /// Returns the current OS system time as a tuple of Ints
  ///
  /// http://erlang.org/doc/man/os.html#timestamp-0
  pub external fn erlang_timestamp() -> #(Int, Int, Int) =
    "os" "timestamp"
}