added markdown metadata parsing

This commit is contained in:
2026-01-03 21:21:09 +01:00
parent 1460db6587
commit 9f9685170c
2 changed files with 63 additions and 0 deletions

43
src/markdown.cpp Normal file
View File

@@ -0,0 +1,43 @@
#include "markdown.hpp"
#include "utils.hpp"
#include <fstream>
#include <iostream>
#include <map>
#include <md4c-html.h>
#include <optional>
std::optional<Metadata> get_metadata(const std::string &FILE_PATH) {
std::fstream file(FILE_PATH);
std::string buffer;
if (!getline(file, buffer) || buffer != "---") {
std::cerr << "File " << FILE_PATH << "does not contain metadata."
<< std::endl;
return std::nullopt;
}
std::map<std::string, std::string> metadata_map;
while (getline(file, buffer)) {
if (buffer == "---") {
break;
}
size_t colon_pos = buffer.find(":");
if (colon_pos == std::string::npos) {
std::cerr << "The line: \n"
<< buffer << " does not contain a colon" << std::endl;
}
std::string key = buffer.substr(0, colon_pos);
trim(key);
std::string value = buffer.substr(colon_pos + 1);
trim(value);
metadata_map[key] = value;
}
return std::optional(Metadata{metadata_map["author"], metadata_map["date"],
metadata_map["title"],
convert_string_to_set(metadata_map["tags"])});
}

20
src/markdown.hpp Normal file
View File

@@ -0,0 +1,20 @@
#include <optional>
#include <set>
#include <string>
struct Metadata {
std::string author;
std::string date;
std::string title;
std::set<std::string> tags;
};
// Reads the metadata of the markdown file
// Metadata are in yaml format at the top of the file
// They are separated from the rest of the file with `---` at the beginning and
// at the end.
std::optional<Metadata> get_metadata(const std::string &FILE_PATH);
// Reads the markdown file and converts it to html.
// Return everything in one string
std::string get_html(const std::string &FILE_PATH);