-module(ephraim_config). -behaviour(gen_server). -export([start_link/0]). -export([get/1]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -spec start_link() -> {ok, pid()}. start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). -spec init(term()) -> {ok, dict()}. init(_Args) -> {ok, Terms} = file:consult(config_path() ++ "/ephraim.cfg"), Config = dict:from_list(lists:map(fun(Term) -> {element(1, Term), Term} end, Terms)), {ok, Config}. -spec config_path() -> string(). config_path() -> Path = case os:getenv("XDG_CONFIG_HOME") of false -> os:getenv("HOME") ++ "/.config"; ConfigHome -> ConfigHome end ++ "/ephraim", case file:read_file_info(Path) of {ok, _} -> ok; {error, _} -> file:make_dir(Path) end, Path. -spec get(atom()) -> tuple() | error. get(Key) -> gen_server:call(?MODULE, {get, Key}). -spec handle_call(term(), {pid(), term()}, dict()) -> {reply, tuple() | error, dict()}. handle_call({get, Key}, _From, Config) -> ephraim_config ! {self(), get, Key}, case dict:find(Key, Config) of {ok, Value} -> {reply, Value, Config}; error -> {reply, error, Config} end. handle_cast(_Msg, Config) -> {noreply, Config}. handle_info(_Msg, Config) -> {noreply, Config}. terminate(_Reason, _Config) -> ok. code_change(_OldVersion, Config, _Extra) -> {ok, Config}.