mirai/src/core/TodoMd.cpp

79 lines
2 KiB
C++
Raw Normal View History

2024-04-10 16:53:18 +02:00
/*
* Mirai. Copyright (C) 2024 Vyn
* This file is licensed under version 3 of the GNU General Public License (GPL-3.0-only)
* The license can be found in the LICENSE file or at https://www.gnu.org/licenses/gpl-3.0.txt
*/
#include "TodoMd.h"
namespace mirai {
TasksFile TodoMdFormat::readFile(const std::string& path) {
std::ifstream file(path);
if (!file.is_open()) {
throw std::runtime_error("todo.txt file not found");
}
std::vector<TaskItem> taskItems;
std::string line;
if (!std::getline(file, line) || line.substr(0, 2) != "# ") {
std::cerr << "Couldn't find the task list name" << std::endl;
}
std::string name = line.substr(2);
std::string currentDate = "";
while (std::getline(file, line)) {
if (line.substr(0, 3) == "## ") {
currentDate = line.substr(3);
} else if (line.substr(0, 5) == "- [ ]" || line.substr(0, 5) == "- [X]") {
std::string text = line.substr(5);
trim(text);
TaskItem taskItem = {
.text = text,
.state = line.substr(0, 5) == "- [X]" ? DONE : TODO,
.date = currentDate
};
taskItems.push_back(taskItem);
}
}
file.close();
TasksFile tasks({
.name = name,
.path = path,
.tasks = taskItems
});
return tasks;
}
void TodoMdFormat::writeFile(TasksFile& tasks) {
std::ofstream file(tasks.getPath());
if (!file.is_open()) {
throw std::runtime_error("can't create todo.txt");
}
std::string currentDate = "";
file << "# " << tasks.getName() << "\n";
for (const auto& task : tasks.getTasks()) {
if (currentDate != task->date) {
currentDate = task->date;
file << "\n## " << (task->date != "" ? task->date : "No date") << "\n\n";
}
if (task->getState() == TODO) {
file << "- [ ] ";
} else if (task->getState() == DONE) {
file << "- [X] ";
}
file << task->getText() << '\n';
}
file.close();
}
std::string TodoMdFormat::fieldWithSpace(const std::string& field) {
if (field.length() == 0)
return "";
return (field + " ");
}
}