82 lines
1.5 KiB
C++
82 lines
1.5 KiB
C++
#include "history.h"
|
|
|
|
#include <QDir>
|
|
#include <algorithm>
|
|
#include <filesystem>
|
|
#include <fstream>
|
|
|
|
namespace fs = std::filesystem;
|
|
|
|
CHistory::CHistory()
|
|
{
|
|
default_set();
|
|
}
|
|
|
|
bool CHistory::push(const std::string& content)
|
|
{
|
|
std::vector<std::string> vec;
|
|
read_file(vec);
|
|
|
|
if (std::find(vec.begin(), vec.end(), content) == vec.end()) {
|
|
vec.push_back(content);
|
|
} else {
|
|
return true;
|
|
}
|
|
|
|
if (vec.size() > 10) {
|
|
vec.erase(vec.begin());
|
|
}
|
|
if (!write_file(vec)) {
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
bool CHistory::get_history(std::vector<std::string>& vec)
|
|
{
|
|
return read_file(vec);
|
|
}
|
|
|
|
void CHistory::default_set()
|
|
{
|
|
QDir dir;
|
|
std::string path = dir.homePath().toStdString();
|
|
fs::path p(path);
|
|
p.append(".config/OneLevelXmlOpr");
|
|
|
|
if (!fs::exists(p)) {
|
|
fs::create_directories(p);
|
|
}
|
|
|
|
work_dir_ = p.string();
|
|
p.append("OneLevelXmlOpr.history");
|
|
work_file_ = p.string();
|
|
}
|
|
|
|
bool CHistory::read_file(std::vector<std::string>& vec)
|
|
{
|
|
vec.clear();
|
|
std::ifstream file(work_file_);
|
|
if (!file.is_open()) {
|
|
return false;
|
|
}
|
|
std::string line;
|
|
while (std::getline(file, line)) {
|
|
vec.push_back(line);
|
|
}
|
|
return true;
|
|
}
|
|
|
|
bool CHistory::write_file(std::vector<std::string>& vec)
|
|
{
|
|
std::ofstream file(work_file_);
|
|
if (!file.is_open()) {
|
|
return false;
|
|
}
|
|
for (const auto& line : vec) {
|
|
file << line << std::endl;
|
|
}
|
|
file.close();
|
|
return true;
|
|
}
|