config: Better error messages when opening files

If a config file is a directory, ifstream would just read it as an empty
file without any errors.

Failing early here is a good idea.
This commit is contained in:
patrick96 2020-11-25 01:35:38 +01:00 committed by Patrick Ziegler
parent 9d31b51a63
commit 75eb41f5ad
4 changed files with 31 additions and 2 deletions

View File

@ -6,8 +6,6 @@
#include "components/config.hpp"
#include "components/logger.hpp"
#include "errors.hpp"
#include "utils/file.hpp"
#include "utils/string.hpp"
POLYBAR_NS

View File

@ -102,6 +102,7 @@ class fd_stream : public StreamType {
namespace file_util {
bool exists(const string& filename);
bool is_file(const string& filename);
string pick(const vector<string>& filenames);
string contents(const string& filename);
void write_contents(const string& filename, const string& contents);

View File

@ -1,8 +1,13 @@
#include "components/config_parser.hpp"
#include <algorithm>
#include <cerrno>
#include <cstring>
#include <fstream>
#include "utils/file.hpp"
#include "utils/string.hpp"
POLYBAR_NS
config_parser::config_parser(const logger& logger, string&& file, string&& bar)
@ -89,6 +94,14 @@ void config_parser::parse_file(const string& file, file_list path) {
throw application_error("include-file: Dependency cycle detected:\n" + path_str);
}
if (!file_util::exists(file)) {
throw application_error("Failed to open config file " + file + ": " + strerror(errno));
}
if (!file_util::is_file(file)) {
throw application_error("Config file " + file + " is not a file");
}
m_log.trace("config_parser: Parsing %s", file);
int file_index;

View File

@ -170,12 +170,29 @@ int fd_streambuf::underflow() {
namespace file_util {
/**
* Checks if the given file exist
*
* May also return false if the file status cannot be read
*
* Sets errno when returning false
*/
bool exists(const string& filename) {
struct stat buffer {};
return stat(filename.c_str(), &buffer) == 0;
}
/**
* Checks if the given path exists and is a file
*/
bool is_file(const string& filename) {
struct stat buffer {};
if (stat(filename.c_str(), &buffer) != 0) {
return false;
}
return S_ISREG(buffer.st_mode);
}
/**
* Picks the first existing file out of given entries
*/