From: Matt Mullins Date: Sat, 21 May 2011 22:53:25 +0000 (-0500) Subject: Added module to handle configuration files X-Git-Tag: v4~12 X-Git-Url: http://git.mmlx.us/?a=commitdiff_plain;h=94cdc0168cdbadc8a7cc4d8eea5d5cc6d2496f36;p=erlbot.git Added module to handle configuration files --- diff --git a/core/config.erl b/core/config.erl new file mode 100644 index 0000000..58f0b89 --- /dev/null +++ b/core/config.erl @@ -0,0 +1,50 @@ +%% @doc Looks up information in the configuration file. +%% This restructs us to a configuration file that contains multiple terms of +%% the form: +%% {Tag, Data}. +%% +%% TODO: I might, at some point in the future, want to throw an instance name +%% in each of the terms in the configuration file, but for now, this is fine. + +-module(config). +-behavior(gen_server). + +% Public-facing functions +-export([start_link/0, + get_config/1]). +% Call-backs for gen_server +-export([init/1, handle_call/3]). + +-record(config_state, {filename, data}). + +% Public-facing functions +start_link() -> + gen_server:start_link({local, ?MODULE}, ?MODULE, none, []). + +%% @doc Looks up the given Tag in the configuration file. +%% Returns [Data], where Data is the data included in each mention of Tag in +%% the configuration file. +get_config(Tag) -> + gen_server:call(?MODULE, {get_config, Tag}). + +% Callbacks and process internals +init(_) -> + Filename = get_filename(), + {ok, Data} = file:consult(Filename), + {ok, #config_state{filename = Filename, data = Data}}. + +%% @doc Looks up the given Tag in the configuration file +%% Returns [Data], where the Data is whatever was in each of the appropriate +%% terms in the configuration file. +handle_call({get_config, Tag}, _From, State = #config_state{data = Data}) -> + Terms = lists:filter(fun ({ConfTag, _}) -> Tag == ConfTag end, Data), + Return = lists:map(fun ({_, ConfData}) -> ConfData end, Terms), + {reply, Return, State}. + +%% @doc Gets the name of the configuration file, either from the -bot_config +%% command-line parameter, or returns "bot.cfg" as a fall-back. +get_filename() -> + case init:get_argument(bot_config) of + {ok, [[Filename]]} -> Filename; + _ -> "bot.cfg" + end.