Perform ConfigUtils code refactoring

Instead of manually reading lines and storing them on memory, parse lines while reading them on the fly using std::fstream (also bump the source file copyright years).
This commit is contained in:
luca0N! 2023-12-01 06:50:55 -03:00
parent 340046a264
commit 83ec72e80c
Signed by: luca0N
GPG Key ID: 5978D960572B449E
1 changed files with 5 additions and 47 deletions

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2022 luca0N! * Copyright (C) 2022-2023 luca0N!
* *
* This file is part of Static Website Generator (swg). * This file is part of Static Website Generator (swg).
* *
@ -22,57 +22,13 @@
#include "ConfigUtils.hxx" #include "ConfigUtils.hxx"
#include <iostream> #include <iostream>
#include <fstream>
#include <cstring> #include <cstring>
#include <cassert> #include <cassert>
#include "Common.hxx" #include "Common.hxx"
void parse_config(SwgContext *ctx, std::string const &path) { void parse_config(SwgContext *ctx, std::string const &path) {
std::string ctxCfgPath = path;
ctxCfgPath += "/swg.cfg";
FILE *ctxCfgFile = fopen(ctxCfgPath.c_str(), "r");
if (ctxCfgFile == NULL) {
std::cerr << "error: cannot open swg.cfg file, are you sure "
<< path << " is a valid SWG directory?" << std::endl;
perror(ctxCfgPath.c_str());
exit(RETURN_FAILED_INVALID_DIRECTORY);
}
int buflen = 16;
char cbuf[buflen];
// Yes, this looks ugly, but it works for now. Will probably optimize
// this in the future :)
//
// TODO: Optimize config file interpretation
std::list<std::string> lines = { "" };
while (fgets(cbuf, buflen, ctxCfgFile) != NULL) {
int eol = -1;
for (int c = 0; c < buflen; c++) {
if (cbuf[c] == '\0') {
break;
} else if (cbuf[c] == '\n') {
eol = c;
break;
}
}
if (eol > -1) {
cbuf[eol] = '\0';
*(--lines.end()) += cbuf;
lines.insert(lines.end(), "");
} else
*(--lines.end()) += cbuf;
}
fclose(ctxCfgFile);
std::cout << "Done loading configuration file in memory" << std::endl;
// Parse configuration file
enum ConfigNamespace { General, Blogs }; enum ConfigNamespace { General, Blogs };
ConfigNamespace ns; ConfigNamespace ns;
@ -81,7 +37,9 @@ void parse_config(SwgContext *ctx, std::string const &path) {
// currentBlog->name = "asd"; // currentBlog->name = "asd";
for (std::string line : lines) { std::ifstream cfg_stream(path);
// Parse configuration file
for (std::string line; std::getline(cfg_stream, line);) {
// Skip comment lines // Skip comment lines
if (line.c_str()[0] == '#') if (line.c_str()[0] == '#')
continue; continue;