You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

106 lines
3.2 KiB
C++

#pragma once
#include <sstream>
#include <iomanip>
#include <numeric>
#include <algorithm>
#include <vector>
#include <set>
#include <filesystem>
#include <iostream>
namespace filepath
{
std::tuple<std::filesystem::path, std::filesystem::file_status> getFileInfo(const std::filesystem::directory_entry& entry)
{
const auto file_status (std::filesystem::status(entry));
return {entry.path(), file_status};
}
bool endsWith(const std::string& string, const std::string& ending)
{
if (ending.size() > string.size())
return false;
return std::equal(ending.rbegin(), ending.rend(), string.rbegin());
}
std::string randomChoice(const std::vector<std::string>& poll)
{
std::cout << "Loading random image!\n";
const auto range = poll.size() - 1;
return poll.at(rand() & range);
}
std::vector<std::tuple<std::filesystem::path, std::filesystem::file_status>> extractFilesFrom(std::filesystem::path&& path)
{
std::vector<std::tuple<std::filesystem::path, std::filesystem::file_status>> dir_items;
std::transform(std::filesystem::directory_iterator(path), {}, std::back_inserter(dir_items), filepath::getFileInfo);
return dir_items;
}
bool isImage(const std::filesystem::path& filepath)
{
static std::set<std::string> allowed_ext = {".bmp", ".jpg", "*.jpeg", ".png"};
const std::string path_string = filepath.string();
return std::filesystem::is_regular_file(filepath) &&
std::any_of(allowed_ext.begin(), allowed_ext.end(),
[&](const std::string& e)
{
return filepath::endsWith(path_string, e);
});
}
std::tuple<int, std::vector<std::string>> parseFolder(std::filesystem::path&& path)
{
auto directory_items = extractFilesFrom(std::move(path));
std::vector<std::string> image_pathes;
for (const auto &[local_path, status] : directory_items)
{
if (isImage(local_path))
image_pathes.emplace_back(local_path.string());
}
if (image_pathes.empty())
return {EXIT_FAILURE, {}};
const std::tuple<int, std::vector<std::string>> empty_folder = {EXIT_FAILURE, {}};
const std::tuple<int, std::vector<std::string>> found_images = {EXIT_SUCCESS, image_pathes};
return image_pathes.empty()
? empty_folder
: found_images;
}
std::tuple<int, std::vector<std::string>> parsePath(const std::string &argv)
{
std::filesystem::path path(argv);
if (!std::filesystem::exists(path))
{
std::cout << "Path " << path << " does not exist.\n";
return {EXIT_FAILURE, {}};
}
if (std::filesystem::is_regular_file(path))
{
return {EXIT_SUCCESS, {path.string()}};
}
return parseFolder(std::move(path));
}
std::vector<std::string> split(const std::string &s, char delim)
{
std::vector<std::string> result;
std::stringstream ss (s);
std::string item;
while (getline(ss, item, delim))
result.push_back(item);
return result;
}
}