From 22082a515bec06ae149cd3be56286deb182d980e Mon Sep 17 00:00:00 2001 From: Riyyi Date: Sun, 26 Sep 2021 00:14:43 +0200 Subject: [PATCH] Util: Add convenience functions to save external process creation --- src/util/system.cpp | 76 +++++++++++++++++++++++++++++++++++++++++++++ src/util/system.h | 9 ++++-- 2 files changed, 83 insertions(+), 2 deletions(-) diff --git a/src/util/system.cpp b/src/util/system.cpp index 7d62a9c..5c3e39a 100644 --- a/src/util/system.cpp +++ b/src/util/system.cpp @@ -4,6 +4,7 @@ #include // exit, WEXITSTATUS #include // strcpy, strtok #include // function +#include // istringstream #include #include #include // waitpid @@ -132,6 +133,81 @@ System System::operator||(System rhs) return rhs; } +// cut -f +System& System::cut(uint32_t field) +{ + exec(); + + return apply([&field](std::vector& lines) { + for (auto& line : lines) { + size_t count = 1; + size_t index = 0; + while (index != std::string::npos) { + if (count == field) { + line = line.substr(0, line.find_first_of(" ")); + break; + } + + index = line.find_first_of(" "); + line = line.substr(index + 1); + count++; + } + } + }); +} + +System& System::sort(bool unique) +{ + exec(); + + return apply([&unique](std::vector& lines) { + std::sort(lines.begin(), lines.end()); + + if (unique) { + auto last = std::unique(lines.begin(), lines.end()); + lines.erase(last, lines.end()); + } + }); +} + +// tail -n +System& System::tail(int32_t number, bool starting) +{ + exec(); + + return apply([&number, &starting](std::vector& lines) { + number = abs(number); + if (!starting) { + lines.erase(lines.begin(), lines.end() - number); + } + else { + lines.erase(lines.begin(), lines.begin() + number - 1); + } + }); +} + +System& System::apply(LineCallback callback) +{ + exec(); + + std::vector lines; + + auto stream = std::istringstream(m_output); + std::string line; + while (std::getline(stream, line)) { + lines.push_back(line); + } + + callback(lines); + + m_output.clear(); + for (size_t i = 0; i < lines.size(); ++i) { + m_output.append(lines.at(i) + '\n'); + } + + return *this; +} + void System::print(const std::vector& arguments) { if (!arguments.size()) { diff --git a/src/util/system.h b/src/util/system.h index 768ea2d..5b71ffe 100644 --- a/src/util/system.h +++ b/src/util/system.h @@ -1,7 +1,7 @@ #ifndef SYSTEM_H #define SYSTEM_H -#include // size_t +#include // int32_t, uint32_t #include // function #include #include @@ -9,7 +9,7 @@ namespace Util { -using SplitCallback = std::function; +using LineCallback = std::function&)>; class System { public: @@ -36,6 +36,11 @@ public: System operator&&(System rhs); System operator||(System rhs); + System& cut(uint32_t field); + System& sort(bool unique = false); + System& tail(int32_t number, bool starting = false); + System& apply(LineCallback callback); + void print(const std::vector& arguments); const std::vector& arguments() const { return m_arguments; }