stuff-from-scratch/apps/website-generator/MarkdownContentParser.h

93 lines
2.1 KiB
C
Raw Normal View History

2022-10-03 07:46:41 +00:00
#pragma once
#include "File.h"
#include <string>
#include <optional>
2022-10-04 07:20:39 +00:00
#include <unordered_map>
2022-10-03 07:46:41 +00:00
class MarkdownContentParser
{
public:
using FileMetadataItem = std::pair<std::string, std::string>;
2022-10-04 07:20:39 +00:00
using FileMetadata = std::unordered_map<std::string, std::string>;
2022-10-03 07:46:41 +00:00
using FileContentBody = std::vector<std::string>;
void run(const std::string& path)
{
FileMetadata metadata;
const auto lines = File(path).readLines();
2022-10-04 07:20:39 +00:00
bool metadata_finished = false;
2022-10-03 07:46:41 +00:00
for (const auto& line : lines)
{
2022-10-04 07:20:39 +00:00
if (!metadata_finished)
{
const auto metadata = checkForMetadataItem(line);
if (!metadata)
{
metadata_finished = true;
mContentBody.push_back(line);
}
else
{
mMetadata[metadata->first] - metadata->second;
}
}
else
{
mContentBody.push_back(line);
}
2022-10-03 07:46:41 +00:00
}
}
2022-10-04 07:20:39 +00:00
FileContentBody getContentBody() const
2022-10-03 07:46:41 +00:00
{
return mContentBody;
}
FileMetadata getFileMetadata() const
{
return mMetadata;
}
private:
std::optional<FileMetadataItem> checkForMetadataItem(const std::string& line) const
{
unsigned char_count = 0;
std::string prefix;
std::string suffix;
bool building_prefix = true;
for (const auto c : line)
{
if (c == ':' && char_count > 0 && building_prefix)
{
building_prefix = false;
}
else if (building_prefix)
{
prefix += c;
}
else
{
suffix += c;
}
char_count ++;
}
2022-10-04 07:20:39 +00:00
if (!prefix.empty() && !building_prefix)
2022-10-03 07:46:41 +00:00
{
return FileMetadataItem{prefix, suffix};
}
else
{
return std::nullopt;
}
}
FileMetadata mMetadata;
FileContentBody mContentBody;
};