| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | // Copyright 2019 Juan Palacios <[email protected]> |
| 3 | |
| 4 | #include "commandqueue.h" |
| 5 | |
| 6 | #include <QByteArray> |
| 7 | #include <algorithm> |
| 8 | #include <filesystem> |
| 9 | #include <iterator> |
| 10 | #include <spdlog/spdlog.h> |
| 11 | #include <utility> |
| 12 | |
| 13 | CommandQueue::CommandQueue(std::unordered_set<std::string> &&multiCommandFiles) noexcept |
| 14 | : multiCommandFiles_(std::move(multiCommandFiles)) |
| 15 | { |
| 16 | commands().reserve(50); |
| 17 | } |
| 18 | |
| 19 | bool CommandQueue::hasCommandQueuedFor(std::string const &file) |
| 20 | { |
| 21 | // find the last queued command for the file |
| 22 | auto it = std::find_if(commands().crbegin(), commands().crend(), |
| 23 | [&](auto const &v) { return v.first == file; }); |
| 24 | return it != commands().crend(); |
| 25 | } |
| 26 | |
| 27 | void CommandQueue::add(std::pair<std::string, std::string> &&cmd) |
| 28 | { |
| 29 | // find the last queued command for the file |
| 30 | auto lastIt = std::find_if(commands().crbegin(), commands().crend(), |
| 31 | [&](auto const &v) { return v.first == cmd.first; }); |
| 32 | |
| 33 | if (lastIt != commands().crend() && lastIt->second == cmd.second) |
| 34 | return; // command already queued |
| 35 | |
| 36 | // insert command at the end by default |
| 37 | auto insertIt = commands().cend(); |
| 38 | |
| 39 | // when a different command is already queued for that file... |
| 40 | if (lastIt != commands().crend()) { |
| 41 | |
| 42 | auto file = std::filesystem::path(cmd.first).filename(); |
| 43 | if (multiCommandFiles_.contains(file)) { |
| 44 | // insert it after the last queued command for that particular file |
| 45 | insertIt = lastIt.base(); |
| 46 | } |
| 47 | else { |
| 48 | // remove the previous queued command |
| 49 | commands().erase(std::prev(lastIt.base())); |
| 50 | insertIt = commands().cend(); // refresh iterator |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | commands().emplace(insertIt, std::move(cmd)); |
| 55 | } |
| 56 | |
| 57 | QByteArray CommandQueue::toRawData() |
| 58 | { |
| 59 | QByteArray data; |
| 60 | for (auto const &[path, value] : commands()) { |
| 61 | data += path.c_str(); |
| 62 | data += '\0'; |
| 63 | data += value.c_str(); |
| 64 | data += '\0'; |
| 65 | } |
| 66 | |
| 67 | commands().clear(); |
| 68 | return data; |
| 69 | } |
| 70 | |
| 71 | void CommandQueue::logCommands() const |
| 72 | { |
| 73 | for (auto const &[path, value] : commands_) |
| 74 | SPDLOG_INFO("{}: {}", path, value); |
| 75 | } |
| 76 | |
| 77 | std::vector<std::pair<std::string, std::string>> &CommandQueue::commands() |
| 78 | { |
| 79 | return commands_; |
| 80 | } |