You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

127 lines
3.0 KiB

#include "util.h"
#include <csignal>
#include <sys/wait.h>
std::string
file_ext(std::string path)
{
return path.substr(path.find_last_of(".") + 1, path.length());
}
std::string trim_whitespace(std::string s) {
int ff = s.find_first_not_of(" \n\t");
int ll = s.find_last_not_of(" \n\t");
return s.substr(ff, ll - ff + 1);
}
std::string read_file(std::string const &fpath) {
std::ostringstream sstr;
std::ifstream in (fpath);
sstr << in.rdbuf();
return sstr.str();
}
std::string
reformat_date(const std::string& date_time, const std::unordered_map<std::string, std::string> &properties)
{
std::istringstream in {date_time};
date::sys_seconds timepoint;
in >> date::parse(properties.at("date-in-format"), timepoint);
auto t = std::chrono::system_clock::to_time_t(timepoint);
std::ostringstream ss;
date::to_stream(ss, properties.at("date-out-format").c_str(), timepoint);
return ss.str();
}
void write_file(std::string const &fpath, std::string const &content) {
std::fstream s;
s.open(fpath, std::ios_base::out);
if (!s.is_open()) {
spdlog::error ("Error: failed to open file {}", fpath);
return;
}
s << content;
s.close();
}
namespace stgen {
fs::path
compute_target(fs::path fpath, std::unordered_map<std::string, std::string> &properties)
{
std::string ext = file_ext(fpath);
fs::path relative_path = fs::relative(fpath, properties.at("source_root"));
fs::path dest_path = fs::path(properties.at("publish_root")).append(relative_path.string());
std::string destext;
if (properties.count("template")) {
std::string temp = properties.at("template");
if (temp.find(".") != std::string::npos)
destext = file_ext(temp);
destext = temp;
return fs::path(dest_path.string().substr(0, dest_path.string().find_last_of(".")) + "." + destext);
}
if (ext == "md" || ext == "markdown") {
destext = "html";
return fs::path(dest_path.string().substr(0, dest_path.string().find_last_of(".")) + "." + destext);
}
return dest_path;
}
std::string
compute_url(fs::path path, std::unordered_map<std::string, std::string> properties)
{
fs::path target = compute_target(path, properties);
fs::path rel = fs::relative(target, properties.at("publish_root"));
fs::path url = fs::path(properties.at("url")) / rel;
return url.string();
}
};
void server::serve_now(std::string wroot, std::string port, std::string addr) {
if (spid) {
// already serving
return;
}
int pid;
if (!(pid = fork())) {
const char *argv[] = {"stgen3", wroot.c_str(), "--port", port.c_str(),
"--addr", addr.c_str()};
int argc = 6;
darkhttpd::darkhttpd_main(argc, argv);
} else {
this->spid = pid;
return;
}
}
void server::stop_serving() {
if (spid) {
kill(spid, SIGTERM);
waitpid(-1, NULL, 0);
}
spid = 0;
}
server::~server() {
stop_serving();
}