aboutsummaryrefslogtreecommitdiff
path: root/src/cli_ffi.erl
blob: 1c1b6f063542851b21444d8308bf35e6d2d68860 (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
-module(cli_ffi).
-export([
    get_cpu/0,
    get_esbuild/1,
    get_os/0,
    unzip_esbuild/1
]).

get_os() ->
    case os:type() of
        {win32, _} -> <<"win32">>;
        {unix, darwin} -> <<"darwin">>;
        {unix, linux} -> <<"linux">>;
        {_, Unknown} -> atom_to_binary(Unknown, utf8)
    end.

get_cpu() ->
    case erlang:system_info(os_type) of
        {unix, _} ->
            [Arch, _] = string:split(erlang:system_info(system_architecture), "-"),
            list_to_binary(Arch);
        {win32, _} ->
            case erlang:system_info(wordsize) of
                4 -> {ok, <<"ia32">>};
                8 -> {ok, <<"x64">>}
            end
    end.

get_esbuild(Url) ->
    inets:start(),
    ssl:start(),

    case httpc:request(get, {Url, []}, [], [{body_format, binary}]) of
        {ok, {{_, 200, _}, _, Zip}} -> {ok, Zip};
        {ok, Res} -> {error, Res};
        {error, Err} -> {error, Err}
    end.

unzip_esbuild(Zip) ->
    Result =
        erl_tar:extract({binary, Zip}, [
            memory, compressed, {files, ["package/bin/esbuild"]}
        ]),

    case Result of
        {ok, [{_, Esbuild}]} -> {ok, Esbuild};
        {ok, Res} -> {error, Res};
        {error, Err} -> {error, Err}
    end.