You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@nifi.apache.org by lo...@apache.org on 2025/09/30 13:12:58 UTC
(nifi-minifi-cpp) 02/04: Fix clang tidy
This is an automated email from the ASF dual-hosted git repository.
lordgamez pushed a commit to branch MINIFICPP-2629
in repository https://gitbox.apache.org/repos/asf/nifi-minifi-cpp.git
commit 1bfbf4f2a835213315d51a2190b1e8ac5ce30b1c
Author: Gabor Gyimesi <ga...@gmail.com>
AuthorDate: Mon Sep 15 15:34:52 2025 +0200
Fix clang tidy
---
.clang-tidy | 1 +
core-framework/src/io/FileStream.cpp | 5 ++---
core-framework/src/utils/ByteArrayCallback.cpp | 6 +++---
core-framework/src/utils/Id.cpp | 4 ++--
core-framework/src/utils/OsUtils.cpp | 6 +++---
core-framework/src/utils/SystemCpuUsageTracker.cpp | 4 ++--
.../src/serialization/FlowFileV3Serializer.cpp | 2 +-
.../src/utils/ListingStateManager.cpp | 4 ++--
extensions/aws/processors/PutS3Object.cpp | 4 ++--
.../azure/processors/FetchAzureDataLakeStorage.cpp | 6 +++---
.../azure/processors/PutAzureDataLakeStorage.cpp | 2 +-
extensions/civetweb/processors/ListenHTTP.cpp | 2 +-
extensions/execute-process/ExecuteProcess.cpp | 2 +-
.../tests/GCPCredentialsControllerServiceTests.cpp | 2 +-
extensions/kafka/PublishKafka.cpp | 6 +++---
extensions/libarchive/FocusArchiveEntry.cpp | 1 -
extensions/libarchive/tests/MergeFileTests.cpp | 8 ++++----
extensions/libarchive/tests/util/ArchiveTests.cpp | 2 +-
extensions/lua/LuaScriptFlowFile.cpp | 8 ++++----
extensions/lua/LuaScriptFlowFile.h | 4 ++--
extensions/opc/include/opc.h | 2 +-
extensions/opc/src/opc.cpp | 3 +--
extensions/rocksdb-repos/tests/ProvenanceTests.cpp | 2 +-
extensions/sftp/processors/ListSFTP.cpp | 8 ++++----
extensions/sftp/processors/ListSFTP.h | 4 ++--
extensions/sftp/processors/SFTPProcessorBase.cpp | 8 ++------
extensions/sftp/tests/ListThenFetchSFTPTests.cpp | 2 +-
extensions/sql/data/SQLRowsetProcessor.cpp | 19 +++++--------------
extensions/sql/processors/QueryDatabaseTable.cpp | 2 +-
.../processors/AttributeRollingWindow.cpp | 2 +-
.../processors/AttributesToJSON.cpp | 4 ++--
.../processors/DefragmentText.cpp | 2 +-
.../standard-processors/processors/PutFile.cpp | 12 ++++++++----
.../standard-processors/processors/PutUDP.cpp | 2 +-
.../standard-processors/processors/SplitText.cpp | 4 ++--
.../tests/unit/RouteTextTests.cpp | 2 +-
.../tests/unit/SplitTextTests.cpp | 2 +-
.../tests/unit/YamlConnectionParserTest.cpp | 1 -
extensions/standard-processors/utils/JoltUtils.cpp | 21 +++++++++++----------
extensions/standard-processors/utils/JoltUtils.h | 2 +-
extensions/systemd/ConsumeJournald.cpp | 2 +-
extensions/systemd/libwrapper/LibWrapper.cpp | 10 ++--------
extensions/systemd/libwrapper/LibWrapper.h | 10 ++--------
extensions/systemd/tests/ConsumeJournaldTest.cpp | 2 +-
.../core/logging/internal/ActiveCompressor.h | 16 ++--------------
libminifi/include/core/state/UpdateController.h | 17 +++--------------
libminifi/src/FlowFileRecord.cpp | 6 +++---
libminifi/src/RemoteProcessorGroupPort.cpp | 15 +++++----------
libminifi/src/ResourceClaim.cpp | 2 +-
libminifi/src/ThreadedSchedulingAgent.cpp | 2 +-
libminifi/src/c2/C2Agent.cpp | 7 +++----
libminifi/src/core/ClassLoader.cpp | 4 ++--
libminifi/src/core/ProcessSession.cpp | 9 +++++----
libminifi/src/core/ProcessSessionReadCallback.cpp | 2 +-
.../core/logging/internal/CompressionManager.cpp | 2 +-
.../reporting/SiteToSiteProvenanceReportingTask.cpp | 2 +-
libminifi/src/core/state/UpdateController.cpp | 12 ++----------
libminifi/src/provenance/Provenance.cpp | 2 +-
libminifi/src/sitetosite/RawSocketProtocol.cpp | 2 +-
libminifi/src/sitetosite/SiteToSiteClient.cpp | 4 ++--
libminifi/test/flow-tests/FlowControllerTests.cpp | 2 +-
libminifi/test/libtest/integration/HTTPHandlers.cpp | 4 ++--
.../libtest/unit/SingleProcessorTestController.cpp | 4 ++--
.../libtest/unit/SingleProcessorTestController.h | 4 ++--
libminifi/test/libtest/unit/TestUtils.cpp | 14 +++++++-------
.../libtest/unit/WriteToFlowFileTestProcessor.h | 4 ++--
libminifi/test/unit/EnvironmentUtilsTests.cpp | 5 +++--
libminifi/test/unit/ExtendedKeyUsageTests.cpp | 18 +++++++++---------
libminifi/test/unit/FlowFileQueueSwapTests.cpp | 18 +++++++++---------
libminifi/test/unit/ResponseNodeLoaderTests.cpp | 2 +-
70 files changed, 164 insertions(+), 222 deletions(-)
diff --git a/.clang-tidy b/.clang-tidy
index 63fb7029d..50c7f52a2 100644
--- a/.clang-tidy
+++ b/.clang-tidy
@@ -1,6 +1,7 @@
Checks: >
-clang-analyzer-optin.cplusplus.VirtualCall,
-clang-analyzer-optin.core.EnumCastOutOfRange,
+ -clang-analyzer-unix.BlockInCriticalSection,
boost-use-to-string,
portability-restrict-system-includes,
portability-simd-intrinsics,
diff --git a/core-framework/src/io/FileStream.cpp b/core-framework/src/io/FileStream.cpp
index da9b2e9c0..d2154d43b 100644
--- a/core-framework/src/io/FileStream.cpp
+++ b/core-framework/src/io/FileStream.cpp
@@ -21,6 +21,7 @@
#include <vector>
#include <string>
#include <utility>
+#include <algorithm>
#include "minifi-cpp/Exception.h"
#include "io/validation.h"
@@ -124,9 +125,7 @@ size_t FileStream::write(const uint8_t *value, size_t size) {
return STREAM_ERROR;
}
offset_ += size;
- if (offset_ > length_) {
- length_ = offset_;
- }
+ length_ = std::max(offset_, length_);
if (!file_stream_->flush()) {
logger_->log_error("{}{}", WRITE_ERROR_MSG, FLUSH_CALL_ERROR_MSG);
return STREAM_ERROR;
diff --git a/core-framework/src/utils/ByteArrayCallback.cpp b/core-framework/src/utils/ByteArrayCallback.cpp
index 823e415ae..8446e9a27 100644
--- a/core-framework/src/utils/ByteArrayCallback.cpp
+++ b/core-framework/src/utils/ByteArrayCallback.cpp
@@ -100,7 +100,7 @@ size_t ByteOutputCallback::read_current_str(char *buffer, size_t size) {
read_started_ = true;
do {
std::lock_guard<std::recursive_mutex> lock(vector_lock_);
- if (current_str_pos <= current_str.length() && current_str.length() > 0) {
+ if (current_str_pos <= current_str.length() && !current_str.empty()) {
size_t str_remaining = current_str.length() - current_str_pos;
size_t current_str_read = str_remaining;
if (str_remaining > amount_to_read) {
@@ -137,9 +137,9 @@ size_t ByteOutputCallback::read_current_str(char *buffer, size_t size) {
bool ByteOutputCallback::preload_next_str() {
// wait until there is data or this stream has been stopped.
- if (queue_.size_approx() == 0 && current_str.length() == 0) {
+ if (queue_.size_approx() == 0 && current_str.empty()) {
std::unique_lock<std::recursive_mutex> lock(vector_lock_);
- if (queue_.size_approx() == 0 && current_str.length() == 0) {
+ if (queue_.size_approx() == 0 && current_str.empty()) {
spinner_.wait(lock, [&] {
return queue_.size_approx() > 0 || !is_alive_;});
}
diff --git a/core-framework/src/utils/Id.cpp b/core-framework/src/utils/Id.cpp
index 62d810b3c..3037827f1 100644
--- a/core-framework/src/utils/Id.cpp
+++ b/core-framework/src/utils/Id.cpp
@@ -170,8 +170,8 @@ std::optional<Identifier> Identifier::parse(const std::string &str) {
bool Identifier::parseByte(Data &data, const uint8_t *input, int &charIdx, int &byteIdx) {
uint8_t upper = 0;
uint8_t lower = 0;
- if (!string::from_hex(input[charIdx++], upper)
- || !string::from_hex(input[charIdx++], lower)) {
+ if (!string::from_hex(input[charIdx++], upper) // NOLINT(bugprone-inc-dec-in-conditions)
+ || !string::from_hex(input[charIdx++], lower)) { // NOLINT(bugprone-inc-dec-in-conditions)
return false;
}
data[byteIdx++] = (upper << 4) | lower;
diff --git a/core-framework/src/utils/OsUtils.cpp b/core-framework/src/utils/OsUtils.cpp
index cac91c2c5..6aa43ca59 100644
--- a/core-framework/src/utils/OsUtils.cpp
+++ b/core-framework/src/utils/OsUtils.cpp
@@ -177,7 +177,7 @@ int64_t OsUtils::getCurrentProcessPhysicalMemoryUsage() {
std::string line;
while (std::getline(status_file, line)) {
- if (line.rfind(resident_set_size_prefix, 0) == 0) {
+ if (line.starts_with(resident_set_size_prefix)) {
std::istringstream resident_set_size_value(line.substr(resident_set_size_prefix.length()));
uint64_t memory_usage_in_kBytes = 0;
resident_set_size_value >> memory_usage_in_kBytes;
@@ -221,11 +221,11 @@ int64_t OsUtils::getSystemPhysicalMemoryUsage() {
std::optional<uint64_t> total_memory_kByte;
std::optional<uint64_t> available_memory_kByte;
while ((!total_memory_kByte.has_value() || !available_memory_kByte.has_value()) && std::getline(meminfo_file, line)) {
- if (line.rfind(total_memory_prefix, 0) == 0) {
+ if (line.starts_with(total_memory_prefix)) {
std::istringstream total_memory_line(line.substr(total_memory_prefix.length()));
total_memory_kByte.emplace(0);
total_memory_line >> total_memory_kByte.value();
- } else if (line.rfind(available_memory_prefix, 0) == 0) {
+ } else if (line.starts_with(available_memory_prefix)) {
std::istringstream available_memory_line(line.substr(available_memory_prefix.length()));
available_memory_kByte.emplace(0);
available_memory_line >> available_memory_kByte.value();
diff --git a/core-framework/src/utils/SystemCpuUsageTracker.cpp b/core-framework/src/utils/SystemCpuUsageTracker.cpp
index 46757000d..39cc663f8 100644
--- a/core-framework/src/utils/SystemCpuUsageTracker.cpp
+++ b/core-framework/src/utils/SystemCpuUsageTracker.cpp
@@ -44,7 +44,7 @@ void SystemCpuUsageTracker::queryCpuTimes() {
previous_total_sys_ = total_sys_;
previous_total_idle_ = total_idle_;
gsl::owner<FILE*> file = fopen("/proc/stat", "r");
- if (fscanf(file, "cpu %lu %lu %lu %lu", &total_user_, &total_user_low_, &total_sys_, &total_idle_) != 4) { // NOLINT(cert-err34-c)
+ if (fscanf(file, "cpu %lu %lu %lu %lu", &total_user_, &total_user_low_, &total_sys_, &total_idle_) != 4) { // NOLINT(cert-err34-c,clang-analyzer-unix.Stream)
total_user_ = previous_total_user_;
total_user_low_ = previous_total_user_low_;
total_idle_ = previous_total_idle_;
@@ -76,7 +76,7 @@ double SystemCpuUsageTracker::getCpuUsageBetweenLastTwoQueries() const {
if (total_diff + total_idle_diff == 0) {
return -1.0;
}
- double percent = static_cast<double>(total_diff) / static_cast<double>(total_diff + total_idle_diff);
+ double percent = static_cast<double>(total_diff) / static_cast<double>(total_diff + total_idle_diff); // NOLINT(clang-analyzer-optin.taint.TaintedDiv)
return percent;
}
diff --git a/extension-framework/src/serialization/FlowFileV3Serializer.cpp b/extension-framework/src/serialization/FlowFileV3Serializer.cpp
index 69e0dd40d..972092ce4 100644
--- a/extension-framework/src/serialization/FlowFileV3Serializer.cpp
+++ b/extension-framework/src/serialization/FlowFileV3Serializer.cpp
@@ -84,7 +84,7 @@ int64_t FlowFileV3Serializer::serialize(const std::shared_ptr<core::FlowFile>& f
}
}
{
- const auto ret = out->write(static_cast<uint64_t>(flowFile->getSize()));
+ const auto ret = out->write(flowFile->getSize());
if (io::isError(ret)) return -1;
sum += ret;
}
diff --git a/extension-framework/src/utils/ListingStateManager.cpp b/extension-framework/src/utils/ListingStateManager.cpp
index c2f07b1d0..d56a8f445 100644
--- a/extension-framework/src/utils/ListingStateManager.cpp
+++ b/extension-framework/src/utils/ListingStateManager.cpp
@@ -27,7 +27,7 @@ static const std::string LATEST_LISTED_OBJECT_TIMESTAMP = "listed_timestamp";
bool ListingState::wasObjectListedAlready(const ListedObject &object) const {
return listed_key_timestamp > object.getLastModified() ||
- (listed_key_timestamp == object.getLastModified() && listed_keys.find(object.getKey()) != listed_keys.end());
+ (listed_key_timestamp == object.getLastModified() && listed_keys.contains(object.getKey()));
}
void ListingState::updateState(const ListedObject &object) {
@@ -62,7 +62,7 @@ uint64_t ListingStateManager::getLatestListedKeyTimestampInMilliseconds(const st
std::unordered_set<std::string> ListingStateManager::getLatestListedKeys(const std::unordered_map<std::string, std::string> &state) {
std::unordered_set<std::string> latest_listed_keys;
for (const auto& kvp : state) {
- if (kvp.first.rfind(LATEST_LISTED_OBJECT_PREFIX, 0) == 0) {
+ if (kvp.first.starts_with(LATEST_LISTED_OBJECT_PREFIX)) {
latest_listed_keys.insert(kvp.second);
}
}
diff --git a/extensions/aws/processors/PutS3Object.cpp b/extensions/aws/processors/PutS3Object.cpp
index 55502f7d3..68ddd5e47 100644
--- a/extensions/aws/processors/PutS3Object.cpp
+++ b/extensions/aws/processors/PutS3Object.cpp
@@ -69,13 +69,13 @@ void PutS3Object::onSchedule(core::ProcessContext& context, core::ProcessSession
}
multipart_threshold_ = context.getProperty(MultipartThreshold)
- | minifi::utils::andThen([&](const auto str) { return parsing::parseDataSizeMinMax(str, getMinPartSize(), getMaxUploadSize()); })
+ | minifi::utils::andThen([&](const auto& str) { return parsing::parseDataSizeMinMax(str, getMinPartSize(), getMaxUploadSize()); })
| minifi::utils::orThrow("Multipart Part Size is not between the valid 5MB and 5GB range!");
logger_->log_debug("PutS3Object: Multipart Threshold {}", multipart_threshold_);
multipart_size_ = context.getProperty(MultipartPartSize)
- | minifi::utils::andThen([&](const auto str) { return parsing::parseDataSizeMinMax(str, getMinPartSize(), getMaxUploadSize()); })
+ | minifi::utils::andThen([&](const auto& str) { return parsing::parseDataSizeMinMax(str, getMinPartSize(), getMaxUploadSize()); })
| minifi::utils::orThrow("Multipart Part Size is not between the valid 5MB and 5GB range!");
diff --git a/extensions/azure/processors/FetchAzureDataLakeStorage.cpp b/extensions/azure/processors/FetchAzureDataLakeStorage.cpp
index d5cd64edf..fa51c21f4 100644
--- a/extensions/azure/processors/FetchAzureDataLakeStorage.cpp
+++ b/extensions/azure/processors/FetchAzureDataLakeStorage.cpp
@@ -40,17 +40,17 @@ std::optional<storage::FetchAzureDataLakeStorageParameters> FetchAzureDataLakeSt
}
if (auto range_start = utils::parseOptionalU64Property(context, RangeStart, &flow_file)) {
- params.range_start = *range_start;
+ params.range_start = range_start;
logger_->log_debug("Range Start property set to {}", *params.range_start);
}
if (auto range_length = utils::parseOptionalU64Property(context, RangeLength, &flow_file)) {
- params.range_length = *range_length;
+ params.range_length = range_length;
logger_->log_debug("Range Length property set to {}", *params.range_length);
}
if (auto number_of_retries = utils::parseOptionalU64Property(context, NumberOfRetries, &flow_file)) {
- params.number_of_retries = *number_of_retries;
+ params.number_of_retries = number_of_retries;
logger_->log_debug("Number Of Retries property set to {}", *params.number_of_retries);
}
diff --git a/extensions/azure/processors/PutAzureDataLakeStorage.cpp b/extensions/azure/processors/PutAzureDataLakeStorage.cpp
index 192e5d731..8e96b98a1 100644
--- a/extensions/azure/processors/PutAzureDataLakeStorage.cpp
+++ b/extensions/azure/processors/PutAzureDataLakeStorage.cpp
@@ -123,7 +123,7 @@ int64_t PutAzureDataLakeStorage::ReadCallback::operator()(const std::shared_ptr<
}
result_ = azure_data_lake_storage_.uploadFile(params_, buffer);
- return read_ret;
+ return gsl::narrow<int64_t>(read_ret);
}
REGISTER_RESOURCE(PutAzureDataLakeStorage, Processor);
diff --git a/extensions/civetweb/processors/ListenHTTP.cpp b/extensions/civetweb/processors/ListenHTTP.cpp
index 9bccbcb73..982c30b79 100644
--- a/extensions/civetweb/processors/ListenHTTP.cpp
+++ b/extensions/civetweb/processors/ListenHTTP.cpp
@@ -486,7 +486,7 @@ void ListenHTTP::Handler::writeBody(core::ProcessSession* payload_reader, mg_con
}
bool ListenHTTP::isSecure() const {
- return (listeningPort.length() > 0) && *listeningPort.rbegin() == 's';
+ return !listeningPort.empty() && *listeningPort.rbegin() == 's';
}
std::string ListenHTTP::getPort() const {
diff --git a/extensions/execute-process/ExecuteProcess.cpp b/extensions/execute-process/ExecuteProcess.cpp
index 276663dcd..03e696a26 100644
--- a/extensions/execute-process/ExecuteProcess.cpp
+++ b/extensions/execute-process/ExecuteProcess.cpp
@@ -158,7 +158,7 @@ void ExecuteProcess::readOutput(core::ProcessSession& session) const {
std::shared_ptr<core::FlowFile> flow_file;
auto num_read = read(pipefd_[0], buf_ptr, buffer.size());
while (num_read > 0) {
- if (num_read == static_cast<ssize_t>(buffer.size() - read_to_buffer)) {
+ if (num_read == static_cast<ssize_t>(buffer.size() - read_to_buffer)) { // NOLINT(modernize-use-integer-sign-comparison)
// we reach the max buffer size
logger_->log_debug("Execute Command Max Respond {}", buffer.size());
if (!writeToFlowFile(session, flow_file, buffer)) {
diff --git a/extensions/gcp/tests/GCPCredentialsControllerServiceTests.cpp b/extensions/gcp/tests/GCPCredentialsControllerServiceTests.cpp
index 549fa681e..969865a74 100644
--- a/extensions/gcp/tests/GCPCredentialsControllerServiceTests.cpp
+++ b/extensions/gcp/tests/GCPCredentialsControllerServiceTests.cpp
@@ -74,7 +74,7 @@ class GCPCredentialsTests : public ::testing::Test {
ASSERT_TRUE(gcp_credentials_);
plan_->addProcessor("DummyProcessor", "dummy_processor");
}
- TestController test_controller_{};
+ TestController test_controller_;
std::shared_ptr<TestPlan> plan_ = test_controller_.createPlan();
std::shared_ptr<minifi::core::controller::ControllerServiceNode> gcp_credentials_node_ = plan_->addController("GCPCredentialsControllerService", "gcp_credentials_controller_service");
std::shared_ptr<GCPCredentialsControllerService> gcp_credentials_ = std::dynamic_pointer_cast<GCPCredentialsControllerService>(gcp_credentials_node_->getControllerServiceImplementation());
diff --git a/extensions/kafka/PublishKafka.cpp b/extensions/kafka/PublishKafka.cpp
index 9fd2a0f77..7c6c0912c 100644
--- a/extensions/kafka/PublishKafka.cpp
+++ b/extensions/kafka/PublishKafka.cpp
@@ -112,7 +112,7 @@ class PublishKafka::Messages {
}
template<typename Func>
- auto modifyResult(size_t index, Func fun) -> decltype(fun(flow_files_.at(index))) {
+ auto modifyResult(size_t index, const Func& fun) -> decltype(fun(flow_files_.at(index))) {
std::unique_lock<std::mutex> lock(mutex_);
const auto notifier = gsl::finally([this] { cv_.notify_all(); });
try {
@@ -219,7 +219,7 @@ class ReadCallback {
// in case of success, rd_kafka_producev takes ownership of the headers, so we no longer need to delete it
std::ignore = callback_ptr.release();
}
- logger_->log_trace("produce enqueued flow file #{}/segment #{}: {}",
+ logger_->log_trace("produce enqueued flow file #{}/segment #{}: {}", // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks)
flow_file_index_,
segment_num,
rd_kafka_err2str(err));
@@ -353,7 +353,7 @@ void PublishKafka::onSchedule(core::ProcessContext& context, core::ProcessSessio
// Attributes to Send as Headers
attributeNameRegex_ = context.getProperty(AttributeNameRegex)
- | utils::transform([](const auto pattern_str) { return utils::Regex{std::move(pattern_str)}; })
+ | utils::transform([](auto pattern_str) { return utils::Regex{std::move(pattern_str)}; })
| utils::toOptional();
key_.brokers_ = brokers;
diff --git a/extensions/libarchive/FocusArchiveEntry.cpp b/extensions/libarchive/FocusArchiveEntry.cpp
index 50a1dda8c..acc301194 100644
--- a/extensions/libarchive/FocusArchiveEntry.cpp
+++ b/extensions/libarchive/FocusArchiveEntry.cpp
@@ -68,7 +68,6 @@ void FocusArchiveEntry::onTrigger(core::ProcessContext& context, core::ProcessSe
// For each extracted entry, import & stash to key
std::string targetEntryStashKey;
- std::string targetEntry;
for (auto &entryMetadata : archiveMetadata.entryMetadata) {
if (entryMetadata.entryType == AE_IFREG) {
diff --git a/extensions/libarchive/tests/MergeFileTests.cpp b/extensions/libarchive/tests/MergeFileTests.cpp
index e5a3adcfc..3da5b84df 100644
--- a/extensions/libarchive/tests/MergeFileTests.cpp
+++ b/extensions/libarchive/tests/MergeFileTests.cpp
@@ -639,9 +639,9 @@ TEST_CASE_METHOD(MergeTestController, "Test Merge File Attributes Keeping Only C
std::shared_ptr<core::FlowFile> flow = output_->poll(expiredFlowRecords);
auto attributes = flow->getAttributes();
- REQUIRE(attributes.find("tagUncommon") == attributes.end());
- REQUIRE(attributes.find("tagUnique1") == attributes.end());
- REQUIRE(attributes.find("tagUnique2") == attributes.end());
+ CHECK_FALSE(attributes.contains("tagUncommon"));
+ CHECK_FALSE(attributes.contains("tagUnique1"));
+ CHECK_FALSE(attributes.contains("tagUnique2"));
REQUIRE(attributes["tagCommon"] == "common");
REQUIRE(attributes["mime.type"] == "application/tar");
}
@@ -688,7 +688,7 @@ TEST_CASE_METHOD(MergeTestController, "Test Merge File Attributes Keeping All Un
std::shared_ptr<core::FlowFile> flow = output_->poll(expiredFlowRecords);
auto attributes = flow->getAttributes();
- REQUIRE(attributes.find("tagUncommon") == attributes.end());
+ CHECK_FALSE(attributes.contains("tagUncommon"));
REQUIRE(attributes["tagUnique1"] == "unique1");
REQUIRE(attributes["tagUnique2"] == "unique2");
REQUIRE(attributes["tagCommon"] == "common");
diff --git a/extensions/libarchive/tests/util/ArchiveTests.cpp b/extensions/libarchive/tests/util/ArchiveTests.cpp
index 03b0b9e3e..93cc99e6a 100644
--- a/extensions/libarchive/tests/util/ArchiveTests.cpp
+++ b/extensions/libarchive/tests/util/ArchiveTests.cpp
@@ -83,7 +83,7 @@ void build_test_archive(const std::filesystem::path& path, const TAE_MAP_T& entr
}
for (const std::string& name : order) {
- TestArchiveEntry test_entry = entries.at(name);
+ const TestArchiveEntry& test_entry = entries.at(name);
std::cout << "Adding entry: " << name << std::endl;
diff --git a/extensions/lua/LuaScriptFlowFile.cpp b/extensions/lua/LuaScriptFlowFile.cpp
index 38f23ba2f..6476adde3 100644
--- a/extensions/lua/LuaScriptFlowFile.cpp
+++ b/extensions/lua/LuaScriptFlowFile.cpp
@@ -56,20 +56,20 @@ bool LuaScriptFlowFile::setAttribute(const std::string& key, const std::string&
return flow_file_->setAttribute(key, value);
}
-bool LuaScriptFlowFile::updateAttribute(std::string key, std::string value) {
+bool LuaScriptFlowFile::updateAttribute(std::string_view key, const std::string& value) {
if (!flow_file_) {
throw std::runtime_error("Access of FlowFile after it has been released");
}
- return flow_file_->updateAttribute(std::move(key), std::move(value));
+ return flow_file_->updateAttribute(key, value);
}
-bool LuaScriptFlowFile::removeAttribute(std::string key) {
+bool LuaScriptFlowFile::removeAttribute(std::string_view key) {
if (!flow_file_) {
throw std::runtime_error("Access of FlowFile after it has been released");
}
- return flow_file_->removeAttribute(std::move(key));
+ return flow_file_->removeAttribute(key);
}
std::shared_ptr<core::FlowFile> LuaScriptFlowFile::getFlowFile() {
diff --git a/extensions/lua/LuaScriptFlowFile.h b/extensions/lua/LuaScriptFlowFile.h
index 36c3ae50a..477f23a0f 100644
--- a/extensions/lua/LuaScriptFlowFile.h
+++ b/extensions/lua/LuaScriptFlowFile.h
@@ -32,8 +32,8 @@ class LuaScriptFlowFile {
std::string getAttribute(const std::string &key);
bool setAttribute(const std::string &key, const std::string &value);
bool addAttribute(const std::string &key, const std::string &value);
- bool updateAttribute(std::string key, std::string value);
- bool removeAttribute(std::string key);
+ bool updateAttribute(std::string_view key, const std::string& value);
+ bool removeAttribute(std::string_view key);
std::shared_ptr<core::FlowFile> getFlowFile();
void releaseFlowFile();
diff --git a/extensions/opc/include/opc.h b/extensions/opc/include/opc.h
index 7be3d39a1..dee0c3347 100644
--- a/extensions/opc/include/opc.h
+++ b/extensions/opc/include/opc.h
@@ -123,7 +123,7 @@ struct NodeData {
UA_Variant* var_;
explicit NodeData(UA_Variant * var = nullptr) {
- var_ = var;
+ var_ = var; // NOLINT(clang-analyzer-optin.cplusplus.UninitializedObject)
}
void addVariant(UA_Variant * var) {
if (var_) {
diff --git a/extensions/opc/src/opc.cpp b/extensions/opc/src/opc.cpp
index fccf992c3..f8e44f6d2 100644
--- a/extensions/opc/src/opc.cpp
+++ b/extensions/opc/src/opc.cpp
@@ -160,7 +160,7 @@ Client::Client(const std::shared_ptr<core::logging::Logger>& logger, const std::
UA_ClientConfig *config_ptr = UA_Client_getConfig(client_);
config_ptr->logging = &minifi_ua_logger_;
- if (application_uri.length() > 0) {
+ if (!application_uri.empty()) {
UA_String_clear(&config_ptr->clientDescription.applicationUri);
config_ptr->clientDescription.applicationUri = UA_STRING_ALLOC(application_uri.c_str());
}
@@ -246,7 +246,6 @@ NodeData Client::getNodeData(const UA_ReferenceDescription *ref, const std::stri
request.timestampsToReturn = UA_TIMESTAMPSTORETURN_BOTH;
UA_ReadResponse response = UA_Client_Service_read(client_, request);
UA_DataValue *dv = response.results;
- auto server_timestamp = OPCDateTime2String(dv->serverTimestamp);
auto source_timestamp = OPCDateTime2String(dv->sourceTimestamp);
nodedata.attributes["Sourcetimestamp"] = source_timestamp;
UA_ReadResponse_clear(&response);
diff --git a/extensions/rocksdb-repos/tests/ProvenanceTests.cpp b/extensions/rocksdb-repos/tests/ProvenanceTests.cpp
index e63930ded..ab70db15e 100644
--- a/extensions/rocksdb-repos/tests/ProvenanceTests.cpp
+++ b/extensions/rocksdb-repos/tests/ProvenanceTests.cpp
@@ -36,7 +36,7 @@ using namespace std::literals::chrono_literals;
TEST_CASE("Test Provenance record create", "[Testprovenance::ProvenanceEventRecord]") {
auto record1 = std::make_shared<provenance::ProvenanceEventRecordImpl>(provenance::ProvenanceEventRecord::ProvenanceEventType::CREATE, "blah", "blahblah");
REQUIRE(record1->getAttributes().empty());
- REQUIRE(record1->getAlternateIdentifierUri().length() == 0);
+ REQUIRE(record1->getAlternateIdentifierUri().empty());
}
TEST_CASE("Test Provenance record serialization", "[Testprovenance::ProvenanceEventRecordSerializeDeser]") {
diff --git a/extensions/sftp/processors/ListSFTP.cpp b/extensions/sftp/processors/ListSFTP.cpp
index 3b6ce984e..0bd2975e6 100644
--- a/extensions/sftp/processors/ListSFTP.cpp
+++ b/extensions/sftp/processors/ListSFTP.cpp
@@ -384,7 +384,7 @@ bool ListSFTP::updateFromTrackingTimestampsCache(core::ProcessContext& /*context
return false;
}
for (const auto &kv : state_map) {
- if (kv.first.compare(0, strlen("id."), "id.") == 0) {
+ if (kv.first.starts_with("id.")) {
state_ids.emplace(kv.second);
}
}
@@ -420,7 +420,7 @@ void ListSFTP::listByTrackingTimestamps(
uint16_t port,
const std::string& username,
const std::string& remote_path,
- std::vector<Child>&& files) {
+ std::vector<Child> files) {
auto min_timestamp_to_list = last_listed_latest_entry_timestamp_;
/* Load state from cache file if needed */
@@ -676,7 +676,7 @@ void ListSFTP::listByTrackingEntities(
const std::string& username,
const std::string& remote_path,
std::chrono::milliseconds entity_tracking_time_window,
- std::vector<Child>&& files) {
+ std::vector<Child> files) {
/* Load state from cache file if needed */
if (!already_loaded_from_cache_) {
if (updateFromTrackingEntitiesCache(context, hostname, username, remote_path)) {
@@ -690,7 +690,7 @@ void ListSFTP::listByTrackingEntities(
time_t now = time(nullptr);
uint64_t min_timestamp_to_list = (!initial_listing_complete_ && entity_tracking_initial_listing_target_ == ENTITY_TRACKING_INITIAL_LISTING_TARGET_ALL_AVAILABLE)
- ? 0U : (now * 1000 - entity_tracking_time_window.count());
+ ? 0U : ((now * 1000) - entity_tracking_time_window.count());
/* Skip files not in the tracking window */
for (auto it = files.begin(); it != files.end(); ) {
diff --git a/extensions/sftp/processors/ListSFTP.h b/extensions/sftp/processors/ListSFTP.h
index 4ed764923..7466f879b 100644
--- a/extensions/sftp/processors/ListSFTP.h
+++ b/extensions/sftp/processors/ListSFTP.h
@@ -279,7 +279,7 @@ class ListSFTP : public SFTPProcessorBase {
uint16_t port,
const std::string& username,
const std::string& remote_path,
- std::vector<Child>&& files);
+ std::vector<Child> files);
void listByTrackingEntities(
core::ProcessContext& context,
@@ -289,7 +289,7 @@ class ListSFTP : public SFTPProcessorBase {
const std::string& username,
const std::string& remote_path,
std::chrono::milliseconds entity_tracking_time_window,
- std::vector<Child>&& files);
+ std::vector<Child> files);
};
} // namespace org::apache::nifi::minifi::processors
diff --git a/extensions/sftp/processors/SFTPProcessorBase.cpp b/extensions/sftp/processors/SFTPProcessorBase.cpp
index d6d0923c4..c06cf285d 100644
--- a/extensions/sftp/processors/SFTPProcessorBase.cpp
+++ b/extensions/sftp/processors/SFTPProcessorBase.cpp
@@ -185,9 +185,7 @@ void SFTPProcessorBase::keepaliveThreadFunc() {
connection.first.hostname,
connection.first.port,
seconds_to_next);
- if (seconds_to_next < min_wait) {
- min_wait = seconds_to_next;
- }
+ min_wait = std::min(min_wait, seconds_to_next);
} else {
logger_->log_debug("Failed to send keepalive to {}@{}:{}",
connection.first.username,
@@ -197,9 +195,7 @@ void SFTPProcessorBase::keepaliveThreadFunc() {
}
/* Avoid busy loops */
- if (min_wait < 1) {
- min_wait = 1;
- }
+ min_wait = std::max(min_wait, 1);
logger_->log_trace("Keepalive thread is going to sleep for {} s", min_wait);
keepalive_cv_.wait_for(lock, std::chrono::seconds(min_wait), [this] {
diff --git a/extensions/sftp/tests/ListThenFetchSFTPTests.cpp b/extensions/sftp/tests/ListThenFetchSFTPTests.cpp
index 60a4df000..cd821bdd3 100644
--- a/extensions/sftp/tests/ListThenFetchSFTPTests.cpp
+++ b/extensions/sftp/tests/ListThenFetchSFTPTests.cpp
@@ -158,7 +158,7 @@ class ListThenFetchSFTPTestsFixture {
}
void createFileWithModificationTimeDiff(const std::string& relative_path, const std::string& content, std::chrono::seconds modification_timediff = -5min) const {
- return createFile(relative_path, content, std::chrono::file_clock::now() + modification_timediff);
+ createFile(relative_path, content, std::chrono::file_clock::now() + modification_timediff);
}
enum TestWhere {
diff --git a/extensions/sql/data/SQLRowsetProcessor.cpp b/extensions/sql/data/SQLRowsetProcessor.cpp
index 8d7403755..01c997487 100644
--- a/extensions/sql/data/SQLRowsetProcessor.cpp
+++ b/extensions/sql/data/SQLRowsetProcessor.cpp
@@ -21,11 +21,7 @@
#include "minifi-cpp/Exception.h"
#include "utils/StringUtils.h"
-namespace org {
-namespace apache {
-namespace nifi {
-namespace minifi {
-namespace sql {
+namespace org::apache::nifi::minifi::sql {
SQLRowsetProcessor::SQLRowsetProcessor(std::unique_ptr<Rowset> rowset, std::vector<std::reference_wrapper<SQLRowSubscriber>> row_subscribers)
: rowset_(std::move(rowset)), row_subscribers_(std::move(row_subscribers)) {
@@ -104,11 +100,11 @@ void SQLRowsetProcessor::addRow(const Row& row, size_t rowCount) {
case DataType::DATE: {
const std::tm when = row.getDate(i);
- char value[128];
- if (!std::strftime(value, sizeof(value), "%Y-%m-%d %H:%M:%S", &when))
+ std::array<char, 128> value{};
+ if (!std::strftime(value.data(), value.size(), "%Y-%m-%d %H:%M:%S", &when))
throw minifi::Exception(PROCESSOR_EXCEPTION, "SQLRowsetProcessor: !strftime.");
- processColumn(name, std::string(value));
+ processColumn(name, std::string(value.data()));
}
break;
default: {
@@ -123,9 +119,4 @@ void SQLRowsetProcessor::addRow(const Row& row, size_t rowCount) {
}
}
-} /* namespace sql */
-} /* namespace minifi */
-} /* namespace nifi */
-} /* namespace apache */
-} /* namespace org */
-
+} // namespace org::apache::nifi::minifi::sql
diff --git a/extensions/sql/processors/QueryDatabaseTable.cpp b/extensions/sql/processors/QueryDatabaseTable.cpp
index d68c41d5a..3f63d7f6f 100644
--- a/extensions/sql/processors/QueryDatabaseTable.cpp
+++ b/extensions/sql/processors/QueryDatabaseTable.cpp
@@ -143,7 +143,7 @@ bool QueryDatabaseTable::loadMaxValuesFromStoredState(const std::unordered_map<s
}
}
for (auto& column : max_value_columns_) {
- if (new_max_values.find(column) == new_max_values.end()) {
+ if (!new_max_values.contains(column)) {
logger_->log_info("New maximum-value column \"{}\" specified, resetting state.", column.str());
return false;
}
diff --git a/extensions/standard-processors/processors/AttributeRollingWindow.cpp b/extensions/standard-processors/processors/AttributeRollingWindow.cpp
index 1eecb36c2..c46631b47 100644
--- a/extensions/standard-processors/processors/AttributeRollingWindow.cpp
+++ b/extensions/standard-processors/processors/AttributeRollingWindow.cpp
@@ -113,7 +113,7 @@ void AttributeRollingWindow::calculateAndSetAttributes(core::FlowFile &flow_file
}());
// https://math.stackexchange.com/questions/1720876/sums-of-squares-minus-square-of-sums
const auto avg_of_squares = std::accumulate(std::begin(sorted_values), std::end(sorted_values), 0.0, [&](double acc, double value) {
- return acc + std::pow(value, 2) / gsl::narrow_cast<double>(sorted_values.size());
+ return acc + (std::pow(value, 2) / gsl::narrow_cast<double>(sorted_values.size()));
});
const auto variance = avg_of_squares - std::pow(mean, 2);
set_aggregate("variance", variance);
diff --git a/extensions/standard-processors/processors/AttributesToJSON.cpp b/extensions/standard-processors/processors/AttributesToJSON.cpp
index 357bd9e50..866c3b1df 100644
--- a/extensions/standard-processors/processors/AttributesToJSON.cpp
+++ b/extensions/standard-processors/processors/AttributesToJSON.cpp
@@ -38,11 +38,11 @@ void AttributesToJSON::initialize() {
void AttributesToJSON::onSchedule(core::ProcessContext& context, core::ProcessSessionFactory&) {
attribute_list_ = context.getProperty(AttributesList)
- | utils::transform([](const auto attributes_list_str) { return utils::string::splitAndTrimRemovingEmpty(attributes_list_str, ","); })
+ | utils::transform([](const auto& attributes_list_str) { return utils::string::splitAndTrimRemovingEmpty(attributes_list_str, ","); })
| utils::valueOrElse([] { return std::vector<std::string>{}; });
attributes_regular_expression_ = context.getProperty(AttributesRegularExpression)
- | utils::transform([](const auto s) { return utils::Regex{s}; })
+ | utils::transform([](auto s) { return utils::Regex{std::move(s)}; })
| utils::toOptional();
write_destination_ = utils::parseEnumProperty<attributes_to_json::WriteDestination>(context, Destination);
diff --git a/extensions/standard-processors/processors/DefragmentText.cpp b/extensions/standard-processors/processors/DefragmentText.cpp
index 70d09c021..6b051682b 100644
--- a/extensions/standard-processors/processors/DefragmentText.cpp
+++ b/extensions/standard-processors/processors/DefragmentText.cpp
@@ -52,7 +52,7 @@ void DefragmentText::onSchedule(core::ProcessContext& context, core::ProcessSess
pattern_location_ = utils::parseEnumProperty<defragment_text::PatternLocation>(context, PatternLoc);
pattern_ = context.getProperty(Pattern)
- | utils::transform([](const auto pattern_str) { return utils::Regex{pattern_str}; })
+ | utils::transform([](auto pattern_str) { return utils::Regex{std::move(pattern_str)}; })
| utils::orThrow("Pattern property missing or invalid");
}
diff --git a/extensions/standard-processors/processors/PutFile.cpp b/extensions/standard-processors/processors/PutFile.cpp
index adcbda6c0..2bd822399 100644
--- a/extensions/standard-processors/processors/PutFile.cpp
+++ b/extensions/standard-processors/processors/PutFile.cpp
@@ -82,7 +82,8 @@ void PutFile::onTrigger(core::ProcessContext& context, core::ProcessSession& ses
auto dest_path = getDestinationPath(context, flow_file);
if (!dest_path) {
- return session.transfer(flow_file, Failure);
+ session.transfer(flow_file, Failure);
+ return;
}
logger_->log_trace("PutFile writing file {} into directory {}", dest_path->filename(), dest_path->parent_path());
@@ -90,15 +91,18 @@ void PutFile::onTrigger(core::ProcessContext& context, core::ProcessSession& ses
if (directoryIsFull(dest_path->parent_path())) {
logger_->log_warn("Routing to failure because the output directory {} has at least {} files, which exceeds the "
"configured max number of files", dest_path->parent_path(), *max_dest_files_);
- return session.transfer(flow_file, Failure);
+ session.transfer(flow_file, Failure);
+ return;
}
if (utils::file::exists(*dest_path)) {
logger_->log_info("Destination file {} exists; applying Conflict Resolution Strategy: {}", dest_path->string(), magic_enum::enum_name(conflict_resolution_strategy_));
if (conflict_resolution_strategy_ == FileExistsResolutionStrategy::fail) {
- return session.transfer(flow_file, Failure);
+ session.transfer(flow_file, Failure);
+ return;
} else if (conflict_resolution_strategy_ == FileExistsResolutionStrategy::ignore) {
- return session.transfer(flow_file, Success);
+ session.transfer(flow_file, Success);
+ return;
}
}
diff --git a/extensions/standard-processors/processors/PutUDP.cpp b/extensions/standard-processors/processors/PutUDP.cpp
index a20d0caeb..aa4b1eb63 100644
--- a/extensions/standard-processors/processors/PutUDP.cpp
+++ b/extensions/standard-processors/processors/PutUDP.cpp
@@ -90,7 +90,7 @@ void PutUDP::onTrigger(core::ProcessContext& context, core::ProcessSession& sess
for (const auto& resolver_entry : resolved_query) {
error.clear();
udp::socket socket(io_context);
- socket.open(resolver_entry.endpoint().protocol(), error);
+ std::ignore = socket.open(resolver_entry.endpoint().protocol(), error);
if (error) {
logger->log_debug("opening {} socket failed due to {} ", resolver_entry.endpoint().protocol() == udp::v4() ? "IPv4" : "IPv6", error.message());
continue;
diff --git a/extensions/standard-processors/processors/SplitText.cpp b/extensions/standard-processors/processors/SplitText.cpp
index 68797e26d..0e43494c5 100644
--- a/extensions/standard-processors/processors/SplitText.cpp
+++ b/extensions/standard-processors/processors/SplitText.cpp
@@ -53,7 +53,7 @@ uint8_t LineReader::getEndLineSize(size_t newline_position) {
}
void LineReader::setLastLineInfoAttributes(uint8_t endline_size, const std::optional<std::string>& starts_with) {
- const uint64_t size_from_beginning_of_stream = (current_buffer_count_ - 1) * buffer_size_ + buffer_offset_;
+ const uint64_t size_from_beginning_of_stream = ((current_buffer_count_ - 1) * buffer_size_) + buffer_offset_;
if (last_line_info_) {
LineInfo previous_line_info = *last_line_info_;
last_line_info_->offset = previous_line_info.offset + previous_line_info.size;
@@ -401,7 +401,7 @@ void SplitText::onSchedule(core::ProcessContext& context, core::ProcessSessionFa
split_text_config_.line_split_count = utils::parseU64Property(context, LineSplitCount);
logger_->log_debug("SplitText line split count: {}", split_text_config_.line_split_count);
if (const auto max_fragment_data_size_value = utils::parseOptionalDataSizeProperty(context, MaximumFragmentSize)) {
- split_text_config_.maximum_fragment_size = *max_fragment_data_size_value;
+ split_text_config_.maximum_fragment_size = max_fragment_data_size_value;
logger_->log_debug("SplitText maximum fragment size: {}", split_text_config_.maximum_fragment_size.value());
}
if (split_text_config_.maximum_fragment_size && split_text_config_.maximum_fragment_size.value() == 0) {
diff --git a/extensions/standard-processors/tests/unit/RouteTextTests.cpp b/extensions/standard-processors/tests/unit/RouteTextTests.cpp
index 75521c3cb..9b503fd30 100644
--- a/extensions/standard-processors/tests/unit/RouteTextTests.cpp
+++ b/extensions/standard-processors/tests/unit/RouteTextTests.cpp
@@ -95,7 +95,7 @@ struct RouteTextController : public TestController {
}
verifyOutputRelationship(rel, files);
}
- if (patterns.find("original") == patterns.end()) {
+ if (!patterns.contains("original")) {
// expectations on "original" were implicit
verifyOutputRelationship("original", all);
}
diff --git a/extensions/standard-processors/tests/unit/SplitTextTests.cpp b/extensions/standard-processors/tests/unit/SplitTextTests.cpp
index 53c437627..4e8297a93 100644
--- a/extensions/standard-processors/tests/unit/SplitTextTests.cpp
+++ b/extensions/standard-processors/tests/unit/SplitTextTests.cpp
@@ -81,7 +81,7 @@ TEST_CASE("Test LineReader with input larger than buffer length") {
TEST_CASE("Test LineReader with input of same size as buffer length") {
auto stream = std::make_shared<io::BufferStream>();
- std::string input = std::string(BUFFER_SIZE - 1, 'a') + "\n" + std::string(BUFFER_SIZE * 2 - 1, 'b') + "\n";
+ std::string input = std::string(BUFFER_SIZE - 1, 'a') + "\n" + std::string((BUFFER_SIZE * 2) - 1, 'b') + "\n";
stream->write(reinterpret_cast<const uint8_t*>(input.data()), input.size());
processors::detail::LineReader reader{stream, BUFFER_SIZE};
CHECK(reader.readNextLine() == processors::detail::LineReader::LineInfo{.offset = 0, .size = BUFFER_SIZE, .endline_size = 1});
diff --git a/extensions/standard-processors/tests/unit/YamlConnectionParserTest.cpp b/extensions/standard-processors/tests/unit/YamlConnectionParserTest.cpp
index 5798f5f31..3884d8cc5 100644
--- a/extensions/standard-processors/tests/unit/YamlConnectionParserTest.cpp
+++ b/extensions/standard-processors/tests/unit/YamlConnectionParserTest.cpp
@@ -147,7 +147,6 @@ TEST_CASE("Connections components are parsed from yaml", "[YamlConfiguration]")
CHECK_THROWS(StructuredConnectionParser(connection_node, "test_node", parent_ptr, logger));
}
SECTION("With a configuration that lists keys but has no assigned values") {
- std::string serialized_yaml;
SECTION("Single relationship name left empty") {
YAML::Node yaml_node = YAML::Load(std::string {
"source name: \n"
diff --git a/extensions/standard-processors/utils/JoltUtils.cpp b/extensions/standard-processors/utils/JoltUtils.cpp
index 6b533f617..bf9392527 100644
--- a/extensions/standard-processors/utils/JoltUtils.cpp
+++ b/extensions/standard-processors/utils/JoltUtils.cpp
@@ -284,7 +284,7 @@ std::optional<std::vector<std::string_view>> Spec::Regex::match(std::string_view
}
// first fragment is at the beginning of the string
- if (str.substr(0, fragments.front().size()) != fragments.front()) {
+ if (!str.starts_with(fragments.front())) {
return std::nullopt;
}
auto it = str.begin() + fragments.front().size();
@@ -833,9 +833,9 @@ void putValue(const Spec::Context& ctx, const Spec::Destination& dest, const rap
member_value = inner_member_value.value();
} else {
auto sub_path = toString(ctx, val_ref->second);
- ctx.log([&] (auto logger) {
+ ctx.log([&] (const auto& logger) {
logger->log_trace("Could not find member at @({},{} as {}) from {}", val_ref->first, sub_path.first, sub_path.second, ctx.path());
- }, [] (auto) {});
+ }, [] (const auto&) {});
// do not write anything and do not throw
return;
}
@@ -1009,9 +1009,9 @@ void Spec::Pattern::process(const Value& val, const Context& ctx, const rapidjso
}
bool Spec::Pattern::processMember(const Context& ctx, std::string_view name, const rapidjson::Value& member, rapidjson::Document& output) const {
- auto on_exit = ctx.log([&] (auto logger) {
+ auto on_exit = ctx.log([&] (const auto& logger) {
logger->log_trace("Processing member '{}' of {}", name, ctx.path());
- }, [&] (auto logger) {
+ }, [&] (const auto& logger) {
logger->log_trace("Finished processing member '{}' of {}", name, ctx.path());
});
if (auto it = literal_indices.find(std::string{name}); it != literal_indices.end()) {
@@ -1078,9 +1078,9 @@ void Spec::Pattern::processObject(const Context& ctx, const rapidjson::Value &in
}
void Spec::Pattern::process(const Context& ctx, const rapidjson::Value &input, rapidjson::Document &output) const {
- auto on_exit = ctx.log([&] (auto logger) {
+ auto on_exit = ctx.log([&] (const auto& logger) {
logger->log_trace("Processing node at {}", ctx.path());
- }, [&] (auto logger) {
+ }, [&] (const auto& logger) {
logger->log_trace("Finished processing node at {}", ctx.path());
});
for (auto& [val_ref, dest] : values) {
@@ -1096,16 +1096,17 @@ void Spec::Pattern::process(const Context& ctx, const rapidjson::Value &input, r
Context sub_ctx = ctx.extend(ctx.matches, ctx.node);
process(dest, sub_ctx, value.value(), output);
} else {
- ctx.log([&, path_ptr = &path] (auto logger) {
+ ctx.log([&, path_ptr = &path] (const auto& logger) {
auto path_str = toString(ctx, *path_ptr);
logger->log_trace("Failed to resolve value path {} (evaled as {}) at {} (triggered from {}): {}", path_str.first, path_str.second, target->path(), ctx.path(), value.error());
- }, [&] (auto) {});
+ }, [] (const auto&) {});
// pass, non-existent member is not an error
}
}
for (auto& [key, dest] : keys) {
auto key_str = ctx.find(key.first)->matches.at(key.second);
- putValue(ctx.extend({key_str}, nullptr), dest, rapidjson::Value{key_str.data(), gsl::narrow<rapidjson::SizeType>(key_str.size()), output.GetAllocator()}, output);
+ putValue(ctx.extend({key_str}, nullptr), dest,
+ rapidjson::Value{key_str.data(), gsl::narrow<rapidjson::SizeType>(key_str.size()), output.GetAllocator()}, output); // NOLINT(bugprone-suspicious-stringview-data-usage)
}
for (auto& [value, dest] : defaults) {
Context sub_ctx = ctx.extend({value}, nullptr);
diff --git a/extensions/standard-processors/utils/JoltUtils.h b/extensions/standard-processors/utils/JoltUtils.h
index a6b0a0947..c9b208233 100644
--- a/extensions/standard-processors/utils/JoltUtils.h
+++ b/extensions/standard-processors/utils/JoltUtils.h
@@ -58,7 +58,7 @@ class Spec {
return nullptr;
}
- template<std::invocable<std::shared_ptr<core::logging::Logger>> OnEnterFn, std::invocable<std::shared_ptr<core::logging::Logger>> OnExitFn>
+ template<std::invocable<const std::shared_ptr<core::logging::Logger>&> OnEnterFn, std::invocable<const std::shared_ptr<core::logging::Logger>&> OnExitFn>
::gsl::final_action<std::function<void()>> log(OnEnterFn on_enter, OnExitFn on_exit) const {
if (logger) {
on_enter(logger);
diff --git a/extensions/systemd/ConsumeJournald.cpp b/extensions/systemd/ConsumeJournald.cpp
index cb8dfcb47..8fbe4356a 100644
--- a/extensions/systemd/ConsumeJournald.cpp
+++ b/extensions/systemd/ConsumeJournald.cpp
@@ -78,7 +78,7 @@ void ConsumeJournald::onSchedule(core::ProcessContext& context, core::ProcessSes
return process_old_messages ? journal.seekHead() : journal.seekTail();
};
worker_->enqueue([this, &seek_default] {
- const auto cursor = state_manager_->get() | utils::transform([](std::unordered_map<std::string, std::string>&& m) { return m.at(CURSOR_KEY); });
+ const auto cursor = state_manager_->get() | utils::transform([](const std::unordered_map<std::string, std::string>& m) { return m.at(CURSOR_KEY); });
if (!cursor) {
seek_default(*journal_);
} else {
diff --git a/extensions/systemd/libwrapper/LibWrapper.cpp b/extensions/systemd/libwrapper/LibWrapper.cpp
index c405b5ede..47b3e040a 100644
--- a/extensions/systemd/libwrapper/LibWrapper.cpp
+++ b/extensions/systemd/libwrapper/LibWrapper.cpp
@@ -18,16 +18,10 @@
#include "LibWrapper.h"
#include "DlopenWrapper.h"
-namespace org { namespace apache { namespace nifi { namespace minifi { namespace extensions { namespace systemd { namespace libwrapper {
+namespace org::apache::nifi::minifi::extensions::systemd::libwrapper {
std::unique_ptr<LibWrapper> createLibWrapper() {
return std::make_unique<DlopenWrapper>();
}
-} // namespace libwrapper
-} // namespace systemd
-} // namespace extensions
-} // namespace minifi
-} // namespace nifi
-} // namespace apache
-} // namespace org
+} // namespace org::apache::nifi::minifi::extensions::systemd::libwrapper
diff --git a/extensions/systemd/libwrapper/LibWrapper.h b/extensions/systemd/libwrapper/LibWrapper.h
index 0785e4eb5..164710c4f 100644
--- a/extensions/systemd/libwrapper/LibWrapper.h
+++ b/extensions/systemd/libwrapper/LibWrapper.h
@@ -23,7 +23,7 @@
#include "../Common.h"
#include "minifi-cpp/utils/gsl.h"
-namespace org { namespace apache { namespace nifi { namespace minifi { namespace extensions { namespace systemd { namespace libwrapper {
+namespace org::apache::nifi::minifi::extensions::systemd::libwrapper {
struct Journal {
virtual int seekHead() noexcept = 0;
@@ -48,10 +48,4 @@ struct LibWrapper {
std::unique_ptr<LibWrapper> createLibWrapper();
-} // namespace libwrapper
-} // namespace systemd
-} // namespace extensions
-} // namespace minifi
-} // namespace nifi
-} // namespace apache
-} // namespace org
+} // namespace org::apache::nifi::minifi::extensions::systemd::libwrapper
diff --git a/extensions/systemd/tests/ConsumeJournaldTest.cpp b/extensions/systemd/tests/ConsumeJournaldTest.cpp
index f793f740f..35d66f536 100644
--- a/extensions/systemd/tests/ConsumeJournaldTest.cpp
+++ b/extensions/systemd/tests/ConsumeJournaldTest.cpp
@@ -90,7 +90,7 @@ struct TestJournal final : libwrapper::Journal {
}
int getCursor(gsl::owner<char*>* const cursor_out) noexcept override {
- *cursor_out = gsl::owner<char*>(strdup(std::to_string(consumed).c_str()));
+ *cursor_out = gsl::owner<char*>(strdup(std::to_string(consumed).c_str())); // NOLINT(readability-redundant-casting)
return *cursor_out ? 0 : -ENOMEM;
}
diff --git a/libminifi/include/core/logging/internal/ActiveCompressor.h b/libminifi/include/core/logging/internal/ActiveCompressor.h
index 8ffaca8d4..c4de395b5 100644
--- a/libminifi/include/core/logging/internal/ActiveCompressor.h
+++ b/libminifi/include/core/logging/internal/ActiveCompressor.h
@@ -24,13 +24,7 @@
#include "LogCompressor.h"
#include "minifi-cpp/core/logging/Logger.h"
-namespace org {
-namespace apache {
-namespace nifi {
-namespace minifi {
-namespace core {
-namespace logging {
-namespace internal {
+namespace org::apache::nifi::minifi::core::logging::internal {
class ActiveCompressor {
public:
@@ -63,10 +57,4 @@ class ActiveCompressor {
std::unique_ptr<LogCompressor> compressor_;
};
-} // namespace internal
-} // namespace logging
-} // namespace core
-} // namespace minifi
-} // namespace nifi
-} // namespace apache
-} // namespace org
+} // namespace org::apache::nifi::minifi::core::logging::internal
diff --git a/libminifi/include/core/state/UpdateController.h b/libminifi/include/core/state/UpdateController.h
index 3203b5ea4..652f43f8d 100644
--- a/libminifi/include/core/state/UpdateController.h
+++ b/libminifi/include/core/state/UpdateController.h
@@ -15,8 +15,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-#ifndef LIBMINIFI_INCLUDE_CORE_STATE_UPDATECONTROLLER_H_
-#define LIBMINIFI_INCLUDE_CORE_STATE_UPDATECONTROLLER_H_
+#pragma once
#include <memory>
#include <utility>
@@ -28,11 +27,7 @@
#include "minifi-cpp/io/InputStream.h"
#include "utils/expected.h"
-namespace org {
-namespace apache {
-namespace nifi {
-namespace minifi {
-namespace state {
+namespace org::apache::nifi::minifi::state {
enum class UpdateState {
INITIATE,
@@ -211,10 +206,4 @@ class UpdateController {
std::atomic<bool> controller_running_;
};
-} // namespace state
-} // namespace minifi
-} // namespace nifi
-} // namespace apache
-} // namespace org
-
-#endif // LIBMINIFI_INCLUDE_CORE_STATE_UPDATECONTROLLER_H_
+} // namespace org::apache::nifi::minifi::state
diff --git a/libminifi/src/FlowFileRecord.cpp b/libminifi/src/FlowFileRecord.cpp
index 412537f78..46ff8dfd7 100644
--- a/libminifi/src/FlowFileRecord.cpp
+++ b/libminifi/src/FlowFileRecord.cpp
@@ -178,7 +178,7 @@ std::shared_ptr<FlowFileRecord> FlowFileRecordImpl::DeSerialize(io::InputStream&
auto file = std::make_shared<FlowFileRecordImpl>();
{
- uint64_t event_time_in_ms;
+ uint64_t event_time_in_ms = 0;
const auto ret = inStream.read(event_time_in_ms);
if (ret != 8) {
return {};
@@ -187,7 +187,7 @@ std::shared_ptr<FlowFileRecord> FlowFileRecordImpl::DeSerialize(io::InputStream&
}
{
- uint64_t entry_date_in_ms;
+ uint64_t entry_date_in_ms = 0;
const auto ret = inStream.read(entry_date_in_ms);
if (ret != 8) {
return {};
@@ -196,7 +196,7 @@ std::shared_ptr<FlowFileRecord> FlowFileRecordImpl::DeSerialize(io::InputStream&
}
{
- uint64_t lineage_start_date_in_ms;
+ uint64_t lineage_start_date_in_ms = 0;
const auto ret = inStream.read(lineage_start_date_in_ms);
if (ret != 8) {
return {};
diff --git a/libminifi/src/RemoteProcessorGroupPort.cpp b/libminifi/src/RemoteProcessorGroupPort.cpp
index 890cf5868..1dd4ef74c 100644
--- a/libminifi/src/RemoteProcessorGroupPort.cpp
+++ b/libminifi/src/RemoteProcessorGroupPort.cpp
@@ -26,6 +26,7 @@
#include <string>
#include <utility>
#include <vector>
+#include <algorithm>
#include "minifi-cpp/Exception.h"
#include "controllers/SSLContextService.h"
@@ -72,7 +73,7 @@ std::unique_ptr<sitetosite::SiteToSiteClient> RemoteProcessorGroupPort::getNextP
sitetosite::SiteToSiteClientConfiguration config(peers_[this->peer_index_].getPeer(), local_network_interface_, client_type_);
config.setSecurityContext(ssl_service);
peer_index_++;
- if (peer_index_ >= static_cast<int>(peers_.size())) {
+ if (peer_index_.load() >= static_cast<int>(peers_.size())) {
peer_index_ = 0;
}
config.setHTTPProxy(this->proxy_);
@@ -89,9 +90,7 @@ std::unique_ptr<sitetosite::SiteToSiteClient> RemoteProcessorGroupPort::getNextP
}
void RemoteProcessorGroupPort::returnProtocol(core::ProcessContext& context, std::unique_ptr<sitetosite::SiteToSiteClient> return_protocol) {
- auto count = peers_.size();
- if (context.getProcessor().getMaxConcurrentTasks() > count)
- count = context.getProcessor().getMaxConcurrentTasks();
+ auto count = std::max(static_cast<size_t>(context.getProcessor().getMaxConcurrentTasks()), peers_.size());
if (available_protocols_.size_approx() >= count) {
logger_->log_debug("not enqueueing protocol {}", getUUIDStr());
// let the memory be freed
@@ -139,15 +138,13 @@ void RemoteProcessorGroupPort::onSchedule(core::ProcessContext& context, core::P
}
// populate the site2site protocol for load balancing between them
if (!peers_.empty()) {
- auto count = peers_.size();
- if (context.getProcessor().getMaxConcurrentTasks() > count)
- count = context.getProcessor().getMaxConcurrentTasks();
+ auto count = std::max(static_cast<size_t>(context.getProcessor().getMaxConcurrentTasks()), peers_.size());
for (uint32_t i = 0; i < count; i++) {
std::unique_ptr<sitetosite::SiteToSiteClient> nextProtocol = nullptr;
sitetosite::SiteToSiteClientConfiguration config(peers_[this->peer_index_].getPeer(), this->getInterface(), client_type_);
config.setSecurityContext(ssl_service);
peer_index_++;
- if (peer_index_ >= static_cast<int>(peers_.size())) {
+ if (peer_index_.load() >= static_cast<int>(peers_.size())) {
peer_index_ = 0;
}
logger_->log_trace("Creating client");
@@ -183,8 +180,6 @@ void RemoteProcessorGroupPort::onTrigger(core::ProcessContext& context, core::Pr
RPGLatch count;
- std::string value;
-
logger_->log_trace("On trigger {}", getUUIDStr());
std::unique_ptr<sitetosite::SiteToSiteClient> protocol_ = nullptr;
diff --git a/libminifi/src/ResourceClaim.cpp b/libminifi/src/ResourceClaim.cpp
index 8f5734c0f..d1aba0825 100644
--- a/libminifi/src/ResourceClaim.cpp
+++ b/libminifi/src/ResourceClaim.cpp
@@ -64,7 +64,7 @@ ResourceClaimImpl::~ResourceClaimImpl() {
}
std::shared_ptr<ResourceClaim> ResourceClaim::create(std::shared_ptr<core::ContentRepository> repository) {
- return std::make_shared<ResourceClaimImpl>(repository);
+ return std::make_shared<ResourceClaimImpl>(std::move(repository));
}
} // namespace org::apache::nifi::minifi
diff --git a/libminifi/src/ThreadedSchedulingAgent.cpp b/libminifi/src/ThreadedSchedulingAgent.cpp
index 4befef6d9..c809a3535 100644
--- a/libminifi/src/ThreadedSchedulingAgent.cpp
+++ b/libminifi/src/ThreadedSchedulingAgent.cpp
@@ -86,7 +86,7 @@ void ThreadedSchedulingAgent::schedule(core::Processor* processor) {
std::vector<std::thread *> threads;
ThreadedSchedulingAgent *agent = this;
- for (int i = 0; i < processor->getMaxConcurrentTasks(); i++) {
+ for (uint8_t i = 0; i < processor->getMaxConcurrentTasks(); i++) {
// reference the disable function from serviceNode
processor->incrementActiveTasks();
diff --git a/libminifi/src/c2/C2Agent.cpp b/libminifi/src/c2/C2Agent.cpp
index 3519fb49e..363cf9577 100644
--- a/libminifi/src/c2/C2Agent.cpp
+++ b/libminifi/src/c2/C2Agent.cpp
@@ -357,7 +357,7 @@ void C2Agent::handle_c2_server_response(const C2ContentResponse &resp) {
}
});
- if (resp.ident.length() > 0) {
+ if (!resp.ident.empty()) {
C2Payload response(Operation::acknowledge, resp.ident, true);
enqueue_c2_response(std::move(response));
}
@@ -538,7 +538,6 @@ void C2Agent::handle_describe(const C2ContentResponse &resp) {
for (const auto &trace : traces) {
C2Payload options(Operation::acknowledge, resp.ident, true);
options.setLabel(trace.getName());
- std::string value;
for (const auto &line : trace.getTraces()) {
C2ContentResponse option(Operation::acknowledge);
option.name = line;
@@ -886,7 +885,7 @@ utils::TaskRescheduleInfo C2Agent::produce() {
std::for_each(
std::make_move_iterator(payload_batch.begin()),
std::make_move_iterator(payload_batch.end()),
- [&] (C2Payload&& payload) {
+ [&] (const C2Payload& payload) {
try {
C2Payload response = protocol_->consumePayload(payload);
enqueue_c2_server_response(std::move(response));
@@ -923,7 +922,7 @@ utils::TaskRescheduleInfo C2Agent::produce() {
utils::TaskRescheduleInfo C2Agent::consume() {
if (!responses.empty()) {
- const auto consume_success = responses.consume([this] (C2Payload&& payload) {
+ const auto consume_success = responses.consume([this] (const C2Payload& payload) {
extractPayload(payload);
});
if (!consume_success) {
diff --git a/libminifi/src/core/ClassLoader.cpp b/libminifi/src/core/ClassLoader.cpp
index b5a523fba..4f3c8d344 100644
--- a/libminifi/src/core/ClassLoader.cpp
+++ b/libminifi/src/core/ClassLoader.cpp
@@ -93,7 +93,7 @@ ClassLoader& ClassLoaderImpl::getClassLoader(const std::string& child_name) {
void ClassLoaderImpl::registerClass(const std::string &clazz, std::unique_ptr<ObjectFactory> factory) {
std::lock_guard<std::mutex> lock(internal_mutex_);
- if (loaded_factories_.find(clazz) != loaded_factories_.end()) {
+ if (loaded_factories_.contains(clazz)) {
logger_->log_error("Class '{}' is already registered at '{}'", clazz, name_);
return;
}
@@ -122,7 +122,7 @@ class ProcessorFactoryWrapper : public ObjectFactoryImpl {
[[nodiscard]] CoreComponent* createRaw(const std::string &name, const utils::Identifier &uuid) override {
auto logger = logging::LoggerFactoryBase::getAliasedLogger(getClassName(), uuid);
- return new Processor(name, uuid, factory_->create({.uuid = uuid, .name = name, .logger = logger}));
+ return new Processor(name, uuid, factory_->create({.uuid = uuid, .name = name, .logger = logger})); // NOLINT(cppcoreguidelines-owning-memory)
}
[[nodiscard]] std::string getGroupName() const override {
diff --git a/libminifi/src/core/ProcessSession.cpp b/libminifi/src/core/ProcessSession.cpp
index 4f3e289bf..1eeb5a009 100644
--- a/libminifi/src/core/ProcessSession.cpp
+++ b/libminifi/src/core/ProcessSession.cpp
@@ -86,7 +86,7 @@ ProcessSessionImpl::~ProcessSessionImpl() {
void ProcessSessionImpl::add(const std::shared_ptr<core::FlowFile> &record) {
utils::Identifier uuid = record->getUUID();
- if (updated_flowfiles_.find(uuid) != updated_flowfiles_.end()) {
+ if (updated_flowfiles_.contains(uuid)) {
throw Exception(ExceptionType::PROCESSOR_EXCEPTION, "Mustn't add file that was provided by this session");
}
added_flowfiles_[uuid].flow_file = record;
@@ -238,7 +238,7 @@ void ProcessSessionImpl::transferToCustomRelationship(const std::shared_ptr<core
}
void ProcessSessionImpl::write(const std::shared_ptr<core::FlowFile> &flow, const io::OutputStreamCallback& callback) {
- return write(*flow, callback);
+ write(*flow, callback);
}
void ProcessSessionImpl::write(core::FlowFile &flow, const io::OutputStreamCallback& callback) {
@@ -298,7 +298,8 @@ void ProcessSessionImpl::append(const std::shared_ptr<core::FlowFile> &flow, con
std::shared_ptr<ResourceClaim> claim = flow->getResourceClaim();
if (!claim) {
// No existed claim for append, we need to create new claim
- return write(flow, callback);
+ write(flow, callback);
+ return;
}
try {
@@ -457,7 +458,7 @@ detail::ReadBufferResult ProcessSessionImpl::readBuffer(const std::shared_ptr<co
return result;
}
-void ProcessSessionImpl::importFrom(io::InputStream&& stream, const std::shared_ptr<core::FlowFile> &flow) {
+void ProcessSessionImpl::importFrom(io::InputStream&& stream, const std::shared_ptr<core::FlowFile> &flow) { // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved)
importFrom(stream, flow);
}
/**
diff --git a/libminifi/src/core/ProcessSessionReadCallback.cpp b/libminifi/src/core/ProcessSessionReadCallback.cpp
index 54b531d45..139041fc2 100644
--- a/libminifi/src/core/ProcessSessionReadCallback.cpp
+++ b/libminifi/src/core/ProcessSessionReadCallback.cpp
@@ -48,7 +48,7 @@ int64_t ProcessSessionReadCallback::operator()(const std::shared_ptr<io::InputSt
const auto read = stream->read(buffer);
if (io::isError(read)) return -1;
if (read == 0) break;
- if (!tmp_file_os_.write(reinterpret_cast<char*>(buffer.data()), read)) {
+ if (!tmp_file_os_.write(reinterpret_cast<char*>(buffer.data()), gsl::narrow<std::streamsize>(read))) {
return -1;
}
size += read;
diff --git a/libminifi/src/core/logging/internal/CompressionManager.cpp b/libminifi/src/core/logging/internal/CompressionManager.cpp
index 8450c6fb3..145af75fe 100644
--- a/libminifi/src/core/logging/internal/CompressionManager.cpp
+++ b/libminifi/src/core/logging/internal/CompressionManager.cpp
@@ -34,7 +34,7 @@ std::shared_ptr<LogCompressorSink> CompressionManager::initialize(
const auto get_size = [&] (const char* const property_name) -> std::optional<size_t> {
auto size_str = properties->getString(property_name);
if (!size_str) return {};
- size_t value;
+ size_t value = 0;
if (DataSizeValue::StringToInt(*size_str, value)) {
return value;
}
diff --git a/libminifi/src/core/reporting/SiteToSiteProvenanceReportingTask.cpp b/libminifi/src/core/reporting/SiteToSiteProvenanceReportingTask.cpp
index cca76f0ea..1bb7f0239 100644
--- a/libminifi/src/core/reporting/SiteToSiteProvenanceReportingTask.cpp
+++ b/libminifi/src/core/reporting/SiteToSiteProvenanceReportingTask.cpp
@@ -166,7 +166,7 @@ void SiteToSiteProvenanceReportingTask::onTrigger(core::ProcessContext& context,
logger_->log_debug("Captured {} records", deserialized);
std::string jsonStr;
this->getJsonReport(context, session, records, jsonStr);
- if (jsonStr.length() <= 0) {
+ if (jsonStr.empty()) {
return;
}
diff --git a/libminifi/src/core/state/UpdateController.cpp b/libminifi/src/core/state/UpdateController.cpp
index 6978100f9..040cb5cd0 100644
--- a/libminifi/src/core/state/UpdateController.cpp
+++ b/libminifi/src/core/state/UpdateController.cpp
@@ -20,11 +20,7 @@
#include <utility>
#include <string>
-namespace org {
-namespace apache {
-namespace nifi {
-namespace minifi {
-namespace state {
+namespace org::apache::nifi::minifi::state {
UpdateStatus::UpdateStatus(UpdateState state, int16_t reason)
: state_(state),
@@ -43,8 +39,4 @@ int16_t UpdateStatus::getReadonCode() const {
return reason_;
}
-} /* namespace state */
-} /* namespace minifi */
-} /* namespace nifi */
-} /* namespace apache */
-} /* namespace org */
+} // namespace org::apache::nifi::minifi::state
diff --git a/libminifi/src/provenance/Provenance.cpp b/libminifi/src/provenance/Provenance.cpp
index 40a8ee225..d8ee5e723 100644
--- a/libminifi/src/provenance/Provenance.cpp
+++ b/libminifi/src/provenance/Provenance.cpp
@@ -457,7 +457,7 @@ void ProvenanceReporterImpl::commit() {
std::vector<std::pair<std::string, std::unique_ptr<io::BufferStream>>> flowData;
for (auto& event : _events) {
- std::unique_ptr<io::BufferStream> stramptr(new io::BufferStream());
+ auto stramptr = std::make_unique<io::BufferStream>();
event->serialize(*stramptr);
flowData.emplace_back(event->getUUIDStr(), std::move(stramptr));
diff --git a/libminifi/src/sitetosite/RawSocketProtocol.cpp b/libminifi/src/sitetosite/RawSocketProtocol.cpp
index 35ba9ac34..dcdd8ec66 100644
--- a/libminifi/src/sitetosite/RawSocketProtocol.cpp
+++ b/libminifi/src/sitetosite/RawSocketProtocol.cpp
@@ -557,7 +557,7 @@ bool RawSiteToSiteClient::transmitPayload(core::ProcessContext& context, core::P
std::map<std::string, std::string> attributes) {
std::shared_ptr<Transaction> transaction;
- if (payload.length() <= 0)
+ if (payload.empty())
return false;
if (peer_state_ != READY) {
diff --git a/libminifi/src/sitetosite/SiteToSiteClient.cpp b/libminifi/src/sitetosite/SiteToSiteClient.cpp
index 26fadcc07..bb26e664f 100644
--- a/libminifi/src/sitetosite/SiteToSiteClient.cpp
+++ b/libminifi/src/sitetosite/SiteToSiteClient.cpp
@@ -483,13 +483,13 @@ int16_t SiteToSiteClient::send(const utils::Identifier& transactionID, DataPacke
return -2;
}
}
- if (packet->payload_.length() == 0 && len == 0) {
+ if (packet->payload_.empty() && len == 0) {
if (flowFile->getResourceClaim() == nullptr)
logger_->log_trace("no claim");
else
logger_->log_trace("Flowfile empty {}", flowFile->getResourceClaim()->getContentFullPath());
}
- } else if (packet->payload_.length() > 0) {
+ } else if (!packet->payload_.empty()) {
len = packet->payload_.length();
{
const auto ret = transaction->getStream().write(len);
diff --git a/libminifi/test/flow-tests/FlowControllerTests.cpp b/libminifi/test/flow-tests/FlowControllerTests.cpp
index a02cd268f..9e0bb90d8 100644
--- a/libminifi/test/flow-tests/FlowControllerTests.cpp
+++ b/libminifi/test/flow-tests/FlowControllerTests.cpp
@@ -90,7 +90,7 @@ Controller Services:
)";
template<typename Fn>
-bool verifyWithBusyWait(std::chrono::milliseconds timeout, Fn&& fn) {
+bool verifyWithBusyWait(std::chrono::milliseconds timeout, const Fn& fn) {
auto start = std::chrono::steady_clock::now();
while (std::chrono::steady_clock::now() - start < timeout) {
if (fn()) {
diff --git a/libminifi/test/libtest/integration/HTTPHandlers.cpp b/libminifi/test/libtest/integration/HTTPHandlers.cpp
index fdea72c45..b76d6d089 100644
--- a/libminifi/test/libtest/integration/HTTPHandlers.cpp
+++ b/libminifi/test/libtest/integration/HTTPHandlers.cpp
@@ -406,10 +406,10 @@ void HeartbeatHandler::verifyProperties(const rapidjson::Value& operation_node,
case minifi::c2::Operation::start:
case minifi::c2::Operation::stop: {
auto operands = getOperandsOfProperties(operation_node);
- REQUIRE(operands.find("c2") != operands.end());
+ REQUIRE(operands.contains("c2"));
// FlowController is also present, but this handler has no way of knowing its UUID to test it
for (const auto& component : verify_components) {
- REQUIRE(operands.find(component) != operands.end());
+ REQUIRE(operands.contains(component));
}
break;
}
diff --git a/libminifi/test/libtest/unit/SingleProcessorTestController.cpp b/libminifi/test/libtest/unit/SingleProcessorTestController.cpp
index 04ca5c276..fe2a04fc7 100644
--- a/libminifi/test/libtest/unit/SingleProcessorTestController.cpp
+++ b/libminifi/test/libtest/unit/SingleProcessorTestController.cpp
@@ -42,7 +42,7 @@ ProcessorTriggerResult SingleProcessorTestController::trigger() {
return result;
}
-ProcessorTriggerResult SingleProcessorTestController::trigger(InputFlowFileData&& input_flow_file_data) {
+ProcessorTriggerResult SingleProcessorTestController::trigger(InputFlowFileData input_flow_file_data) {
input_->put(createFlowFile(input_flow_file_data.content, std::move(input_flow_file_data.attributes)));
return trigger();
}
@@ -84,7 +84,7 @@ core::Relationship SingleProcessorTestController::addDynamicRelationship(std::st
return relationship;
}
-std::shared_ptr<core::FlowFile> SingleProcessorTestController::createFlowFile(const std::string_view content, std::unordered_map<std::string, std::string> attributes) {
+std::shared_ptr<core::FlowFile> SingleProcessorTestController::createFlowFile(const std::string_view content, std::unordered_map<std::string, std::string> attributes) const {
const auto flow_file = std::make_shared<FlowFileRecordImpl>();
for (auto& attr : std::move(attributes)) {
flow_file->setAttribute(attr.first, std::move(attr.second));
diff --git a/libminifi/test/libtest/unit/SingleProcessorTestController.h b/libminifi/test/libtest/unit/SingleProcessorTestController.h
index a12caa9a5..61acebc29 100644
--- a/libminifi/test/libtest/unit/SingleProcessorTestController.h
+++ b/libminifi/test/libtest/unit/SingleProcessorTestController.h
@@ -52,7 +52,7 @@ class SingleProcessorTestController : public TestController {
}
ProcessorTriggerResult trigger();
- ProcessorTriggerResult trigger(InputFlowFileData&& input_flow_file_data);
+ ProcessorTriggerResult trigger(InputFlowFileData input_flow_file_data);
ProcessorTriggerResult trigger(const std::string_view input_flow_file_content, std::unordered_map<std::string, std::string> input_flow_file_attributes = {});
ProcessorTriggerResult trigger(std::vector<InputFlowFileData>&& input_flow_file_datas);
bool triggerUntil(const std::unordered_map<core::Relationship, size_t>& expected_quantities,
@@ -70,7 +70,7 @@ class SingleProcessorTestController : public TestController {
std::shared_ptr<TestPlan> plan = createPlan();
private:
- std::shared_ptr<core::FlowFile> createFlowFile(const std::string_view content, std::unordered_map<std::string, std::string> attributes);
+ std::shared_ptr<core::FlowFile> createFlowFile(const std::string_view content, std::unordered_map<std::string, std::string> attributes) const;
core::Processor* processor_ = nullptr;
std::unordered_map<core::Relationship, Connection*> outgoing_connections_;
diff --git a/libminifi/test/libtest/unit/TestUtils.cpp b/libminifi/test/libtest/unit/TestUtils.cpp
index ba4ee1f53..c1f18ba6b 100644
--- a/libminifi/test/libtest/unit/TestUtils.cpp
+++ b/libminifi/test/libtest/unit/TestUtils.cpp
@@ -174,7 +174,7 @@ std::error_code sendMessagesViaTCP(const std::vector<std::string_view>& contents
asio::io_context io_context;
asio::ip::tcp::socket socket(io_context);
std::error_code err;
- socket.connect(remote_endpoint, err);
+ std::ignore = socket.connect(remote_endpoint, err);
if (err)
return err;
for (auto& content : contents) {
@@ -192,7 +192,7 @@ std::error_code sendUdpDatagram(const asio::const_buffer content, const asio::ip
asio::io_context io_context;
asio::ip::udp::socket socket(io_context);
std::error_code err;
- socket.open(remote_endpoint.protocol(), err);
+ std::ignore = socket.open(remote_endpoint.protocol(), err);
if (err)
return err;
socket.send_to(content, remote_endpoint, 0, err);
@@ -211,7 +211,7 @@ bool isIPv6Disabled() {
asio::io_context io_context;
std::error_code error_code;
asio::ip::tcp::socket socket_tcp(io_context);
- socket_tcp.connect(asio::ip::tcp::endpoint(asio::ip::address_v6::loopback(), 10), error_code);
+ std::ignore = socket_tcp.connect(asio::ip::tcp::endpoint(asio::ip::address_v6::loopback(), 10), error_code);
return error_code.value() == EADDRNOTAVAIL;
}
@@ -233,15 +233,15 @@ std::error_code sendMessagesViaSSL(const std::vector<std::string_view>& contents
asio::ssl::stream<asio::ip::tcp::socket> socket(io_context, ctx);
auto shutdown_socket = gsl::finally([&] {
asio::error_code ec;
- socket.lowest_layer().cancel(ec);
- socket.shutdown(ec);
+ std::ignore = socket.lowest_layer().cancel(ec);
+ std::ignore = socket.shutdown(ec);
});
asio::error_code err;
- socket.lowest_layer().connect(remote_endpoint, err);
+ std::ignore = socket.lowest_layer().connect(remote_endpoint, err);
if (err) {
return err;
}
- socket.handshake(asio::ssl::stream_base::client, err);
+ std::ignore = socket.handshake(asio::ssl::stream_base::client, err);
if (err) {
return err;
}
diff --git a/libminifi/test/libtest/unit/WriteToFlowFileTestProcessor.h b/libminifi/test/libtest/unit/WriteToFlowFileTestProcessor.h
index 81370e445..4e33764eb 100644
--- a/libminifi/test/libtest/unit/WriteToFlowFileTestProcessor.h
+++ b/libminifi/test/libtest/unit/WriteToFlowFileTestProcessor.h
@@ -15,6 +15,8 @@
* limitations under the License.
*/
+#pragma once
+
#include <string>
#include <memory>
#include <utility>
@@ -28,8 +30,6 @@
#include "minifi-cpp/core/logging/Logger.h"
#include "core/logging/LoggerConfiguration.h"
-#pragma once
-
namespace org::apache::nifi::minifi::processors {
class WriteToFlowFileTestProcessor : public core::ProcessorImpl {
diff --git a/libminifi/test/unit/EnvironmentUtilsTests.cpp b/libminifi/test/unit/EnvironmentUtilsTests.cpp
index 8f29592c3..fa252bb55 100644
--- a/libminifi/test/unit/EnvironmentUtilsTests.cpp
+++ b/libminifi/test/unit/EnvironmentUtilsTests.cpp
@@ -31,7 +31,7 @@
TEST_CASE("getenv already existing", "[getenv]") {
auto res = utils::Environment::getEnvironmentVariable("PATH");
REQUIRE(res.has_value());
- REQUIRE(0 < res->length());
+ REQUIRE(!res->empty());
}
TEST_CASE("getenv not existing", "[getenv]") {
@@ -91,6 +91,7 @@ TEST_CASE("unsetenv existing", "[unsetenv]") {
TEST_CASE("multithreaded environment manipulation", "[getenv][setenv][unsetenv]") {
std::vector<std::thread> threads;
+ threads.reserve(16U);
for (size_t i = 0U; i < 16U; i++) {
threads.emplace_back([](){
std::mt19937 gen(std::random_device { }());
@@ -107,7 +108,7 @@ TEST_CASE("multithreaded environment manipulation", "[getenv][setenv][unsetenv]"
const size_t value_len = gen() % 256;
std::vector<char> value(value_len + 1, '\0');
std::generate_n(value.begin(), value_len, [&]() -> char {
- return 'A' + gen() % static_cast<uint8_t>('Z' - 'A');
+ return gsl::narrow<char>('A' + (gen() % static_cast<uint8_t>('Z' - 'A')));
});
const bool overwrite = gen() % 2;
utils::Environment::setEnvironmentVariable(env_name.c_str(), value.data(), overwrite);
diff --git a/libminifi/test/unit/ExtendedKeyUsageTests.cpp b/libminifi/test/unit/ExtendedKeyUsageTests.cpp
index b323924b1..990496e70 100644
--- a/libminifi/test/unit/ExtendedKeyUsageTests.cpp
+++ b/libminifi/test/unit/ExtendedKeyUsageTests.cpp
@@ -42,12 +42,12 @@ std::vector<unsigned char> createDerEncodedExtendedKeyUsage(const std::vector<ui
der_encoded_key_usage[1] = gsl::narrow<unsigned char>(oids_size);
for (size_t i = 0; i < last_bytes_of_oids.size(); ++i) {
- der_encoded_key_usage[2 + OID_ENCODED_LENGTH * i] = OID_TAG;
- der_encoded_key_usage[3 + OID_ENCODED_LENGTH * i] = OID_LENGTH;
+ der_encoded_key_usage[2 + (OID_ENCODED_LENGTH * i)] = OID_TAG;
+ der_encoded_key_usage[3 + (OID_ENCODED_LENGTH * i)] = OID_LENGTH;
for (size_t j = 0; j < OID_PREFIX.size(); ++j) {
- der_encoded_key_usage[4 + j + OID_ENCODED_LENGTH * i] = OID_PREFIX[j];
+ der_encoded_key_usage[4 + j + (OID_ENCODED_LENGTH * i)] = OID_PREFIX[j];
}
- der_encoded_key_usage[4 + OID_PREFIX.size() + OID_ENCODED_LENGTH * i] = last_bytes_of_oids[i];
+ der_encoded_key_usage[4 + OID_PREFIX.size() + (OID_ENCODED_LENGTH * i)] = last_bytes_of_oids[i];
}
return der_encoded_key_usage;
}
@@ -61,11 +61,11 @@ utils::tls::EXTENDED_KEY_USAGE_unique_ptr createExtendedKeyUsage(const std::vect
}
void testIsSubsetOf(
- const utils::tls::ExtendedKeyUsage key_usage_empty,
- const utils::tls::ExtendedKeyUsage key_usage_clientauth,
- const utils::tls::ExtendedKeyUsage key_usage_clientauth_serverauth,
- const utils::tls::ExtendedKeyUsage key_usage_clientauth_serverauth_codesigning,
- const utils::tls::ExtendedKeyUsage key_usage_clientauth_serverauth_timestamping) {
+ const utils::tls::ExtendedKeyUsage& key_usage_empty,
+ const utils::tls::ExtendedKeyUsage& key_usage_clientauth,
+ const utils::tls::ExtendedKeyUsage& key_usage_clientauth_serverauth,
+ const utils::tls::ExtendedKeyUsage& key_usage_clientauth_serverauth_codesigning,
+ const utils::tls::ExtendedKeyUsage& key_usage_clientauth_serverauth_timestamping) {
REQUIRE(key_usage_empty.isSubsetOf(key_usage_empty));
REQUIRE(key_usage_empty.isSubsetOf(key_usage_clientauth));
REQUIRE(key_usage_empty.isSubsetOf(key_usage_clientauth_serverauth));
diff --git a/libminifi/test/unit/FlowFileQueueSwapTests.cpp b/libminifi/test/unit/FlowFileQueueSwapTests.cpp
index eb2fed349..9c737d86f 100644
--- a/libminifi/test/unit/FlowFileQueueSwapTests.cpp
+++ b/libminifi/test/unit/FlowFileQueueSwapTests.cpp
@@ -102,7 +102,7 @@ struct FlowFileComparator {
};
struct VerifiedQueue {
- void push(FlowFilePtr ff) {
+ void push(const FlowFilePtr& ff) {
size();
impl.push(ff);
ref_.insert(std::lower_bound(ref_.begin(), ref_.end(), ff, FlowFileComparator{}), ff);
@@ -179,7 +179,7 @@ class SwapTestController : public TestController {
queue_ = std::make_shared<VerifiedQueue>(std::static_pointer_cast<minifi::SwapManager>(flow_repo_));
}
- void setLimits(size_t min_size, size_t target_size, size_t max_size) {
+ void setLimits(size_t min_size, size_t target_size, size_t max_size) const {
queue_->impl.setMinSize(min_size);
queue_->impl.setTargetSize(target_size);
queue_->impl.setMaxSize(max_size);
@@ -190,32 +190,32 @@ class SwapTestController : public TestController {
std::initializer_list<unsigned > seconds;
};
- void verifySwapEvents(std::vector<SwapEventPattern> events) {
+ void verifySwapEvents(const std::vector<SwapEventPattern>& events) const {
REQUIRE(flow_repo_->swap_events_.size() == events.size());
size_t idx = 0;
- for (auto& pattern : events) {
+ for (const auto& pattern : events) {
REQUIRE(pattern.kind == flow_repo_->swap_events_[idx].kind);
flow_repo_->swap_events_[idx].verifyTimes(pattern.seconds);
}
}
- void clearSwapEvents() {
+ void clearSwapEvents() const {
flow_repo_->swap_events_.clear();
}
- void verifyQueue(std::initializer_list<unsigned> live, std::optional<std::initializer_list<unsigned>> inter, std::initializer_list<unsigned> swapped) {
+ void verifyQueue(std::initializer_list<unsigned> live, std::optional<std::initializer_list<unsigned>> inter, std::initializer_list<unsigned> swapped) const {
queue_->verify(live, inter, swapped);
}
- void pushAll(std::initializer_list<unsigned> seconds) {
+ void pushAll(std::initializer_list<unsigned> seconds) const {
for (auto sec : seconds) {
auto ff = std::static_pointer_cast<core::FlowFile>(std::make_shared<minifi::FlowFileRecordImpl>());
ff->setPenaltyExpiration(Timepoint{std::chrono::seconds{sec}});
- queue_->push(std::move(ff));
+ queue_->push(ff);
}
}
- void popAll(std::initializer_list<unsigned> seconds, bool check_is_work_available = false) {
+ void popAll(std::initializer_list<unsigned> seconds, bool check_is_work_available = false) const {
for (auto sec : seconds) {
if (check_is_work_available) {
REQUIRE(queue_->isWorkAvailable());
diff --git a/libminifi/test/unit/ResponseNodeLoaderTests.cpp b/libminifi/test/unit/ResponseNodeLoaderTests.cpp
index 16b1adf99..bb18aa836 100644
--- a/libminifi/test/unit/ResponseNodeLoaderTests.cpp
+++ b/libminifi/test/unit/ResponseNodeLoaderTests.cpp
@@ -50,7 +50,7 @@ class ResponseNodeLoaderTestFixture {
}
protected:
- template<typename T, typename = typename std::enable_if_t<std::is_base_of_v<minifi::core::ProcessorImpl, T>>>
+ template<typename T> requires(std::is_base_of_v<minifi::core::ProcessorImpl, T>)
minifi::utils::Identifier addProcessor(const std::string& name) {
auto processor = minifi::test::utils::make_processor<T>(name);
auto uuid = processor->getUUID();