Skip to content

Commit

Permalink
refactor: remove circular dependencies from header files (#3025)
Browse files Browse the repository at this point in the history
Co-authored-by: Eduardo Dantas <[email protected]>
  • Loading branch information
beats-dh and dudantas authored Oct 30, 2024
1 parent 6c00cc0 commit cdd68ad
Show file tree
Hide file tree
Showing 212 changed files with 8,271 additions and 6,302 deletions.
72 changes: 72 additions & 0 deletions docs/python-scripts/normalize_cpp_own_includes.py.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import os

# Path to the directory containing C++ files (.cpp)
directory_path = "path/to/src"

def normalize_include_line(line):
# Normalize the include line by removing extra spaces and using '/' as separator
return ' '.join(line.strip().split()).replace('\\', '/')

def correct_include_path(line, correct_include):
# Check if the include line matches the correct include, regardless of the path
if line.strip().startswith('#include') and ('"' + correct_include.split('/')[-1] + '"') in line:
return f'#include "{correct_include}"\n'
return line

# Function to modify files and correct their own includes
def modify_includes(directory):
for root, dirs, files in os.walk(directory):
for filename in files:
if filename.endswith('.cpp'):
file_path = os.path.join(root, filename)
correct_include = f"{os.path.relpath(root, directory).replace('\\', '/')}/{filename.replace('.cpp', '.hpp')}"

# Remove './' from the beginning of the path, if present
if correct_include.startswith('./'):
correct_include = correct_include[2:]

include_statement = f'#include "{correct_include}"\n'

with open(file_path, 'r', encoding='utf8') as file:
lines = file.readlines()

corrected_lines = []
include_found = False
include_renamed = False
include_at_correct_position = False

# Normalize lines and correct includes as necessary
for i, line in enumerate(lines):
normalized_line = normalize_include_line(line)
if correct_include in normalized_line:
# If the correct include was found and is in the correct position
include_found = True
if i == next((idx for idx, l in enumerate(lines) if l.strip().startswith('#include')), i):
include_at_correct_position = True
if include_at_correct_position:
corrected_lines.append(line) # Keep the original include if it is correct and in the right position
elif filename.replace('.cpp', '.hpp') in normalized_line:
# Replace any old version of the include with the corrected version
corrected_lines.append(correct_include_path(line, correct_include))
include_renamed = True
else:
corrected_lines.append(line)

# If the include was found but not in the correct position, or was renamed, move it to the first include position
if (include_found and not include_at_correct_position) or include_renamed:
# Remove any occurrence of the correct include that is out of place
corrected_lines = [line for line in corrected_lines if line.strip() != include_statement.strip()]
# Find the first include position and insert the correct include
first_include_index = next((i for i, line in enumerate(corrected_lines) if line.strip().startswith('#include')), len(corrected_lines))
corrected_lines.insert(first_include_index, include_statement)
# Add a blank line immediately after the first include, if necessary
if first_include_index + 1 < len(corrected_lines) and not corrected_lines[first_include_index + 1].isspace():
corrected_lines.insert(first_include_index + 1, '\n')

# Write the changes back to the file only if modifications were made
if corrected_lines != lines:
with open(file_path, 'w', encoding='utf8') as file:
file.writelines(corrected_lines)

# Call the function to modify the files
modify_includes(directory_path)
87 changes: 43 additions & 44 deletions src/account/account.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,33 +10,32 @@
#include "account/account.hpp"

#include "account/account_repository_db.hpp"
#include "config/configmanager.hpp"
#include "utils/definitions.hpp"
#include "security/argon.hpp"
#include "utils/tools.hpp"

#include "enums/account_type.hpp"
#include "enums/account_coins.hpp"
#include "enums/account_errors.hpp"
#include "enums/account_type.hpp"

Account::Account(const uint32_t &id) {
m_descriptor.clear();
m_account.id = id;
m_account.premiumRemainingDays = 0;
m_account.premiumLastDay = 0;
m_account.accountType = ACCOUNT_TYPE_NORMAL;
m_account = std::make_unique<AccountInfo>();
m_account->id = id;
m_account->premiumRemainingDays = 0;
m_account->premiumLastDay = 0;
m_account->accountType = ACCOUNT_TYPE_NORMAL;
}

Account::Account(std::string descriptor) :
m_descriptor(std::move(descriptor)) {
m_account.id = 0;
m_account.premiumRemainingDays = 0;
m_account.premiumLastDay = 0;
m_account.accountType = ACCOUNT_TYPE_NORMAL;
m_account = std::make_unique<AccountInfo>();
m_account->id = 0;
m_account->premiumRemainingDays = 0;
m_account->premiumLastDay = 0;
m_account->accountType = ACCOUNT_TYPE_NORMAL;
}

uint8_t Account::load() {
if (m_account.id != 0 && g_accountRepository().loadByID(m_account.id, m_account)) {
if (m_account->id != 0 && g_accountRepository().loadByID(m_account->id, m_account)) {
m_accLoaded = true;
return enumToValue(AccountErrors_t::Ok);
}
Expand Down Expand Up @@ -81,7 +80,7 @@ std::tuple<uint32_t, uint8_t> Account::getCoins(const uint8_t &type) const {
}

uint32_t coins = 0;
if (!g_accountRepository().getCoins(m_account.id, type, coins)) {
if (!g_accountRepository().getCoins(m_account->id, type, coins)) {
return { 0, enumToValue(AccountErrors_t::Storage) };
}

Expand All @@ -103,7 +102,7 @@ uint8_t Account::addCoins(const uint8_t &type, const uint32_t &amount, const std
return result;
}

if (!g_accountRepository().setCoins(m_account.id, type, coins + amount)) {
if (!g_accountRepository().setCoins(m_account->id, type, coins + amount)) {
return enumToValue(AccountErrors_t::Storage);
}

Expand Down Expand Up @@ -132,7 +131,7 @@ uint8_t Account::removeCoins(const uint8_t &type, const uint32_t &amount, const
return enumToValue(AccountErrors_t::RemoveCoins);
}

if (!g_accountRepository().setCoins(m_account.id, type, coins - amount)) {
if (!g_accountRepository().setCoins(m_account->id, type, coins - amount)) {
return enumToValue(AccountErrors_t::Storage);
}

Expand All @@ -150,17 +149,17 @@ void Account::registerCoinTransaction(const uint8_t &transactionType, const uint
return;
}

if (!g_accountRepository().registerCoinsTransaction(m_account.id, transactionType, amount, type, detail)) {
if (!g_accountRepository().registerCoinsTransaction(m_account->id, transactionType, amount, type, detail)) {
g_logger().error(
"Failed to register transaction: 'account:[{}], transaction "
"type:[{}], coins:[{}], coin type:[{}], description:[{}]",
m_account.id, transactionType, amount, type, detail
m_account->id, transactionType, amount, type, detail
);
}
}

[[nodiscard]] uint32_t Account::getID() const {
return m_account.id;
return m_account->id;
};

std::string Account::getDescriptor() const {
Expand All @@ -173,61 +172,61 @@ std::string Account::getPassword() {
}

std::string password;
if (!g_accountRepository().getPassword(m_account.id, password)) {
if (!g_accountRepository().getPassword(m_account->id, password)) {
password.clear();
g_logger().error("Failed to get password for account[{}]!", m_account.id);
g_logger().error("Failed to get password for account[{}]!", m_account->id);
}

return password;
}

void Account::addPremiumDays(const int32_t &days) {
auto timeLeft = std::max(0, static_cast<int>((m_account.premiumLastDay - getTimeNow()) % 86400));
setPremiumDays(m_account.premiumRemainingDays + days);
m_account.premiumDaysPurchased += days;
auto timeLeft = std::max(0, static_cast<int>((m_account->premiumLastDay - getTimeNow()) % 86400));
setPremiumDays(m_account->premiumRemainingDays + days);
m_account->premiumDaysPurchased += days;

if (timeLeft > 0) {
m_account.premiumLastDay += timeLeft;
m_account->premiumLastDay += timeLeft;
}
}

void Account::setPremiumDays(const int32_t &days) {
m_account.premiumRemainingDays = days;
m_account.premiumLastDay = getTimeNow() + (days * 86400);
m_account->premiumRemainingDays = days;
m_account->premiumLastDay = getTimeNow() + (days * 86400);

if (days <= 0) {
m_account.premiumLastDay = 0;
m_account.premiumRemainingDays = 0;
m_account->premiumLastDay = 0;
m_account->premiumRemainingDays = 0;
}
}

[[nodiscard]] uint32_t Account::getPremiumRemainingDays() const {
return m_account.premiumLastDay > getTimeNow() ? static_cast<uint32_t>((m_account.premiumLastDay - getTimeNow()) / 86400) : 0;
return m_account->premiumLastDay > getTimeNow() ? static_cast<uint32_t>((m_account->premiumLastDay - getTimeNow()) / 86400) : 0;
}

[[nodiscard]] uint32_t Account::getPremiumDaysPurchased() const {
return m_account.premiumDaysPurchased;
return m_account->premiumDaysPurchased;
}

uint8_t Account::setAccountType(const uint8_t &accountType) {
m_account.accountType = accountType;
m_account->accountType = accountType;
return enumToValue(AccountErrors_t::Ok);
}

[[nodiscard]] uint8_t Account::getAccountType() const {
return m_account.accountType;
return m_account->accountType;
}

void Account::updatePremiumTime() {
time_t lastDay = m_account.premiumLastDay;
uint32_t remainingDays = m_account.premiumRemainingDays;
time_t lastDay = m_account->premiumLastDay;
uint32_t remainingDays = m_account->premiumRemainingDays;

time_t currentTime = getTimeNow();

auto daysLeft = static_cast<int32_t>((lastDay - currentTime) / 86400);
auto timeLeft = static_cast<int32_t>((lastDay - currentTime) % 86400);

m_account.premiumRemainingDays = daysLeft > 0 ? daysLeft : 0;
m_account->premiumRemainingDays = daysLeft > 0 ? daysLeft : 0;

if (daysLeft == 0 && timeLeft == 0) {
setPremiumDays(0);
Expand All @@ -237,7 +236,7 @@ void Account::updatePremiumTime() {
setPremiumDays(0);
}

if (remainingDays == m_account.premiumRemainingDays) {
if (remainingDays == m_account->premiumRemainingDays) {
return;
}

Expand All @@ -249,14 +248,14 @@ void Account::updatePremiumTime() {
std::tuple<phmap::flat_hash_map<std::string, uint64_t>, uint8_t>
Account::getAccountPlayers() const {
auto valueToReturn = enumToValue(m_accLoaded ? AccountErrors_t::Ok : AccountErrors_t::NotInitialized);
return { m_account.players, valueToReturn };
return { m_account->players, valueToReturn };
}

void Account::setProtocolCompat(bool toggle) {
m_account.oldProtocol = toggle;
m_account->oldProtocol = toggle;
}
bool Account::getProtocolCompat() const {
return m_account.oldProtocol;
return m_account->oldProtocol;
}

bool Account::authenticate() {
Expand All @@ -269,8 +268,8 @@ bool Account::authenticate(const std::string &secret) {
}

bool Account::authenticateSession() {
if (m_account.sessionExpires < getTimeNow()) {
g_logger().error("Session expired for account[{}] expired at [{}] current time [{}]!", m_account.id, m_account.sessionExpires, getTimeNow());
if (m_account->sessionExpires < getTimeNow()) {
g_logger().error("Session expired for account[{}] expired at [{}] current time [{}]!", m_account->id, m_account->sessionExpires, getTimeNow());
return false;
}
return true;
Expand All @@ -290,9 +289,9 @@ bool Account::authenticatePassword(const std::string &password) {
}

uint32_t Account::getAccountAgeInDays() const {
return static_cast<uint32_t>(std::ceil((getTimeNow() - m_account.creationTime) / 86400));
return static_cast<uint32_t>(std::ceil((getTimeNow() - m_account->creationTime) / 86400));
}

[[nodiscard]] time_t Account::getPremiumLastDay() const {
return m_account.premiumLastDay;
return m_account->premiumLastDay;
}
6 changes: 4 additions & 2 deletions src/account/account.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@

#pragma once

#include "account/account_info.hpp"
struct AccountInfo;

class Account {
public:
explicit Account(const uint32_t &id);
explicit Account(std::string descriptor);

~Account() = default;

/** Coins
* @brief Get the amount of coins that the account has from database.
*
Expand Down Expand Up @@ -126,6 +128,6 @@ class Account {

private:
std::string m_descriptor;
AccountInfo m_account;
std::unique_ptr<AccountInfo> m_account;
bool m_accLoaded = false;
};
2 changes: 2 additions & 0 deletions src/account/account_info.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
#endif

struct AccountInfo {
~AccountInfo() = default;

uint32_t id = 0;
uint32_t premiumRemainingDays = 0;
time_t premiumLastDay = 0;
Expand Down
8 changes: 4 additions & 4 deletions src/account/account_repository.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ class AccountRepository {

static AccountRepository &getInstance();

virtual bool loadByID(const uint32_t &id, AccountInfo &acc) = 0;
virtual bool loadByEmailOrName(bool oldProtocol, const std::string &emailOrName, AccountInfo &acc) = 0;
virtual bool loadBySession(const std::string &email, AccountInfo &acc) = 0;
virtual bool save(const AccountInfo &accInfo) = 0;
virtual bool loadByID(const uint32_t &id, std::unique_ptr<AccountInfo> &acc) = 0;
virtual bool loadByEmailOrName(bool oldProtocol, const std::string &emailOrName, std::unique_ptr<AccountInfo> &acc) = 0;
virtual bool loadBySession(const std::string &email, std::unique_ptr<AccountInfo> &acc) = 0;
virtual bool save(const std::unique_ptr<AccountInfo> &accInfo) = 0;

virtual bool getCharacterByAccountIdAndName(const uint32_t &id, const std::string &name) = 0;

Expand Down
Loading

0 comments on commit cdd68ad

Please sign in to comment.