esv/esvsearch.d

110 lines
2.4 KiB
D

/*
* esvsearch: search the Bible from your terminal
*
* The GPLv2 License (GPLv2)
* Copyright (c) 2023-2024 Jeremy Baxter
*
* esv is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* esv is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with esv. If not, see <http://www.gnu.org/licenses/>.
*/
module esvsearch;
import std.file : FileException;
import std.getopt : getopt, GetOptException;
import std.path : baseName, expandTilde;
import std.process : environment;
import std.stdio : writeln, writefln;
import esvapi;
import initial;
import util;
import cf = config;
@safe:
string cFlag; /* config path */
bool VFlag; /* show version */
int
main(string[] args)
{
INIUnit ini;
ESVApi esv;
string apiKey;
string configPath;
sharedInit(args);
cFlag = null;
/* Parse command-line options */
try {
import std.getopt : config;
getopt(args,
config.bundling,
config.caseSensitive,
"c", &cFlag,
"V", &VFlag,
);
} catch (GetOptException e) {
handleOptError(e.msg);
}
if (VFlag) {
writeln("esvsearch " ~ cf.esvVersion);
return 0;
}
if (args.length < 2) {
stderr.writefln("usage: %s [-l length] query",
baseName(args[0]));
return 1;
}
/* determine configuration file: options take first priority,
* then environment variables, and then the default path */
configPath = environment.get(cf.configEnv, cf.configPath)
.expandTilde();
try {
if (cFlag)
configPath = cFlag.expandTilde();
readINIFile(ini, configPath);
} catch (FileException e) {
/* filesystem syscall errors */
import core.stdc.errno : ENOENT;
if (e.errno != ENOENT)
die(e.msg);
warn(configPath ~ ": no such file or directory");
warn("Invoke esv to create an initial configuration file.");
}
apiKey = ini["api"].key("key");
enforceDie(apiKey != null,
"API key not present in configuration file; cannot proceed");
esv = ESVApi(apiKey);
try
writeln(esv.searchFormat(args[1]));
catch (ESVException)
die("no results");
catch (CurlException e)
die(e.msg);
return 0;
}