diff --git a/.clang-format b/.clang-format new file mode 100644 index 00000000..755e693b --- /dev/null +++ b/.clang-format @@ -0,0 +1,15 @@ +--- +Language: Cpp +BasedOnStyle: Google + +AccessModifierOffset: -2 +AllowAllParametersOfDeclarationOnNextLine: false +AllowShortIfStatementsOnASingleLine: false +BinPackArguments: false +BinPackParameters: false +BreakConstructorInitializers: AfterColon +ConstructorInitializerAllOnOneLineOrOnePerLine: true +FixNamespaceComments: false +SpaceAfterTemplateKeyword: false +Standard: Cpp11 +... diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 81051413..c86a0f01 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -21,13 +21,9 @@ When you do make a pull request, please do so from a branch which doesn't have t ## Code Style -LOOT's JavaScript uses a slightly tweaked version of the Airbnb style, and can be automatically linted by ESLint, so isn't covered here. +The LOOT API code style is based on the [Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html). Formatting style is codified in the repository's `.clang-format` file, but is not enforced. -### C++ Code Style - -The [Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html) is used as the base, with deviations as listed below. - -#### C++ Features +### C++ Features * Static variables may contain non-POD types. * Reference arguments don't need to be `const` (ie. they can be used for output variables). @@ -36,12 +32,7 @@ The [Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html) * There's no restriction on which Boost libraries can be used. * Specialising `std::hash` is allowed. -#### Naming +### Naming * Constant, enumerator and variable names should use `camelCase` or `underscore_separators`, but they should be consistent within the same scope. * Function names should use `PascalCase` or `camelCase`, but they should be consistent within the same scope. - -#### Formatting - -* Line length doesn't matter. -* `public`, `protected` and `private` keywords should not be indented within a class declaration. diff --git a/include/loot/api.h b/include/loot/api.h index 8e7f1777..a2e54570 100644 --- a/include/loot/api.h +++ b/include/loot/api.h @@ -26,41 +26,46 @@ #define LOOT_API_H #include -#include #include +#include #include "loot/api_decorator.h" -#include "loot/game_interface.h" -#include "loot/exception/error_categories.h" -#include "loot/exception/condition_syntax_error.h" -#include "loot/exception/cyclic_interaction_error.h" -#include "loot/exception/file_access_error.h" -#include "loot/exception/git_state_error.h" #include "loot/enum/game_type.h" #include "loot/enum/log_level.h" +#include "loot/exception/condition_syntax_error.h" +#include "loot/exception/cyclic_interaction_error.h" +#include "loot/exception/error_categories.h" +#include "loot/exception/file_access_error.h" +#include "loot/exception/git_state_error.h" +#include "loot/game_interface.h" #include "loot/loot_version.h" namespace loot { /**@}*/ -/**********************************************************************//** - * @name Logging Functions - *************************************************************************/ +/**********************************************************************/ /** + * @name + *Logging + *Functions + *************************************************************************/ /**@{*/ /** * @brief Set the callback function that is called when logging. - * @details If this function is not called, the default behaviour is to + * @details If this function is not called, the default behaviour is to * print messages to the console. * @param callback * The function called when logging. The first parameter is the * level of the message being logged, and the second is the message. */ -LOOT_API void SetLoggingCallback(std::function callback); +LOOT_API void SetLoggingCallback( + std::function callback); /**@}*/ -/**********************************************************************//** - * @name Version Functions - *************************************************************************/ +/**********************************************************************/ /** + * @name + *Version + *Functions + *************************************************************************/ /**@{*/ /** @@ -81,9 +86,12 @@ LOOT_API bool IsCompatible(const unsigned int major, const unsigned int patch); /**@}*/ -/**********************************************************************//** - * @name Lifecycle Management Functions - *************************************************************************/ +/**********************************************************************/ /** + * @name + *Lifecycle + *Management + *Functions + *************************************************************************/ /**@{*/ /** @@ -108,15 +116,16 @@ LOOT_API void InitialiseLocale(const std::string& id); * sibling Data folder and by searching for the game's Registry entry. * @param game_local_path * The relative or absolute path to the game's folder in - * `%%LOCALAPPDATA%` or an empty string. If an empty string, the API will - * attempt to look up the path that `%%LOCALAPPDATA%` corresponds to. - * This parameter is provided so that systems lacking that environmental + * `%%LOCALAPPDATA%` or an empty string. If an empty string, the API + * will attempt to look up the path that `%%LOCALAPPDATA%` corresponds to. This + * parameter is provided so that systems lacking that environmental * variable (eg. Linux) can still use the API. * @returns The new game handle. */ -LOOT_API std::shared_ptr CreateGameHandle(const GameType game, - const std::string& game_path = "", - const std::string& game_local_path = ""); +LOOT_API std::shared_ptr CreateGameHandle( + const GameType game, + const std::string& game_path = "", + const std::string& game_local_path = ""); } #endif diff --git a/include/loot/api_decorator.h b/include/loot/api_decorator.h index 4080d181..8a64d730 100644 --- a/include/loot/api_decorator.h +++ b/include/loot/api_decorator.h @@ -30,15 +30,15 @@ that use this header do not need to define anything to import the symbols properly. */ #if defined(_WIN32) -# ifdef LOOT_STATIC -# define LOOT_API -# elif defined LOOT_EXPORT -# define LOOT_API __declspec(dllexport) -# else -# define LOOT_API __declspec(dllimport) -# endif +#ifdef LOOT_STATIC +#define LOOT_API +#elif defined LOOT_EXPORT +#define LOOT_API __declspec(dllexport) #else -# define LOOT_API +#define LOOT_API __declspec(dllimport) +#endif +#else +#define LOOT_API #endif #endif diff --git a/include/loot/database_interface.h b/include/loot/database_interface.h index 5706f686..b2e2b30c 100644 --- a/include/loot/database_interface.h +++ b/include/loot/database_interface.h @@ -136,8 +136,9 @@ public: * character hash will be outputted. * @returns The revision data. */ - virtual MasterlistInfo GetMasterlistRevision(const std::string& masterlist_path, - const bool get_short_id) const = 0; + virtual MasterlistInfo GetMasterlistRevision( + const std::string& masterlist_path, + const bool get_short_id) const = 0; /** * Check if the given masterlist is the latest available for a given branch. @@ -176,7 +177,8 @@ public: * @returns A vector of messages supplied in the metadata lists but not * attached to any particular plugin. */ - virtual std::vector GetGeneralMessages(bool evaluateConditions = false) const = 0; + virtual std::vector GetGeneralMessages( + bool evaluateConditions = false) const = 0; /** * @} @@ -200,32 +202,34 @@ public: * If the plugin has no metadata, PluginMetadata.IsNameOnly() * will return true. */ - virtual PluginMetadata GetPluginMetadata(const std::string& plugin, - bool includeUserMetadata = true, - bool evaluateConditions = false) const = 0; + virtual PluginMetadata GetPluginMetadata( + const std::string& plugin, + bool includeUserMetadata = true, + bool evaluateConditions = false) const = 0; /** - * @brief Get a plugin's metadata loaded from the given userlist. - * @param plugin - * The filename of the plugin to look up user-added metadata for. - * @param evaluateConditions - * If true, any metadata conditions are evaluated before the metadata - * is returned, otherwise unevaluated metadata is returned. Evaluating - * plugin metadata conditions does not clear the condition cache. - * @returns A PluginMetadata object containing the plugin's user-added - * metadata. If the plugin has no metadata, - * PluginMetadata.IsNameOnly() will return true. - */ - virtual PluginMetadata GetPluginUserMetadata(const std::string& plugin, - bool evaluateConditions = false) const = 0; + * @brief Get a plugin's metadata loaded from the given userlist. + * @param plugin + * The filename of the plugin to look up user-added metadata for. + * @param evaluateConditions + * If true, any metadata conditions are evaluated before the metadata + * is returned, otherwise unevaluated metadata is returned. Evaluating + * plugin metadata conditions does not clear the condition cache. + * @returns A PluginMetadata object containing the plugin's user-added + * metadata. If the plugin has no metadata, + * PluginMetadata.IsNameOnly() will return true. + */ + virtual PluginMetadata GetPluginUserMetadata( + const std::string& plugin, + bool evaluateConditions = false) const = 0; /** - * @brief Sets a plugin's user metadata, overwriting any existing user - * metadata. - * @param pluginMetadata - * The user metadata you want to set, with plugin.Name() being the - * filename of the plugin the metadata is for. - */ + * @brief Sets a plugin's user metadata, overwriting any existing user + * metadata. + * @param pluginMetadata + * The user metadata you want to set, with plugin.Name() being the + * filename of the plugin the metadata is for. + */ virtual void SetPluginUserMetadata(const PluginMetadata& pluginMetadata) = 0; /** @@ -238,8 +242,8 @@ public: virtual void DiscardPluginUserMetadata(const std::string& plugin) = 0; /** - * @brief Discards all loaded user metadata for all plugins, and any user-added - * general messages and known bash tags. + * @brief Discards all loaded user metadata for all plugins, and any + * user-added general messages and known bash tags. */ virtual void DiscardAllUserMetadata() = 0; diff --git a/include/loot/enum/game_type.h b/include/loot/enum/game_type.h index d90953d7..d937798d 100644 --- a/include/loot/enum/game_type.h +++ b/include/loot/enum/game_type.h @@ -25,7 +25,6 @@ along with LOOT. If not, see #ifndef LOOT_GAME_TYPE #define LOOT_GAME_TYPE - /** * The namespace used by the LOOT API. */ diff --git a/include/loot/exception/cyclic_interaction_error.h b/include/loot/exception/cyclic_interaction_error.h index 9907ddd8..5818003d 100644 --- a/include/loot/exception/cyclic_interaction_error.h +++ b/include/loot/exception/cyclic_interaction_error.h @@ -41,36 +41,34 @@ public: * @param backCycle A string describing the path from lastPlugin to * firstPlugin. */ - CyclicInteractionError(const std::string& firstPlugin, const std::string& lastPlugin, const std::string& backCycle) : - std::runtime_error("Cyclic interaction detected between plugins \"" + firstPlugin + "\" and \"" + lastPlugin + "\". Back cycle: " + backCycle), - firstPlugin_(firstPlugin), - lastPlugin_(lastPlugin), - backCycle_(backCycle) {} + CyclicInteractionError(const std::string& firstPlugin, + const std::string& lastPlugin, + const std::string& backCycle) : + std::runtime_error("Cyclic interaction detected between plugins \"" + + firstPlugin + "\" and \"" + lastPlugin + + "\". Back cycle: " + backCycle), + firstPlugin_(firstPlugin), + lastPlugin_(lastPlugin), + backCycle_(backCycle) {} /** * Get the first plugin in the chosen forward path of the cycle. * @return A plugin filename. */ - std::string getFirstPlugin() { - return firstPlugin_; - } + std::string getFirstPlugin() { return firstPlugin_; } /** * Get the first plugin in the chosen forward path of the cycle. * @return A plugin filename. */ - std::string getLastPlugin() { - return lastPlugin_; - } + std::string getLastPlugin() { return lastPlugin_; } /** * Get a description of the reverse path from the chosen last plugin to the * chosen first plugin of the cycle. * @return A string describing a path between two plugins in the plugin graph. */ - std::string getBackCycle() { - return backCycle_; - } + std::string getBackCycle() { return backCycle_; } private: const std::string firstPlugin_; diff --git a/include/loot/game_interface.h b/include/loot/game_interface.h index 7989fa97..db6cf2ef 100644 --- a/include/loot/game_interface.h +++ b/include/loot/game_interface.h @@ -72,7 +72,8 @@ public: * file if it has been identified by a previous call to * ``IdentifyMainMasterFile()``. */ - virtual void LoadPlugins(const std::vector& plugins, bool loadHeadersOnly) = 0; + virtual void LoadPlugins(const std::vector& plugins, + bool loadHeadersOnly) = 0; /** * @brief Get data for a loaded plugin. @@ -83,7 +84,8 @@ public: * until the ``LoadPlugins()`` or ``SortPlugins()`` functions are * next called or this GameInterface is destroyed. */ - virtual std::shared_ptr GetPlugin(const std::string& pluginName) const = 0; + virtual std::shared_ptr GetPlugin( + const std::string& pluginName) const = 0; /** * @brief Get a set of const references to all loaded plugins' PluginInterface @@ -92,43 +94,45 @@ public: * valid until the ``LoadPlugins()`` or ``SortPlugins()`` functions * are next called or this GameInterface is destroyed. */ - virtual std::set> GetLoadedPlugins() const = 0; + virtual std::set> GetLoadedPlugins() + const = 0; /** - * @} - * @name Sorting - * @{ - */ + * @} + * @name Sorting + * @{ + */ /** - * @brief Identify the game's main master file. - * @details When sorting, LOOT always only loads the headers of the game's - * main master file as a performance optimisation. - */ + * @brief Identify the game's main master file. + * @details When sorting, LOOT always only loads the headers of the game's + * main master file as a performance optimisation. + */ virtual void IdentifyMainMasterFile(const std::string& masterFile) = 0; /** - * @brief Calculates a new load order for the game's installed plugins - * (including inactive plugins) and outputs the sorted order. - * @details Pulls metadata from the masterlist and userlist if they are - * loaded, and reads the contents of each plugin. No changes are - * applied to the load order used by the game. This function does - * not load or evaluate the masterlist or userlist. - * @param plugins - * A vector of filenames of the plugins to sort. - * @returns A vector of the given plugin filenames in their sorted load - * order. - */ - virtual std::vector SortPlugins(const std::vector& plugins) = 0; + * @brief Calculates a new load order for the game's installed plugins + * (including inactive plugins) and outputs the sorted order. + * @details Pulls metadata from the masterlist and userlist if they are + * loaded, and reads the contents of each plugin. No changes are + * applied to the load order used by the game. This function does + * not load or evaluate the masterlist or userlist. + * @param plugins + * A vector of filenames of the plugins to sort. + * @returns A vector of the given plugin filenames in their sorted load + * order. + */ + virtual std::vector SortPlugins( + const std::vector& plugins) = 0; /** - * @} - * @name Load Order Interaction - * @{ - */ + * @} + * @name Load Order Interaction + * @{ + */ /** - * + * * @brief Load the current load order state, discarding any previously held * state. * @details This function should be called whenever the load order or active diff --git a/include/loot/metadata/conditional_metadata.h b/include/loot/metadata/conditional_metadata.h index 12700db5..4c80e11a 100644 --- a/include/loot/metadata/conditional_metadata.h +++ b/include/loot/metadata/conditional_metadata.h @@ -69,6 +69,7 @@ public: * @return The object's condition string. */ LOOT_API std::string GetCondition() const; + private: std::string condition_; }; diff --git a/include/loot/metadata/file.h b/include/loot/metadata/file.h index 581060e3..97537db5 100644 --- a/include/loot/metadata/file.h +++ b/include/loot/metadata/file.h @@ -51,7 +51,8 @@ public: * The File's condition string. * @return A File object. */ - LOOT_API File(const std::string& name, const std::string& display = "", + LOOT_API File(const std::string& name, + const std::string& display = "", const std::string& condition = ""); /** @@ -60,14 +61,14 @@ public: * @returns True if this File's name is case-insensitively lexicographically * less than the given File's name, false otherwise. */ - LOOT_API bool operator < (const File& rhs) const; + LOOT_API bool operator<(const File& rhs) const; /** * Check if two File objects are equal by comparing their filenames. * @returns True if the filenames are case-insensitively equal, false * otherwise. */ - LOOT_API bool operator == (const File& rhs) const; + LOOT_API bool operator==(const File& rhs) const; /** * Get the filename of the file. @@ -80,6 +81,7 @@ public: * @return The file's display name. */ LOOT_API std::string GetDisplayName() const; + private: std::string name_; std::string display_; diff --git a/include/loot/metadata/location.h b/include/loot/metadata/location.h index 1aa2b220..8e343b2c 100644 --- a/include/loot/metadata/location.h +++ b/include/loot/metadata/location.h @@ -58,13 +58,13 @@ public: * lexicographically less than the given Location's URL, false * otherwise. */ - LOOT_API bool operator < (const Location& rhs) const; + LOOT_API bool operator<(const Location& rhs) const; /** * Check if two Location objects are equal by comparing their URLs. * @returns True if the URLs are case-insensitively equal, false otherwise. */ - LOOT_API bool operator == (const Location& rhs) const; + LOOT_API bool operator==(const Location& rhs) const; /** * Get the object's URL. @@ -77,6 +77,7 @@ public: * @return The name of the location. */ LOOT_API std::string GetName() const; + private: std::string url_; std::string name_; diff --git a/include/loot/metadata/message.h b/include/loot/metadata/message.h index 6509431c..e27dfa2e 100644 --- a/include/loot/metadata/message.h +++ b/include/loot/metadata/message.h @@ -28,9 +28,9 @@ #include #include "loot/api_decorator.h" +#include "loot/enum/message_type.h" #include "loot/metadata/conditional_metadata.h" #include "loot/metadata/message_content.h" -#include "loot/enum/message_type.h" #include "loot/struct/simple_message.h" namespace loot { @@ -57,7 +57,8 @@ public: * A condition string. * @return A Message object. */ - LOOT_API Message(const MessageType type, const std::string& content, + LOOT_API Message(const MessageType type, + const std::string& content, const std::string& condition = ""); /** @@ -71,7 +72,8 @@ public: * A condition string. * @return A Message object. */ - LOOT_API Message(const MessageType type, const std::vector& content, + LOOT_API Message(const MessageType type, + const std::vector& content, const std::string& condition = ""); /** @@ -83,13 +85,13 @@ public: * Otherwise returns true if this Message has no content, and false * otherwise. */ - LOOT_API bool operator < (const Message& rhs) const; + LOOT_API bool operator<(const Message& rhs) const; /** * Check if two Message objects are equal by comparing their content. * @returns True if the contents are equal, false otherwise. */ - LOOT_API bool operator == (const Message& rhs) const; + LOOT_API bool operator==(const Message& rhs) const; /** * Get the message type. @@ -120,6 +122,7 @@ public: * if message text is not available for the given language. */ LOOT_API SimpleMessage ToSimpleMessage(const std::string& language) const; + private: MessageType type_; std::vector content_; diff --git a/include/loot/metadata/message_content.h b/include/loot/metadata/message_content.h index d6b16e8e..c9c7e430 100644 --- a/include/loot/metadata/message_content.h +++ b/include/loot/metadata/message_content.h @@ -77,13 +77,13 @@ public: * lexicographically less than the given MessageContent's text, false * otherwise. */ - LOOT_API bool operator < (const MessageContent& rhs) const; + LOOT_API bool operator<(const MessageContent& rhs) const; /** * Check if two MessageContent objects are equal by comparing their texts. * @returns True if the texts are case-insensitively equal, false otherwise. */ - LOOT_API bool operator == (const MessageContent& rhs) const; + LOOT_API bool operator==(const MessageContent& rhs) const; /** * Choose a MessageContent object from a vector given a language. @@ -96,8 +96,10 @@ public: * @return A MessageContent object. If the given vector is empty, a * default-constructed MessageContent is returned. */ - LOOT_API static MessageContent Choose(const std::vector content, - const std::string& language); + LOOT_API static MessageContent Choose( + const std::vector content, + const std::string& language); + private: std::string text_; std::string language_; diff --git a/include/loot/metadata/plugin_cleaning_data.h b/include/loot/metadata/plugin_cleaning_data.h index 994b59ac..f8d54596 100644 --- a/include/loot/metadata/plugin_cleaning_data.h +++ b/include/loot/metadata/plugin_cleaning_data.h @@ -87,13 +87,13 @@ public: * @returns True if this PluginCleaningData's CRC is less than the given * PluginCleaningData's CRC, false otherwise. */ - LOOT_API bool operator < (const PluginCleaningData& rhs) const; + LOOT_API bool operator<(const PluginCleaningData& rhs) const; /** * Check if two PluginCleaningData objects are equal by comparing their CRCs. * @returns True if the CRCs are equal, false otherwise. */ - LOOT_API bool operator == (const PluginCleaningData& rhs) const; + LOOT_API bool operator==(const PluginCleaningData& rhs) const; /** * Get the CRC that identifies the plugin that the cleaning data is for. @@ -143,6 +143,7 @@ public: * does not exist, the English-language MessageContent object. */ LOOT_API MessageContent ChooseInfo(const std::string& language) const; + private: uint32_t crc_; unsigned int itm_; diff --git a/include/loot/metadata/plugin_metadata.h b/include/loot/metadata/plugin_metadata.h index ad21365c..6f7f18ff 100644 --- a/include/loot/metadata/plugin_metadata.h +++ b/include/loot/metadata/plugin_metadata.h @@ -60,8 +60,9 @@ public: */ LOOT_API PluginMetadata(const std::string& name); - //Merges from the given plugin into this one, unless there is already equal metadata present. - //For 'enabled' and 'priority' metadata, use the given plugin's values, but if the 'priority' user value is zero, ignore it. + // Merges from the given plugin into this one, unless there is already equal + // metadata present. For 'enabled' and 'priority' metadata, use the given + // plugin's values, but if the 'priority' user value is zero, ignore it. /** * Merge metadata from the given PluginMetadata object into this object. * @@ -75,8 +76,9 @@ public: LOOT_API void MergeMetadata(const PluginMetadata& plugin); // Returns metadata in this plugin not in the given plugin. - //For 'enabled', use this plugin's value. - //For 'priority', use 0 if the two plugin priorities are equal, and make it not explicit. Otherwise use this plugin's value. + // For 'enabled', use this plugin's value. + // For 'priority', use 0 if the two plugin priorities are equal, and make it + // not explicit. Otherwise use this plugin's value. /** * Get metadata in this object that isn't present in the given PluginMetadata @@ -176,7 +178,8 @@ public: * The language to create the SimpleMessage objects for. * @return The plugin's messages as SimpleMessage objects. */ - LOOT_API std::vector GetSimpleMessages(const std::string& language) const; + LOOT_API std::vector GetSimpleMessages( + const std::string& language) const; /** * Set whether the plugin metadata is enabled for use during sorting or not. @@ -275,7 +278,7 @@ public: * @returns True if the plugin names are case-insensitively equal, false * otherwise. */ - LOOT_API bool operator == (const PluginMetadata& rhs) const; + LOOT_API bool operator==(const PluginMetadata& rhs) const; /** * Check if two PluginMetadata objects are not equal by comparing their name @@ -283,22 +286,22 @@ public: * @returns True if the plugin names are not case-insensitively equal, false * otherwise. */ - LOOT_API bool operator != (const PluginMetadata& rhs) const; - + LOOT_API bool operator!=(const PluginMetadata& rhs) const; /** * Check if object's name value is equal to the given string. * @returns True if the plugin name is case-insensitively equal to the given * string, false otherwise. */ - LOOT_API bool operator == (const std::string& rhs) const; + LOOT_API bool operator==(const std::string& rhs) const; /** * Check if object's name value is not equal to the given string. * @returns True if the plugin name is not case-insensitively equal to the * given string, false otherwise. */ - LOOT_API bool operator != (const std::string& rhs) const; + LOOT_API bool operator!=(const std::string& rhs) const; + private: std::string name_; bool enabled_; @@ -326,7 +329,7 @@ struct hash { * loot::PluginMetadata. * @return The hash generated from the plugin's lowercased filename. */ - size_t operator() (const loot::PluginMetadata& plugin) const { + size_t operator()(const loot::PluginMetadata& plugin) const { return hash()(plugin.GetLowercasedName()); } }; diff --git a/include/loot/metadata/priority.h b/include/loot/metadata/priority.h index 16fe27de..72ef03f6 100644 --- a/include/loot/metadata/priority.h +++ b/include/loot/metadata/priority.h @@ -79,36 +79,35 @@ public: * @return True if this Priority object's value is less than the given * Priority object's value. */ - LOOT_API bool operator < (const Priority& rhs) const; + LOOT_API bool operator<(const Priority& rhs) const; /** * Check if this Priority object is greater than another. * @return True if this Priority object's value is greater than the given * Priority object's value, false otherwise. */ - LOOT_API bool operator > (const Priority& rhs) const; + LOOT_API bool operator>(const Priority& rhs) const; /** * Check if this Priority object is greater than or equal to another. * @return True if this Priority object's value is greater than or equal to * the given Priority object's value, false otherwise. */ - LOOT_API bool operator >= (const Priority& rhs) const; + LOOT_API bool operator>=(const Priority& rhs) const; /** * Check if this Priority object is equal to another. * @return True if this Priority object's value is equal to the given * Priority object's value, false otherwise. */ - LOOT_API bool operator == (const Priority& rhs) const; - + LOOT_API bool operator==(const Priority& rhs) const; /** * Check if this Priority object is greater than a given priority value. * @return True if this Priority object's value is greater than the given * value, false otherwise. */ - LOOT_API bool operator > (const uint8_t rhs) const; + LOOT_API bool operator>(const uint8_t rhs) const; private: bool isExplicitZeroValue_; diff --git a/include/loot/metadata/tag.h b/include/loot/metadata/tag.h index 9acf3519..97001243 100644 --- a/include/loot/metadata/tag.h +++ b/include/loot/metadata/tag.h @@ -66,7 +66,7 @@ public: * lexicographically less than the given Tag's name, false * otherwise. */ - LOOT_API bool operator < (const Tag& rhs) const; + LOOT_API bool operator<(const Tag& rhs) const; /** * Check if two Tag objects are equal. @@ -74,7 +74,7 @@ public: * for removal, and the Tag names are case-insensitively equal, false * otherwise. */ - LOOT_API bool operator == (const Tag& rhs) const; + LOOT_API bool operator==(const Tag& rhs) const; /** * Check if the tag should be added. @@ -87,6 +87,7 @@ public: * @return The tag's name. */ LOOT_API std::string GetName() const; + private: std::string name_; bool addTag_; diff --git a/include/loot/plugin_interface.h b/include/loot/plugin_interface.h index 96b2bb6c..2211b970 100644 --- a/include/loot/plugin_interface.h +++ b/include/loot/plugin_interface.h @@ -86,9 +86,9 @@ public: virtual bool IsMaster() const = 0; /** - * Check if the plugin is a light master. - * @return True if plugin is a light master, false otherwise. - */ + * Check if the plugin is a light master. + * @return True if plugin is a light master, false otherwise. + */ virtual bool IsLightMaster() const = 0; /** @@ -125,7 +125,7 @@ struct hash { * loot::PluginInterface. * @return The hash generated from the plugin's lowercased filename. */ - size_t operator() (const loot::PluginInterface& plugin) const { + size_t operator()(const loot::PluginInterface& plugin) const { return hash()(plugin.GetLowercasedName()); } }; diff --git a/include/loot/struct/simple_message.h b/include/loot/struct/simple_message.h index 48346131..73a8ec2a 100644 --- a/include/loot/struct/simple_message.h +++ b/include/loot/struct/simple_message.h @@ -27,7 +27,8 @@ #include "loot/enum/message_type.h" namespace loot { -/** @brief A structure that holds the type of a message and the message string itself. */ +/** @brief A structure that holds the type of a message and the message string + * itself. */ struct SimpleMessage { /** @brief The type of the message. */ MessageType type; @@ -37,7 +38,8 @@ struct SimpleMessage { /** * @brief The message string, which may be formatted using - * [GitHub Flavored Markdown](https://help.github.com/articles/github-flavored-markdown). + * [GitHub Flavored + * Markdown](https://help.github.com/articles/github-flavored-markdown). */ std::string text; diff --git a/src/api/api.cpp b/src/api/api.cpp index 218e4c48..b6837ed7 100644 --- a/src/api/api.cpp +++ b/src/api/api.cpp @@ -42,7 +42,8 @@ std::string ResolvePath(const std::string& path) { return fs::read_symlink(path).string(); } -LOOT_API void SetLoggingCallback(std::function callback) { +LOOT_API void SetLoggingCallback( + std::function callback) { auto sink = std::make_shared(callback); auto logger = std::make_shared(LOGGER_NAME, sink); logger->set_level(spdlog::level::level_enum::trace); @@ -51,7 +52,9 @@ LOOT_API void SetLoggingCallback(std::function call spdlog::register_logger(logger); } -LOOT_API bool IsCompatible(const unsigned int versionMajor, const unsigned int versionMinor, const unsigned int versionPatch) { +LOOT_API bool IsCompatible(const unsigned int versionMajor, + const unsigned int versionMinor, + const unsigned int versionPatch) { if (versionMajor > 0) return versionMajor == loot::LootVersion::major; else @@ -63,16 +66,19 @@ LOOT_API void InitialiseLocale(const std::string& id) { boost::filesystem::path::imbue(std::locale()); } -LOOT_API std::shared_ptr CreateGameHandle(const GameType game, - const std::string& gamePath, - const std::string& gameLocalPath) { +LOOT_API std::shared_ptr CreateGameHandle( + const GameType game, + const std::string& gamePath, + const std::string& gameLocalPath) { const std::string resolvedGamePath = ResolvePath(gamePath); if (!gamePath.empty() && !fs::is_directory(resolvedGamePath)) - throw std::invalid_argument("Given game path \"" + gamePath + "\" does not resolve to a valid directory."); + throw std::invalid_argument("Given game path \"" + gamePath + + "\" does not resolve to a valid directory."); const std::string resolvedGameLocalPath = ResolvePath(gameLocalPath); if (!gameLocalPath.empty() && !fs::is_directory(resolvedGameLocalPath)) - throw std::invalid_argument("Given game path \"" + gameLocalPath + "\" does not resolve to a valid directory."); + throw std::invalid_argument("Given game path \"" + gameLocalPath + + "\" does not resolve to a valid directory."); return std::make_shared(game, resolvedGamePath, resolvedGameLocalPath); } diff --git a/src/api/api_database.cpp b/src/api/api_database.cpp index 6c80e6be..27a22346 100644 --- a/src/api/api_database.cpp +++ b/src/api/api_database.cpp @@ -24,24 +24,24 @@ #include "api/api_database.h" -#include #include +#include #include -#include "loot/exception/file_access_error.h" -#include "api/metadata/yaml/plugin_metadata.h" #include "api/game/game.h" #include "api/metadata/condition_evaluator.h" +#include "api/metadata/yaml/plugin_metadata.h" #include "api/plugin/plugin_sorter.h" +#include "loot/exception/file_access_error.h" namespace loot { ApiDatabase::ApiDatabase(const GameType gameType, const boost::filesystem::path& dataPath, std::shared_ptr gameCache, std::shared_ptr loadOrderHandler) : - gameCache_(gameCache), - conditionEvaluator_(gameType, dataPath, gameCache, loadOrderHandler) {} + gameCache_(gameCache), + conditionEvaluator_(gameType, dataPath, gameCache, loadOrderHandler) {} /////////////////////////////////// // Database Loading Functions @@ -56,7 +56,8 @@ void ApiDatabase::LoadLists(const std::string& masterlistPath, if (boost::filesystem::exists(masterlistPath)) { temp.Load(masterlistPath); } else { - throw FileAccessError("The given masterlist path does not exist: " + masterlistPath); + throw FileAccessError("The given masterlist path does not exist: " + + masterlistPath); } } @@ -64,7 +65,8 @@ void ApiDatabase::LoadLists(const std::string& masterlistPath, if (boost::filesystem::exists(userlistPath)) { userTemp.Load(userlistPath); } else { - throw FileAccessError("The given userlist path does not exist: " + userlistPath); + throw FileAccessError("The given userlist path does not exist: " + + userlistPath); } } @@ -72,12 +74,15 @@ void ApiDatabase::LoadLists(const std::string& masterlistPath, userlist_ = userTemp; } -void ApiDatabase::WriteUserMetadata(const std::string& outputFile, const bool overwrite) const { - if (!boost::filesystem::exists(boost::filesystem::path(outputFile).parent_path())) +void ApiDatabase::WriteUserMetadata(const std::string& outputFile, + const bool overwrite) const { + if (!boost::filesystem::exists( + boost::filesystem::path(outputFile).parent_path())) throw std::invalid_argument("Output directory does not exist."); if (boost::filesystem::exists(outputFile) && !overwrite) - throw FileAccessError("Output file exists but overwrite is not set to true."); + throw FileAccessError( + "Output file exists but overwrite is not set to true."); userlist_.Save(outputFile); } @@ -89,8 +94,10 @@ void ApiDatabase::WriteUserMetadata(const std::string& outputFile, const bool ov bool ApiDatabase::UpdateMasterlist(const std::string& masterlistPath, const std::string& remoteURL, const std::string& remoteBranch) { - if (!boost::filesystem::is_directory(boost::filesystem::path(masterlistPath).parent_path())) - throw std::invalid_argument("Given masterlist path \"" + masterlistPath + "\" does not have a valid parent directory."); + if (!boost::filesystem::is_directory( + boost::filesystem::path(masterlistPath).parent_path())) + throw std::invalid_argument("Given masterlist path \"" + masterlistPath + + "\" does not have a valid parent directory."); Masterlist masterlist; if (masterlist.Update(masterlistPath, remoteURL, remoteBranch)) { @@ -101,8 +108,9 @@ bool ApiDatabase::UpdateMasterlist(const std::string& masterlistPath, return false; } -MasterlistInfo ApiDatabase::GetMasterlistRevision(const std::string& masterlistPath, - const bool getShortID) const { +MasterlistInfo ApiDatabase::GetMasterlistRevision( + const std::string& masterlistPath, + const bool getShortID) const { return Masterlist::GetInfo(masterlistPath, getShortID); } @@ -126,18 +134,22 @@ std::set ApiDatabase::GetKnownBashTags() const { return masterlistTags; } -std::vector ApiDatabase::GetGeneralMessages(bool evaluateConditions) const { +std::vector ApiDatabase::GetGeneralMessages( + bool evaluateConditions) const { auto masterlistMessages = masterlist_.Messages(); auto userlistMessages = userlist_.Messages(); if (!userlistMessages.empty()) { - masterlistMessages.insert(std::end(masterlistMessages), std::begin(userlistMessages), std::end(userlistMessages)); + masterlistMessages.insert(std::end(masterlistMessages), + std::begin(userlistMessages), + std::end(userlistMessages)); } if (evaluateConditions) { // Evaluate conditions from scratch. gameCache_->ClearCachedConditions(); - for (auto it = std::begin(masterlistMessages); it != std::end(masterlistMessages);) { + for (auto it = std::begin(masterlistMessages); + it != std::end(masterlistMessages);) { if (!conditionEvaluator_.evaluate(it->GetCondition())) it = masterlistMessages.erase(it); else @@ -164,8 +176,9 @@ PluginMetadata ApiDatabase::GetPluginMetadata(const std::string& plugin, return metadata; } -PluginMetadata ApiDatabase::GetPluginUserMetadata(const std::string& plugin, - bool evaluateConditions) const { +PluginMetadata ApiDatabase::GetPluginUserMetadata( + const std::string& plugin, + bool evaluateConditions) const { PluginMetadata metadata = userlist_.FindPlugin(plugin); if (evaluateConditions) { @@ -184,20 +197,22 @@ void ApiDatabase::DiscardPluginUserMetadata(const std::string& plugin) { userlist_.ErasePlugin(plugin); } -void ApiDatabase::DiscardAllUserMetadata() { - userlist_.Clear(); -} +void ApiDatabase::DiscardAllUserMetadata() { userlist_.Clear(); } -// Writes a minimal masterlist that only contains mods that have Bash Tag suggestions, -// and/or dirty messages, plus the Tag suggestions and/or messages themselves and their -// conditions, in order to create the Wrye Bash taglist. outputFile is the path to use -// for output. If outputFile already exists, it will only be overwritten if overwrite is true. -void ApiDatabase::WriteMinimalList(const std::string& outputFile, const bool overwrite) const { - if (!boost::filesystem::exists(boost::filesystem::path(outputFile).parent_path())) +// Writes a minimal masterlist that only contains mods that have Bash Tag +// suggestions, and/or dirty messages, plus the Tag suggestions and/or messages +// themselves and their conditions, in order to create the Wrye Bash taglist. +// outputFile is the path to use for output. If outputFile already exists, it +// will only be overwritten if overwrite is true. +void ApiDatabase::WriteMinimalList(const std::string& outputFile, + const bool overwrite) const { + if (!boost::filesystem::exists( + boost::filesystem::path(outputFile).parent_path())) throw std::invalid_argument("Output directory does not exist."); if (boost::filesystem::exists(outputFile) && !overwrite) - throw FileAccessError("Output file exists but overwrite is not set to true."); + throw FileAccessError( + "Output file exists but overwrite is not set to true."); MetadataList minimalList; for (const auto& plugin : masterlist_.Plugins()) { diff --git a/src/api/api_database.h b/src/api/api_database.h index 0166884a..c394381c 100644 --- a/src/api/api_database.h +++ b/src/api/api_database.h @@ -31,9 +31,9 @@ #include "api/game/game_cache.h" #include "api/game/load_order_handler.h" +#include "api/masterlist.h" #include "api/metadata/condition_evaluator.h" #include "api/metadata_list.h" -#include "api/masterlist.h" #include "loot/database_interface.h" #include "loot/enum/game_type.h" @@ -65,7 +65,8 @@ struct ApiDatabase : public DatabaseInterface { std::set GetKnownBashTags() const; - std::vector GetGeneralMessages(bool evaluateConditions = false) const; + std::vector GetGeneralMessages( + bool evaluateConditions = false) const; PluginMetadata GetPluginMetadata(const std::string& plugin, bool includeUserMetadata = true, @@ -79,6 +80,7 @@ struct ApiDatabase : public DatabaseInterface { void DiscardPluginUserMetadata(const std::string& plugin); void DiscardAllUserMetadata(); + private: std::shared_ptr gameCache_; ConditionEvaluator conditionEvaluator_; diff --git a/src/api/error_categories.cpp b/src/api/error_categories.cpp index dd18377e..ceaef001 100644 --- a/src/api/error_categories.cpp +++ b/src/api/error_categories.cpp @@ -29,29 +29,23 @@ namespace loot { namespace detail { class libloadorder_category : public std::error_category { - virtual const char* name() const noexcept { - return "libloadorder"; - } + virtual const char* name() const noexcept { return "libloadorder"; } - virtual std::string message(int ev) const { - return "Libloadorder error"; - } + virtual std::string message(int ev) const { return "Libloadorder error"; } - virtual bool equivalent(const std::error_code& code, int condition) const noexcept { + virtual bool equivalent(const std::error_code& code, int condition) const + noexcept { return code.category().name() == name(); } }; class libgit2_category : public std::error_category { - virtual const char* name() const noexcept { - return "libgit2"; - } + virtual const char* name() const noexcept { return "libgit2"; } - virtual std::string message(int ev) const { - return "libgit2 error"; - } + virtual std::string message(int ev) const { return "libgit2 error"; } - virtual bool equivalent(const std::error_code& code, int condition) const noexcept { + virtual bool equivalent(const std::error_code& code, int condition) const + noexcept { return code.category().name() == name(); } }; diff --git a/src/api/game/game.cpp b/src/api/game/game.cpp index bfda1db0..f5e7d8c7 100644 --- a/src/api/game/game.cpp +++ b/src/api/game/game.cpp @@ -25,8 +25,8 @@ #include "api/game/game.h" #include -#include #include +#include #include @@ -36,16 +36,16 @@ #include "loot/exception/file_access_error.h" #ifdef _WIN32 -# ifndef UNICODE -# define UNICODE -# endif -# ifndef _UNICODE -# define _UNICODE -# endif -# define NOMINMAX -# include "windows.h" -# include "shlobj.h" -# include "shlwapi.h" +#ifndef UNICODE +#define UNICODE +#endif +#ifndef _UNICODE +#define _UNICODE +#endif +#define NOMINMAX +#include "shlobj.h" +#include "shlwapi.h" +#include "windows.h" #endif using std::list; @@ -59,46 +59,42 @@ namespace loot { Game::Game(const GameType gameType, const boost::filesystem::path& gamePath, const boost::filesystem::path& localDataPath) : - type_(gameType), - gamePath_(gamePath), - localDataPath_(localDataPath), - cache_(std::make_shared()), - loadOrderHandler_(std::make_shared()) { + type_(gameType), + gamePath_(gamePath), + localDataPath_(localDataPath), + cache_(std::make_shared()), + loadOrderHandler_(std::make_shared()) { auto logger = getLogger(); if (logger) { - logger->info("Initialising load order data for game of type {} at: {}", (int) type_, gamePath_.string()); + logger->info("Initialising load order data for game of type {} at: {}", + (int)type_, + gamePath_.string()); } loadOrderHandler_->Init(type_, gamePath_, localDataPath_); - database_ = std::make_shared(Type(), DataPath(), GetCache(), GetLoadOrderHandler()); + database_ = std::make_shared( + Type(), DataPath(), GetCache(), GetLoadOrderHandler()); } -GameType Game::Type() const { - return type_; -} +GameType Game::Type() const { return type_; } -boost::filesystem::path Game::DataPath() const { - return gamePath_ / "Data"; -} +boost::filesystem::path Game::DataPath() const { return gamePath_ / "Data"; } -std::shared_ptr Game::GetCache() { - return cache_; -} +std::shared_ptr Game::GetCache() { return cache_; } std::shared_ptr Game::GetLoadOrderHandler() { return loadOrderHandler_; } -std::shared_ptr Game::GetDatabase() { - return database_; -} +std::shared_ptr Game::GetDatabase() { return database_; } bool Game::IsValidPlugin(const std::string& plugin) const { return Plugin::IsValid(plugin, Type(), DataPath()); } -void Game::LoadPlugins(const std::vector& plugins, bool loadHeadersOnly) { +void Game::LoadPlugins(const std::vector& plugins, + bool loadHeadersOnly) { auto logger = getLogger(); uintmax_t meanFileSize = 0; std::multimap sizeMap; @@ -117,18 +113,24 @@ void Game::LoadPlugins(const std::vector& plugins, bool loadHeaders else sizeMap.emplace(fileSize, plugin); } - meanFileSize /= sizeMap.size(); //Rounding error, but not important. + meanFileSize /= sizeMap.size(); // Rounding error, but not important. - // Get the number of threads to use. - // hardware_concurrency() may be zero, if so then use only one thread. - size_t threadsToUse = ::std::min((size_t)thread::hardware_concurrency(), sizeMap.size()); + // Get the number of threads to use. + // hardware_concurrency() may be zero, if so then use only one thread. + size_t threadsToUse = + ::std::min((size_t)thread::hardware_concurrency(), sizeMap.size()); threadsToUse = ::std::max(threadsToUse, (size_t)1); // Divide the plugins up by thread. unsigned int pluginsPerThread = ceil((double)sizeMap.size() / threadsToUse); vector> pluginGroups(threadsToUse); if (logger) { - logger->info("Loading {} plugins using {} threads, with up to {} plugins per thread.", sizeMap.size(), threadsToUse, pluginsPerThread); + logger->info( + "Loading {} plugins using {} threads, with up to {} plugins per " + "thread.", + sizeMap.size(), + threadsToUse, + pluginsPerThread); } // The plugins should be split between the threads so that the data @@ -140,7 +142,8 @@ void Game::LoadPlugins(const std::vector& plugins, bool loadHeaders } if (logger) { - logger->trace("Adding plugin {} to loading group {}", plugin.second, currentGroup); + logger->trace( + "Adding plugin {} to loading group {}", plugin.second, currentGroup); } pluginGroups[currentGroup].push_back(plugin.second); @@ -163,12 +166,17 @@ void Game::LoadPlugins(const std::vector& plugins, bool loadHeaders if (logger) { logger->trace("Loading {}", pluginName); } - const bool loadHeader = boost::iequals(pluginName, masterFile_) || loadHeadersOnly; + const bool loadHeader = + boost::iequals(pluginName, masterFile_) || loadHeadersOnly; try { - cache_->AddPlugin(Plugin(Type(), DataPath(), loadOrderHandler_, pluginName, loadHeader)); - } catch(std::exception& e) { + cache_->AddPlugin(Plugin( + Type(), DataPath(), loadOrderHandler_, pluginName, loadHeader)); + } catch (std::exception& e) { if (logger) { - logger->trace("Caught exception while trying to add {} to the cache: {}", pluginName, e.what()); + logger->trace( + "Caught exception while trying to add {} to the cache: {}", + pluginName, + e.what()); } } } @@ -182,14 +190,18 @@ void Game::LoadPlugins(const std::vector& plugins, bool loadHeaders } } -std::shared_ptr Game::GetPlugin(const std::string& pluginName) const { - return std::static_pointer_cast(cache_->GetPlugin(pluginName)); +std::shared_ptr Game::GetPlugin( + const std::string& pluginName) const { + return std::static_pointer_cast( + cache_->GetPlugin(pluginName)); } -std::set> Game::GetLoadedPlugins() const { +std::set> Game::GetLoadedPlugins() + const { std::set> interfacePointers; for (auto& plugin : cache_->GetPlugins()) { - interfacePointers.insert(std::static_pointer_cast(plugin)); + interfacePointers.insert( + std::static_pointer_cast(plugin)); } return interfacePointers; @@ -199,10 +211,11 @@ void Game::IdentifyMainMasterFile(const std::string& masterFile) { masterFile_ = masterFile; } -std::vector Game::SortPlugins(const std::vector& plugins) { +std::vector Game::SortPlugins( + const std::vector& plugins) { LoadPlugins(plugins, false); - //Sort plugins into their load order. + // Sort plugins into their load order. PluginSorter sorter; return sorter.Sort(*this); } @@ -213,7 +226,8 @@ void Game::LoadCurrentLoadOrderState() { bool Game::IsPluginActive(const std::string& plugin) const { try { - return std::static_pointer_cast(GetPlugin(plugin))->IsActive(); + return std::static_pointer_cast(GetPlugin(plugin)) + ->IsActive(); } catch (...) { return loadOrderHandler_->IsPluginActive(plugin); } diff --git a/src/api/game/game.h b/src/api/game/game.h index 43657ba6..53fe2e72 100644 --- a/src/api/game/game.h +++ b/src/api/game/game.h @@ -56,9 +56,11 @@ public: bool IsValidPlugin(const std::string& plugin) const; - void LoadPlugins(const std::vector& plugins, bool loadHeadersOnly); + void LoadPlugins(const std::vector& plugins, + bool loadHeadersOnly); - std::shared_ptr GetPlugin(const std::string& pluginName) const; + std::shared_ptr GetPlugin( + const std::string& pluginName) const; std::set> GetLoadedPlugins() const; @@ -73,6 +75,7 @@ public: std::vector GetLoadOrder() const; void SetLoadOrder(const std::vector& loadOrder); + private: std::shared_ptr cache_; std::shared_ptr loadOrderHandler_; diff --git a/src/api/game/game_cache.cpp b/src/api/game/game_cache.cpp index c92fe182..750bf71a 100644 --- a/src/api/game/game_cache.cpp +++ b/src/api/game/game_cache.cpp @@ -39,8 +39,8 @@ namespace loot { GameCache::GameCache() {} GameCache::GameCache(const GameCache& cache) : - conditions_(cache.conditions_), - plugins_(cache.plugins_) {} + conditions_(cache.conditions_), + plugins_(cache.plugins_) {} GameCache& GameCache::operator=(const GameCache& cache) { if (&cache != this) { @@ -56,7 +56,8 @@ void GameCache::CacheCondition(const std::string& condition, bool result) { conditions_.insert(pair(to_lower(condition), result)); } -std::pair GameCache::GetCachedCondition(const std::string& condition) const { +std::pair GameCache::GetCachedCondition( + const std::string& condition) const { lock_guard guard(mutex_); auto it = conditions_.find(to_lower(condition)); @@ -69,16 +70,19 @@ std::pair GameCache::GetCachedCondition(const std::string& condition std::set> GameCache::GetPlugins() const { std::set> output; - std::transform(begin(plugins_), - end(plugins_), - std::inserter>>(output, begin(output)), - [](const pair>& pluginPair) { - return pluginPair.second; - }); + std::transform( + begin(plugins_), + end(plugins_), + std::inserter>>(output, + begin(output)), + [](const pair>& pluginPair) { + return pluginPair.second; + }); return output; } -std::shared_ptr GameCache::GetPlugin(const std::string& pluginName) const { +std::shared_ptr GameCache::GetPlugin( + const std::string& pluginName) const { auto it = plugins_.find(to_lower(pluginName)); if (it != end(plugins_)) return it->second; @@ -93,7 +97,8 @@ void GameCache::AddPlugin(const Plugin&& plugin) { if (it != end(plugins_)) plugins_.erase(it); - plugins_.emplace(plugin.GetLowercasedName(), std::make_shared(std::move(plugin))); + plugins_.emplace(plugin.GetLowercasedName(), + std::make_shared(std::move(plugin))); } void GameCache::ClearCachedConditions() { diff --git a/src/api/game/game_cache.h b/src/api/game/game_cache.h index ae1ddace..4e49a393 100644 --- a/src/api/game/game_cache.h +++ b/src/api/game/game_cache.h @@ -49,6 +49,7 @@ public: void ClearCachedConditions(); void ClearCachedPlugins(); + private: std::unordered_map conditions_; std::unordered_map> plugins_; @@ -60,8 +61,8 @@ private: namespace std { template<> struct less> { - bool operator() (const std::shared_ptr& lhs, - const std::shared_ptr& rhs) const { + bool operator()(const std::shared_ptr& lhs, + const std::shared_ptr& rhs) const { return lhs->GetLowercasedName() < rhs->GetLowercasedName(); } }; diff --git a/src/api/game/load_order_handler.cpp b/src/api/game/load_order_handler.cpp index 169beef8..35f487ce 100644 --- a/src/api/game/load_order_handler.cpp +++ b/src/api/game/load_order_handler.cpp @@ -27,8 +27,8 @@ #include #include -#include "loot/exception/error_categories.h" #include "api/helpers/logging.h" +#include "loot/exception/error_categories.h" using boost::format; using std::string; @@ -36,9 +36,7 @@ using std::string; namespace loot { LoadOrderHandler::LoadOrderHandler() : gh_(nullptr) {} -LoadOrderHandler::~LoadOrderHandler() { - lo_destroy_handle(gh_); -} +LoadOrderHandler::~LoadOrderHandler() { lo_destroy_handle(gh_); } void LoadOrderHandler::Init(const GameType& gameType, const boost::filesystem::path& gamePath, @@ -47,7 +45,7 @@ void LoadOrderHandler::Init(const GameType& gameType, throw std::invalid_argument("Game path is not initialised."); } - const char * gameLocalDataPath = nullptr; + const char* gameLocalDataPath = nullptr; string tempPathString = gameLocalAppData.string(); if (!tempPathString.empty()) gameLocalDataPath = tempPathString.c_str(); @@ -60,17 +58,23 @@ void LoadOrderHandler::Init(const GameType& gameType, int ret; if (gameType == GameType::tes4) - ret = lo_create_handle(&gh_, LIBLO_GAME_TES4, gamePath.string().c_str(), gameLocalDataPath); + ret = lo_create_handle( + &gh_, LIBLO_GAME_TES4, gamePath.string().c_str(), gameLocalDataPath); else if (gameType == GameType::tes5) - ret = lo_create_handle(&gh_, LIBLO_GAME_TES5, gamePath.string().c_str(), gameLocalDataPath); + ret = lo_create_handle( + &gh_, LIBLO_GAME_TES5, gamePath.string().c_str(), gameLocalDataPath); else if (gameType == GameType::tes5se) - ret = lo_create_handle(&gh_, LIBLO_GAME_TES5SE, gamePath.string().c_str(), gameLocalDataPath); + ret = lo_create_handle( + &gh_, LIBLO_GAME_TES5SE, gamePath.string().c_str(), gameLocalDataPath); else if (gameType == GameType::fo3) - ret = lo_create_handle(&gh_, LIBLO_GAME_FO3, gamePath.string().c_str(), gameLocalDataPath); + ret = lo_create_handle( + &gh_, LIBLO_GAME_FO3, gamePath.string().c_str(), gameLocalDataPath); else if (gameType == GameType::fonv) - ret = lo_create_handle(&gh_, LIBLO_GAME_FNV, gamePath.string().c_str(), gameLocalDataPath); + ret = lo_create_handle( + &gh_, LIBLO_GAME_FNV, gamePath.string().c_str(), gameLocalDataPath); else if (gameType == GameType::fo4) - ret = lo_create_handle(&gh_, LIBLO_GAME_FO4, gamePath.string().c_str(), gameLocalDataPath); + ret = lo_create_handle( + &gh_, LIBLO_GAME_FO4, gamePath.string().c_str(), gameLocalDataPath); else ret = LIBLO_ERROR_INVALID_ARGS; @@ -108,7 +112,7 @@ std::vector LoadOrderHandler::GetLoadOrder() const { logger->debug("Getting load order."); } - char ** pluginArr; + char** pluginArr; size_t pluginArrSize; unsigned int ret = lo_get_load_order(gh_, &pluginArr, &pluginArrSize); @@ -121,16 +125,17 @@ std::vector LoadOrderHandler::GetLoadOrder() const { return loadOrder; } -void LoadOrderHandler::SetLoadOrder(const std::vector& loadOrder) const { +void LoadOrderHandler::SetLoadOrder( + const std::vector& loadOrder) const { auto logger = getLogger(); if (logger) { logger->info("Setting load order."); } size_t pluginArrSize = loadOrder.size(); - char ** pluginArr = new char*[pluginArrSize]; + char** pluginArr = new char*[pluginArrSize]; int i = 0; - for (const auto &plugin : loadOrder) { + for (const auto& plugin : loadOrder) { if (logger) { logger->info("\t\t{}", plugin); } @@ -142,8 +147,7 @@ void LoadOrderHandler::SetLoadOrder(const std::vector& loadOrder) c unsigned int ret = lo_set_load_order(gh_, pluginArr, pluginArrSize); - for (size_t i = 0; i < pluginArrSize; i++) - delete[] pluginArr[i]; + for (size_t i = 0; i < pluginArrSize; i++) delete[] pluginArr[i]; delete[] pluginArr; HandleError("set the load order", ret); @@ -153,19 +157,21 @@ void LoadOrderHandler::SetLoadOrder(const std::vector& loadOrder) c } } -void LoadOrderHandler::HandleError(const std::string& operation, unsigned int returnCode) const { +void LoadOrderHandler::HandleError(const std::string& operation, + unsigned int returnCode) const { if (returnCode == LIBLO_OK || returnCode == LIBLO_WARN_LO_MISMATCH) { return; } - const char * e = nullptr; + const char* e = nullptr; string err; lo_get_error_message(&e); if (e == nullptr) { - err = "libloadorder failed to " + operation + ". Details could not be fetched."; - } - else { - err = (format("libloadorder failed to " + operation + ". Details: %1%") % e).str(); + err = "libloadorder failed to " + operation + + ". Details could not be fetched."; + } else { + err = (format("libloadorder failed to " + operation + ". Details: %1%") % e) + .str(); } auto logger = getLogger(); diff --git a/src/api/game/load_order_handler.h b/src/api/game/load_order_handler.h index bc98bc35..41b5d3b9 100644 --- a/src/api/game/load_order_handler.h +++ b/src/api/game/load_order_handler.h @@ -51,6 +51,7 @@ public: bool IsPluginActive(const std::string& pluginName) const; void SetLoadOrder(const std::vector& loadOrder) const; + private: void HandleError(const std::string& operation, unsigned int returnCode) const; diff --git a/src/api/helpers/crc.cpp b/src/api/helpers/crc.cpp index 1e596e8f..f35e03b4 100644 --- a/src/api/helpers/crc.cpp +++ b/src/api/helpers/crc.cpp @@ -45,7 +45,7 @@ size_t GetStreamSize(std::istream& stream) { return streamSize; } -//Calculate the CRC of the given file for comparison purposes. +// Calculate the CRC of the given file for comparison purposes. uint32_t GetCrc32(const boost::filesystem::path& filename) { try { auto logger = getLogger(); @@ -77,7 +77,10 @@ uint32_t GetCrc32(const boost::filesystem::path& filename) { return checksum; } catch (std::exception& e) { - throw FileAccessError((boost::format("Unable to open \"%1%\" for CRC calculation: %2%") % filename.string() % e.what()).str()); + throw FileAccessError( + (boost::format("Unable to open \"%1%\" for CRC calculation: %2%") % + filename.string() % e.what()) + .str()); } } } diff --git a/src/api/helpers/git_helper.cpp b/src/api/helpers/git_helper.cpp index ae536271..7d273f9e 100644 --- a/src/api/helpers/git_helper.cpp +++ b/src/api/helpers/git_helper.cpp @@ -26,9 +26,9 @@ #include +#include "api/helpers/logging.h" #include "loot/exception/error_categories.h" #include "loot/exception/git_state_error.h" -#include "api/helpers/logging.h" using std::string; @@ -44,24 +44,25 @@ GitHelper::~GitHelper() { if (!path.empty()) { try { FixRepoPermissions(path); - } catch (std::exception&) {} + } catch (std::exception&) { + } } } } GitHelper::GitData::GitData() : - repo(nullptr), - remote(nullptr), - config(nullptr), - object(nullptr), - commit(nullptr), - reference(nullptr), - reference2(nullptr), - blob(nullptr), - annotated_commit(nullptr), - tree(nullptr), - diff(nullptr), - buffer({0}) { + repo(nullptr), + remote(nullptr), + config(nullptr), + object(nullptr), + commit(nullptr), + reference(nullptr), + reference2(nullptr), + blob(nullptr), + annotated_commit(nullptr), + tree(nullptr), + diff(nullptr), + buffer({0}) { // Init threading system and OpenSSL (for Linux builds). git_libgit2_init(); @@ -99,7 +100,7 @@ void GitHelper::Call(int error_code) { if (!error_code) return; - const git_error * last_error = giterr_last(); + const git_error* last_error = giterr_last(); std::string gitError; if (last_error == nullptr) gitError = std::to_string(error_code) + "."; @@ -107,22 +108,31 @@ void GitHelper::Call(int error_code) { gitError = std::to_string(error_code) + "; " + last_error->message; giterr_clear(); - auto message = (boost::format("Git operation failed. Details: %1%") % gitError).str(); + auto message = + (boost::format("Git operation failed. Details: %1%") % gitError).str(); throw std::system_error(error_code, libgit2_category(), message); } bool GitHelper::IsRepository(const boost::filesystem::path& path) { - return git_repository_open_ext(NULL, path.string().c_str(), GIT_REPOSITORY_OPEN_NO_SEARCH, NULL) == 0; + return git_repository_open_ext(NULL, + path.string().c_str(), + GIT_REPOSITORY_OPEN_NO_SEARCH, + NULL) == 0; } -// Removes the read-only flag from some files in git repositories created by libgit2. +// Removes the read-only flag from some files in git repositories created by +// libgit2. void GitHelper::FixRepoPermissions(const boost::filesystem::path& path) { if (logger_) { - logger_->trace("Recursively setting write permission on directory: {}", path.string()); + logger_->trace("Recursively setting write permission on directory: {}", + path.string()); } - for (fs::recursive_directory_iterator it(path); it != fs::recursive_directory_iterator(); ++it) { - if ((it->status().permissions() & (fs::owner_write | fs::group_write | fs::others_write)) == 0) { + for (fs::recursive_directory_iterator it(path); + it != fs::recursive_directory_iterator(); + ++it) { + if ((it->status().permissions() & + (fs::owner_write | fs::group_write | fs::others_write)) == 0) { if (logger_) { logger_->trace("Setting write permission for: {}", it->path().string()); } @@ -131,13 +141,15 @@ void GitHelper::FixRepoPermissions(const boost::filesystem::path& path) { } } -int GitHelper::DiffFileCallback(const git_diff_delta *delta, float progress, void * payload) { +int GitHelper::DiffFileCallback(const git_diff_delta* delta, + float progress, + void* payload) { auto logger = getLogger(); if (logger) { logger->trace("Checking diff for: {}", delta->old_file.path); } - DiffPayload * gdp = (DiffPayload*)payload; + DiffPayload* gdp = (DiffPayload*)payload; if (strcmp(delta->old_file.path, gdp->fileToFind) == 0) { if (logger) { logger->warn("Edited masterlist found."); @@ -149,9 +161,11 @@ int GitHelper::DiffFileCallback(const git_diff_delta *delta, float progress, voi } // Clones a repository and opens it. -void GitHelper::Clone(const boost::filesystem::path& path, const std::string& url) { +void GitHelper::Clone(const boost::filesystem::path& path, + const std::string& url) { if (data_.repo != nullptr) - throw GitStateError("Cannot clone repository that has already been opened."); + throw GitStateError( + "Cannot clone repository that has already been opened."); // Clone the remote repository. if (logger_) { @@ -160,13 +174,13 @@ void GitHelper::Clone(const boost::filesystem::path& path, const std::string& ur fs::path tempPath = path.parent_path() / fs::unique_path(); - //Delete temporary folder in case it already exists. + // Delete temporary folder in case it already exists. fs::remove_all(tempPath); if (!fs::is_empty(path)) { - // Directory is non-empty. Delete the masterlist file and - // .git folder, then move any remaining files to a temporary - // folder while the repo is cloned, before moving them back. + // Directory is non-empty. Delete the masterlist file and + // .git folder, then move any remaining files to a temporary + // folder while the repo is cloned, before moving them back. if (logger_) { logger_->trace("Repo path not empty, renaming folder."); } @@ -184,27 +198,30 @@ void GitHelper::Clone(const boost::filesystem::path& path, const std::string& ur } // Perform the clone. - Call(git_clone(&data_.repo, url.c_str(), path.string().c_str(), &data_.clone_options)); + Call(git_clone( + &data_.repo, url.c_str(), path.string().c_str(), &data_.clone_options)); if (fs::exists(tempPath)) { - //Move contents back in. + // Move contents back in. if (logger_) { logger_->trace("Repo path wasn't empty, moving previous files back in."); } - for (fs::directory_iterator it(tempPath); it != fs::directory_iterator(); ++it) { + for (fs::directory_iterator it(tempPath); it != fs::directory_iterator(); + ++it) { if (!fs::exists(path / it->path().filename())) { - //No conflict, OK to move back in. + // No conflict, OK to move back in. fs::rename(it->path(), path / it->path().filename()); } } - //Delete temporary folder. + // Delete temporary folder. fs::remove_all(tempPath); } } void GitHelper::Fetch(const std::string& remote) { if (data_.repo == nullptr) - throw GitStateError("Cannot fetch updates for repository that has not been opened."); + throw GitStateError( + "Cannot fetch updates for repository that has not been opened."); if (logger_) { logger_->trace("Fetching updates from remote."); @@ -218,49 +235,61 @@ void GitHelper::Fetch(const std::string& remote) { Call(git_remote_fetch(data_.remote, nullptr, &fetch_options, nullptr)); // Log some stats on what was fetched either during update or clone. - const git_transfer_progress * stats = git_remote_stats(data_.remote); + const git_transfer_progress* stats = git_remote_stats(data_.remote); if (logger_) { logger_->trace("Received {} of {} objects in {} bytes.", - stats->indexed_objects, stats->total_objects, stats->received_bytes); + stats->indexed_objects, + stats->total_objects, + stats->received_bytes); } git_remote_free(data_.remote); data_.remote = nullptr; } -void GitHelper::CheckoutNewBranch(const std::string& remote, const std::string& branch) { +void GitHelper::CheckoutNewBranch(const std::string& remote, + const std::string& branch) { if (data_.repo == nullptr) - throw GitStateError("Cannot fetch updates for repository that has not been opened."); + throw GitStateError( + "Cannot fetch updates for repository that has not been opened."); else if (data_.commit != nullptr) - throw GitStateError("Cannot fetch repository updates, commit memory already allocated."); + throw GitStateError( + "Cannot fetch repository updates, commit memory already allocated."); else if (data_.object != nullptr) - throw GitStateError("Cannot fetch repository updates, object memory already allocated."); + throw GitStateError( + "Cannot fetch repository updates, object memory already allocated."); else if (data_.reference != nullptr) - throw GitStateError("Cannot fetch repository updates, reference memory already allocated."); + throw GitStateError( + "Cannot fetch repository updates, reference memory already allocated."); if (logger_) { - logger_->trace("Looking up commit referred to by the remote branch \"{}\".", branch); + logger_->trace("Looking up commit referred to by the remote branch \"{}\".", + branch); } - Call(git_revparse_single(&data_.object, data_.repo, (remote + "/" + branch).c_str())); - const git_oid * commit_id = git_object_id(data_.object); + Call(git_revparse_single( + &data_.object, data_.repo, (remote + "/" + branch).c_str())); + const git_oid* commit_id = git_object_id(data_.object); if (logger_) { logger_->trace("Creating the new branch."); } Call(git_commit_lookup(&data_.commit, data_.repo, commit_id)); - Call(git_branch_create(&data_.reference, data_.repo, branch.c_str(), data_.commit, 1)); + Call(git_branch_create( + &data_.reference, data_.repo, branch.c_str(), data_.commit, 1)); if (logger_) { logger_->trace("Setting the upstream for the new branch."); } - Call(git_branch_set_upstream(data_.reference, (remote + "/" + branch).c_str())); + Call(git_branch_set_upstream(data_.reference, + (remote + "/" + branch).c_str())); // Check if HEAD points to the desired branch and set it to if not. if (!git_branch_is_head(data_.reference)) { if (logger_) { logger_->trace("Setting HEAD to follow branch: {}", branch); } - Call(git_repository_set_head(data_.repo, (string("refs/heads/") + branch).c_str())); + Call(git_repository_set_head(data_.repo, + (string("refs/heads/") + branch).c_str())); } if (logger_) { @@ -279,15 +308,18 @@ void GitHelper::CheckoutNewBranch(const std::string& remote, const std::string& void GitHelper::CheckoutRevision(const std::string& revision) { if (data_.repo == nullptr) - throw GitStateError("Cannot checkout revision for repository that has not been opened."); + throw GitStateError( + "Cannot checkout revision for repository that has not been opened."); else if (data_.object != nullptr) - throw GitStateError("Cannot fetch repository updates, object memory already allocated."); + throw GitStateError( + "Cannot fetch repository updates, object memory already allocated."); -// Get an object ID for 'HEAD^'. + // Get an object ID for 'HEAD^'. Call(git_revparse_single(&data_.object, data_.repo, revision.c_str())); - const git_oid * oid = git_object_id(data_.object); + const git_oid* oid = git_object_id(data_.object); - // Detach HEAD to HEAD~1. This will roll back HEAD by one commit each time it is called. + // Detach HEAD to HEAD~1. This will roll back HEAD by one commit each time it + // is called. Call(git_repository_set_head_detached(data_.repo, oid)); // Checkout the new HEAD. @@ -302,13 +334,17 @@ void GitHelper::CheckoutRevision(const std::string& revision) { std::string GitHelper::GetHeadShortId() { if (data_.repo == nullptr) - throw GitStateError("Cannot checkout revision for repository that has not been opened."); + throw GitStateError( + "Cannot checkout revision for repository that has not been opened."); else if (data_.object != nullptr) - throw GitStateError("Cannot fetch repository updates, object memory already allocated."); + throw GitStateError( + "Cannot fetch repository updates, object memory already allocated."); else if (data_.reference != nullptr) - throw GitStateError("Cannot fetch repository updates, reference memory already allocated."); + throw GitStateError( + "Cannot fetch repository updates, reference memory already allocated."); else if (data_.buffer.ptr != nullptr) - throw GitStateError("Cannot fetch repository updates, buffer memory already allocated."); + throw GitStateError( + "Cannot fetch repository updates, buffer memory already allocated."); if (logger_) { logger_->trace("Getting the Git object for HEAD."); @@ -332,18 +368,18 @@ std::string GitHelper::GetHeadShortId() { return revision; } -GitHelper::GitData& GitHelper::GetData() { - return data_; -} +GitHelper::GitData& GitHelper::GetData() { return data_; } -bool GitHelper::IsFileDifferent(const boost::filesystem::path& repoRoot, const std::string& filename) { +bool GitHelper::IsFileDifferent(const boost::filesystem::path& repoRoot, + const std::string& filename) { auto logger = getLogger(); if (!IsRepository(repoRoot)) { if (logger) { logger->info("Unknown masterlist revision: Git repository missing."); } - throw GitStateError("Cannot check if the \"" + filename + "\" working copy is edited, Git repository missing."); + throw GitStateError("Cannot check if the \"" + filename + + "\" working copy is edited, Git repository missing."); } if (logger) { @@ -352,17 +388,21 @@ bool GitHelper::IsFileDifferent(const boost::filesystem::path& repoRoot, const s GitHelper git; git.Call(git_repository_open(&git.data_.repo, repoRoot.string().c_str())); - // Perform a git diff, then iterate the deltas to see if one exists for the masterlist. + // Perform a git diff, then iterate the deltas to see if one exists for the + // masterlist. if (logger) { logger->trace("Getting the tree for the HEAD revision."); } - git.Call(git_revparse_single(&git.data_.object, git.data_.repo, "HEAD^{tree}")); - git.Call(git_tree_lookup(&git.data_.tree, git.data_.repo, git_object_id(git.data_.object))); + git.Call( + git_revparse_single(&git.data_.object, git.data_.repo, "HEAD^{tree}")); + git.Call(git_tree_lookup( + &git.data_.tree, git.data_.repo, git_object_id(git.data_.object))); if (logger) { logger->trace("Performing git diff."); } - git.Call(git_diff_tree_to_workdir_with_index(&git.data_.diff, git.data_.repo, git.data_.tree, NULL)); + git.Call(git_diff_tree_to_workdir_with_index( + &git.data_.diff, git.data_.repo, git.data_.tree, NULL)); if (logger) { logger->trace("Iterating over git diff deltas."); @@ -370,7 +410,8 @@ bool GitHelper::IsFileDifferent(const boost::filesystem::path& repoRoot, const s GitHelper::DiffPayload payload; payload.fileFound = false; payload.fileToFind = filename.c_str(); - git.Call(git_diff_foreach(git.data_.diff, &git.DiffFileCallback, NULL, NULL, NULL, &payload)); + git.Call(git_diff_foreach( + git.data_.diff, &git.DiffFileCallback, NULL, NULL, NULL, &payload)); return payload.fileFound; } diff --git a/src/api/helpers/git_helper.h b/src/api/helpers/git_helper.h index f66edcf4..ff671e45 100644 --- a/src/api/helpers/git_helper.h +++ b/src/api/helpers/git_helper.h @@ -27,33 +27,33 @@ #include -#include #include #include +#include namespace loot { class GitHelper { public: struct DiffPayload { bool fileFound; - const char * fileToFind; + const char* fileToFind; }; struct GitData { GitData(); ~GitData(); - git_repository * repo; - git_remote * remote; - git_config * config; - git_object * object; - git_commit * commit; - git_reference * reference; - git_reference * reference2; - git_blob * blob; - git_annotated_commit * annotated_commit; - git_tree * tree; - git_diff * diff; + git_repository* repo; + git_remote* remote; + git_config* config; + git_object* object; + git_commit* commit; + git_reference* reference; + git_reference* reference2; + git_blob* blob; + git_annotated_commit* annotated_commit; + git_tree* tree; + git_diff* diff; git_buf buffer; git_checkout_options checkout_options; @@ -66,8 +66,11 @@ public: void Call(int error_code); static bool IsRepository(const boost::filesystem::path& path); - static bool IsFileDifferent(const boost::filesystem::path& repoRoot, const std::string& filename); - static int DiffFileCallback(const git_diff_delta *delta, float progress, void * payload); + static bool IsFileDifferent(const boost::filesystem::path& repoRoot, + const std::string& filename); + static int DiffFileCallback(const git_diff_delta* delta, + float progress, + void* payload); void Clone(const boost::filesystem::path& path, const std::string& url); void Fetch(const std::string& remote); @@ -79,8 +82,8 @@ public: GitData& GetData(); private: - // Removes the read-only flag from some files in git repositories - // created by libgit2. + // Removes the read-only flag from some files in git repositories + // created by libgit2. void FixRepoPermissions(const boost::filesystem::path& path); GitData data_; diff --git a/src/api/helpers/logging.h b/src/api/helpers/logging.h index 07a444bd..4595da1c 100644 --- a/src/api/helpers/logging.h +++ b/src/api/helpers/logging.h @@ -29,7 +29,7 @@ #include "loot/enum/log_level.h" namespace loot { -static const char * LOGGER_NAME = "loot_api_logger"; +static const char* LOGGER_NAME = "loot_api_logger"; inline std::shared_ptr getLogger() { return spdlog::get(LOGGER_NAME); diff --git a/src/api/helpers/version.cpp b/src/api/helpers/version.cpp index cfa899ea..f324ecab 100644 --- a/src/api/helpers/version.cpp +++ b/src/api/helpers/version.cpp @@ -25,52 +25,54 @@ #include -#include #include +#include #include "api/helpers/windows_encoding_converters.h" #ifdef _WIN32 -# ifndef UNICODE -# define UNICODE -# endif -# ifndef _UNICODE -# define _UNICODE -# endif -# include "windows.h" +#ifndef UNICODE +#define UNICODE +#endif +#ifndef _UNICODE +#define _UNICODE +#endif +#include "windows.h" #endif using std::regex; namespace loot { - /* The string below matches timestamps that use forwardslashes for date - separators. However, Pseudosem v1.0.1 will only compare the first - two digits as it does not recognise forwardslashes as separators. */ -const std::string dateRegex = R"((\d{1,2}/\d{1,2}/\d{1,4} \d{1,2}:\d{1,2}:\d{1,2}))"; +/* The string below matches timestamps that use forwardslashes for date + separators. However, Pseudosem v1.0.1 will only compare the first + two digits as it does not recognise forwardslashes as separators. */ +const std::string dateRegex = + R"((\d{1,2}/\d{1,2}/\d{1,4} \d{1,2}:\d{1,2}:\d{1,2}))"; /* The string below matches the range of version strings supported by Pseudosem v1.0.1, excluding space separators, as they make version extraction from inside sentences very tricky and have not been seen "in the wild". */ const std::string pseudosemVersionRegex = -R"((\d+(?:\.\d+)+(?:[-._:]?[A-Za-z0-9]+)*))" -// The string below prevents version numbers followed by a comma from -// matching. -R"((?!,))"; + R"((\d+(?:\.\d+)+(?:[-._:]?[A-Za-z0-9]+)*))" + // The string below prevents version numbers followed by a comma from + // matching. + R"((?!,))"; /* There are a few different version formats that can appear in strings together, and in order to extract the correct one, they must be searched for in order of priority. */ const std::vector Version::versionRegexes({ regex(dateRegex, regex::ECMAScript | regex::icase), - regex(R"(version:?\s)" + - pseudosemVersionRegex, regex::ECMAScript | regex::icase), - regex(R"((?:^|v|\s))" + - pseudosemVersionRegex, regex::ECMAScript | regex::icase), + regex(R"(version:?\s)" + pseudosemVersionRegex, + regex::ECMAScript | regex::icase), + regex(R"((?:^|v|\s))" + pseudosemVersionRegex, + regex::ECMAScript | regex::icase), regex( - /* The string below matches a number containing one or more digits - found at the start of the search string or preceded by 'v'. */ - R"((?:^|v)(\d+))", regex::ECMAScript | regex::icase), + /* The string below matches a number containing one or more digits + found at the start of the search string or preceded by 'v'. */ + R"((?:^|v)(\d+))", + regex::ECMAScript | regex::icase), }); Version::Version() {} @@ -83,7 +85,7 @@ Version::Version(const std::string& ver) { if (it->str().empty()) continue; - //Use the first non-empty sub-match. + // Use the first non-empty sub-match. verString_ = *it; boost::trim(verString_); return; @@ -100,11 +102,11 @@ Version::Version(const boost::filesystem::path& file) { if (size > 0) { LPBYTE point = new BYTE[size]; UINT uLen; - VS_FIXEDFILEINFO *info; + VS_FIXEDFILEINFO* info; GetFileVersionInfo(ToWinWide(file.string()).c_str(), 0, size, point); - VerQueryValue(point, L"\\", (LPVOID *)&info, &uLen); + VerQueryValue(point, L"\\", (LPVOID*)&info, &uLen); DWORD dwLeftMost = HIWORD(info->dwFileVersionMS); DWORD dwSecondLeft = LOWORD(info->dwFileVersionMS); @@ -113,16 +115,22 @@ Version::Version(const boost::filesystem::path& file) { delete[] point; - verString_ = std::to_string(dwLeftMost) + '.' + std::to_string(dwSecondLeft) + '.' + std::to_string(dwSecondRight) + '.' + std::to_string(dwRightMost); + verString_ = + std::to_string(dwLeftMost) + '.' + std::to_string(dwSecondLeft) + '.' + + std::to_string(dwSecondRight) + '.' + std::to_string(dwRightMost); } #else - // ensure filename has no quote characters in it to avoid command injection attacks + // ensure filename has no quote characters in it to avoid command injection + // attacks if (std::string::npos != file.string().find('"')) { - // command mostly borrowed from the gnome-exe-thumbnailer.sh script - // wrestool is part of the icoutils package - std::string cmd = "wrestool --extract --raw --type=version \"" + file.string() + "\" | tr '\\0, ' '\\t.\\0' | sed 's/\\t\\t/_/g' | tr -c -d '[:print:]' | sed -r 's/.*Version[^0-9]*([0-9]+(\\.[0-9]+)+).*/\\1/'"; + // command mostly borrowed from the gnome-exe-thumbnailer.sh script + // wrestool is part of the icoutils package + std::string cmd = + "wrestool --extract --raw --type=version \"" + file.string() + + "\" | tr '\\0, ' '\\t.\\0' | sed 's/\\t\\t/_/g' | tr -c -d '[:print:]' " + "| sed -r 's/.*Version[^0-9]*([0-9]+(\\.[0-9]+)+).*/\\1/'"; - FILE *fp = popen(cmd.c_str(), "r"); + FILE* fp = popen(cmd.c_str(), "r"); // read out the version string static const uint32_t BUFSIZE = 32; @@ -135,31 +143,29 @@ Version::Version(const boost::filesystem::path& file) { #endif } -std::string Version::AsString() const { - return verString_; -} +std::string Version::AsString() const { return verString_; } -bool Version::operator < (const Version& ver) const { +bool Version::operator<(const Version& ver) const { return pseudosem::compare(this->verString_, ver.AsString()) < 0; } -bool Version::operator > (const Version& ver) const { +bool Version::operator>(const Version& ver) const { return pseudosem::compare(this->verString_, ver.AsString()) > 0; } -bool Version::operator >= (const Version& ver) const { +bool Version::operator>=(const Version& ver) const { return pseudosem::compare(this->verString_, ver.AsString()) >= 0; } -bool Version::operator <= (const Version& ver) const { +bool Version::operator<=(const Version& ver) const { return pseudosem::compare(this->verString_, ver.AsString()) <= 0; } -bool Version::operator == (const Version& ver) const { +bool Version::operator==(const Version& ver) const { return pseudosem::compare(this->verString_, ver.AsString()) == 0; } -bool Version::operator != (const Version& ver) const { +bool Version::operator!=(const Version& ver) const { return pseudosem::compare(this->verString_, ver.AsString()) != 0; } } diff --git a/src/api/helpers/version.h b/src/api/helpers/version.h index ba39c913..59832c3f 100644 --- a/src/api/helpers/version.h +++ b/src/api/helpers/version.h @@ -31,7 +31,7 @@ #include namespace loot { - //Version class for more robust version comparisons. +// Version class for more robust version comparisons. class Version { public: Version(); @@ -40,12 +40,13 @@ public: std::string AsString() const; - bool operator > (const Version&) const; - bool operator < (const Version&) const; - bool operator >= (const Version&) const; - bool operator <= (const Version&) const; - bool operator == (const Version&) const; - bool operator != (const Version&) const; + bool operator>(const Version&) const; + bool operator<(const Version&) const; + bool operator>=(const Version&) const; + bool operator<=(const Version&) const; + bool operator==(const Version&) const; + bool operator!=(const Version&) const; + private: std::string verString_; static const std::vector versionRegexes; diff --git a/src/api/helpers/windows_encoding_converters.h b/src/api/helpers/windows_encoding_converters.h index f14256fa..e25b059d 100644 --- a/src/api/helpers/windows_encoding_converters.h +++ b/src/api/helpers/windows_encoding_converters.h @@ -29,15 +29,15 @@ #include -# ifndef UNICODE -# define UNICODE -# endif -# ifndef _UNICODE -# define _UNICODE -# endif -# include "windows.h" -# include "shlobj.h" -# include "shlwapi.h" +#ifndef UNICODE +#define UNICODE +#endif +#ifndef _UNICODE +#define _UNICODE +#endif +#include "shlobj.h" +#include "shlwapi.h" +#include "windows.h" namespace loot { /** @@ -66,9 +66,11 @@ inline std::wstring ToWinWide(const std::string& str) { * @return A string encoded in UTF-8. */ inline std::string FromWinWide(const std::wstring& wstr) { - size_t len = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), wstr.length(), NULL, 0, NULL, NULL); + size_t len = WideCharToMultiByte( + CP_UTF8, 0, wstr.c_str(), wstr.length(), NULL, 0, NULL, NULL); std::string str(len, 0); - WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), wstr.length(), &str[0], len, NULL, NULL); + WideCharToMultiByte( + CP_UTF8, 0, wstr.c_str(), wstr.length(), &str[0], len, NULL, NULL); return str; } } diff --git a/src/api/masterlist.cpp b/src/api/masterlist.cpp index f57f262e..9cff2870 100644 --- a/src/api/masterlist.cpp +++ b/src/api/masterlist.cpp @@ -29,11 +29,11 @@ #include -#include "loot/exception/file_access_error.h" -#include "loot/exception/git_state_error.h" #include "api/game/game.h" #include "api/helpers/git_helper.h" #include "api/helpers/logging.h" +#include "loot/exception/file_access_error.h" +#include "loot/exception/git_state_error.h" using boost::format; using std::string; @@ -41,7 +41,8 @@ using std::string; namespace fs = boost::filesystem; namespace loot { -MasterlistInfo Masterlist::GetInfo(const boost::filesystem::path& path, bool shortID) { +MasterlistInfo Masterlist::GetInfo(const boost::filesystem::path& path, + bool shortID) { // Compare HEAD and working copy, and get revision info. GitHelper git; MasterlistInfo info; @@ -52,24 +53,29 @@ MasterlistInfo Masterlist::GetInfo(const boost::filesystem::path& path, bool sho if (logger) { logger->info("Unknown masterlist revision: No masterlist present."); } - throw FileAccessError(string("N/A: No masterlist present at ") + path.string()); + throw FileAccessError(string("N/A: No masterlist present at ") + + path.string()); } else if (!git.IsRepository(path.parent_path())) { if (logger) { logger->info("Unknown masterlist revision: Git repository missing."); } - throw GitStateError(string("Unknown: \"") + path.parent_path().string() + "\" is not a Git repository."); + throw GitStateError(string("Unknown: \"") + path.parent_path().string() + + "\" is not a Git repository."); } if (logger) { logger->debug("Existing repository found, attempting to open it."); } - git.Call(git_repository_open(&git.GetData().repo, path.parent_path().string().c_str())); + git.Call(git_repository_open(&git.GetData().repo, + path.parent_path().string().c_str())); - //Need to get the HEAD object, because the individual file has a different SHA. + // Need to get the HEAD object, because the individual file has a different + // SHA. if (logger) { logger->info("Getting the Git object for the tree at HEAD."); } - git.Call(git_revparse_single(&git.GetData().object, git.GetData().repo, "HEAD")); + git.Call( + git_revparse_single(&git.GetData().object, git.GetData().repo, "HEAD")); if (logger) { logger->trace("Generating hex string for Git object ID."); @@ -79,13 +85,14 @@ MasterlistInfo Masterlist::GetInfo(const boost::filesystem::path& path, bool sho info.revision_id = git.GetData().buffer.ptr; } else { char c_rev[GIT_OID_HEXSZ + 1]; - info.revision_id = git_oid_tostr(c_rev, GIT_OID_HEXSZ + 1, git_object_id(git.GetData().object)); + info.revision_id = git_oid_tostr( + c_rev, GIT_OID_HEXSZ + 1, git_object_id(git.GetData().object)); } if (logger) { logger->trace("Getting date for Git object."); } - const git_oid * oid = git_object_id(git.GetData().object); + const git_oid* oid = git_object_id(git.GetData().object); git.Call(git_commit_lookup(&git.GetData().commit, git.GetData().repo, oid)); git_time_t time = git_commit_time(git.GetData().commit); @@ -96,7 +103,8 @@ MasterlistInfo Masterlist::GetInfo(const boost::filesystem::path& path, bool sho if (logger) { logger->trace("Diffing masterlist HEAD and working copy."); } - info.is_modified = GitHelper::IsFileDifferent(path.parent_path(), path.filename().string()); + info.is_modified = + GitHelper::IsFileDifferent(path.parent_path(), path.filename().string()); return info; } @@ -111,21 +119,27 @@ bool Masterlist::IsLatest(const boost::filesystem::path& path, if (!git.IsRepository(path.parent_path())) { if (logger) { - logger->info("Cannot get latest masterlist revision: Git repository missing."); + logger->info( + "Cannot get latest masterlist revision: Git repository missing."); } - throw GitStateError(string("Unknown: \"") + path.parent_path().string() + "\" is not a Git repository."); + throw GitStateError(string("Unknown: \"") + path.parent_path().string() + + "\" is not a Git repository."); } if (logger) { logger->info("Attempting to open repository."); } - git.Call(git_repository_open(&git.GetData().repo, path.parent_path().string().c_str())); + git.Call(git_repository_open(&git.GetData().repo, + path.parent_path().string().c_str())); git.Fetch("origin"); // Get the remote branch's commit ID. git_oid branchOid; - git.Call(git_reference_name_to_id(&branchOid, git.GetData().repo, (string("refs/remotes/origin/") + repoBranch).c_str())); + git.Call(git_reference_name_to_id( + &branchOid, + git.GetData().repo, + (string("refs/remotes/origin/") + repoBranch).c_str())); // Get HEAD's commit ID. git_oid headOid; @@ -134,7 +148,9 @@ bool Masterlist::IsLatest(const boost::filesystem::path& path, return memcmp(branchOid.id, headOid.id, 20) == 0; } -bool Masterlist::Update(const boost::filesystem::path& path, const std::string& repoUrl, const std::string& repoBranch) { +bool Masterlist::Update(const boost::filesystem::path& path, + const std::string& repoUrl, + const std::string& repoBranch) { GitHelper git; auto logger = getLogger(); fs::path repoPath = path.parent_path(); @@ -147,9 +163,10 @@ bool Masterlist::Update(const boost::filesystem::path& path, const std::string& if (logger) { logger->debug("Setting up checkout options."); } - char * paths = new char[filename.length() + 1]; + char* paths = new char[filename.length() + 1]; strcpy(paths, filename.c_str()); - git.GetData().checkout_options.checkout_strategy = GIT_CHECKOUT_FORCE | GIT_CHECKOUT_DONT_REMOVE_EXISTING; + git.GetData().checkout_options.checkout_strategy = + GIT_CHECKOUT_FORCE | GIT_CHECKOUT_DONT_REMOVE_EXISTING; git.GetData().checkout_options.paths.strings = &paths; git.GetData().checkout_options.paths.count = 1; @@ -160,7 +177,8 @@ bool Masterlist::Update(const boost::filesystem::path& path, const std::string& // Now try to access the repository if it exists, or clone one if it doesn't. if (logger) { - logger->trace("Attempting to open the Git repository at: {}", repoPath.string()); + logger->trace("Attempting to open the Git repository at: {}", + repoPath.string()); } if (!git.IsRepository(repoPath)) git.Clone(repoPath, repoUrl); @@ -171,7 +189,8 @@ bool Masterlist::Update(const boost::filesystem::path& path, const std::string& if (logger) { logger->info("Existing repository found, attempting to open it."); } - git.Call(git_repository_open(&git.GetData().repo, repoPath.string().c_str())); + git.Call( + git_repository_open(&git.GetData().repo, repoPath.string().c_str())); // Set the remote URL. if (logger) { @@ -183,13 +202,17 @@ bool Masterlist::Update(const boost::filesystem::path& path, const std::string& git.Fetch("origin"); // Check that a local branch with the correct name exists. - int ret = git_branch_lookup(&git.GetData().reference, git.GetData().repo, repoBranch.c_str(), GIT_BRANCH_LOCAL); + int ret = git_branch_lookup(&git.GetData().reference, + git.GetData().repo, + repoBranch.c_str(), + GIT_BRANCH_LOCAL); if (ret == GIT_ENOTFOUND) - // Branch doesn't exist. Create a new branch using the remote branch's latest commit. + // Branch doesn't exist. Create a new branch using the remote branch's + // latest commit. git.CheckoutNewBranch("origin", repoBranch); else { - // The local branch exists. Need to merge the remote branch - // into it. + // The local branch exists. Need to merge the remote branch + // into it. git.Call(ret); // Handle other errors from preceding branch lookup. // Check if HEAD points to the desired branch and set it to if not. @@ -197,24 +220,36 @@ bool Masterlist::Update(const boost::filesystem::path& path, const std::string& if (logger) { logger->trace("Setting HEAD to follow branch: {}", repoBranch); } - git.Call(git_repository_set_head(git.GetData().repo, (string("refs/heads/") + repoBranch).c_str())); + git.Call(git_repository_set_head( + git.GetData().repo, (string("refs/heads/") + repoBranch).c_str())); } // Get remote branch reference. - git.Call(git_branch_upstream(&git.GetData().reference2, git.GetData().reference)); + git.Call(git_branch_upstream(&git.GetData().reference2, + git.GetData().reference)); if (logger) { logger->trace("Checking HEAD and remote branch's mergeability."); } git_merge_analysis_t analysis; git_merge_preference_t pref; - git.Call(git_annotated_commit_from_ref(&git.GetData().annotated_commit, git.GetData().repo, git.GetData().reference2)); - git.Call(git_merge_analysis(&analysis, &pref, git.GetData().repo, (const git_annotated_commit **)&git.GetData().annotated_commit, 1)); + git.Call(git_annotated_commit_from_ref(&git.GetData().annotated_commit, + git.GetData().repo, + git.GetData().reference2)); + git.Call(git_merge_analysis( + &analysis, + &pref, + git.GetData().repo, + (const git_annotated_commit**)&git.GetData().annotated_commit, + 1)); - if ((analysis & GIT_MERGE_ANALYSIS_FASTFORWARD) == 0 && (analysis & GIT_MERGE_ANALYSIS_UP_TO_DATE) == 0) { - // The local branch can't be easily merged. Best just to delete and recreate it. + if ((analysis & GIT_MERGE_ANALYSIS_FASTFORWARD) == 0 && + (analysis & GIT_MERGE_ANALYSIS_UP_TO_DATE) == 0) { + // The local branch can't be easily merged. Best just to delete and + // recreate it. if (logger) { - logger->trace("Local branch cannot be easily merged with remote branch."); + logger->trace( + "Local branch cannot be easily merged with remote branch."); } if (logger) { @@ -230,9 +265,10 @@ bool Masterlist::Update(const boost::filesystem::path& path, const std::string& git.CheckoutNewBranch("origin", repoBranch); } else { - // Get remote branch commit ID. - git.Call(git_reference_peel(&git.GetData().object, git.GetData().reference2, GIT_OBJ_COMMIT)); - const git_oid * remote_commit_id = git_object_id(git.GetData().object); + // Get remote branch commit ID. + git.Call(git_reference_peel( + &git.GetData().object, git.GetData().reference2, GIT_OBJ_COMMIT)); + const git_oid* remote_commit_id = git_object_id(git.GetData().object); git_object_free(git.GetData().object); git.GetData().object = nullptr; @@ -241,16 +277,19 @@ bool Masterlist::Update(const boost::filesystem::path& path, const std::string& bool updateBranchHead = true; if ((analysis & GIT_MERGE_ANALYSIS_UP_TO_DATE) != 0) { - // No merge is required, but HEAD might be ahead of the remote branch. Check - // to see if that's the case, and move HEAD back to match the remote branch - // if so. + // No merge is required, but HEAD might be ahead of the remote branch. + // Check to see if that's the case, and move HEAD back to match the + // remote branch if so. if (logger) { - logger->trace("Local branch is up-to-date with remote branch. Checking to see if local and remote branch heads are equal."); + logger->trace( + "Local branch is up-to-date with remote branch. Checking to " + "see if local and remote branch heads are equal."); } // Get local branch commit ID. - git.Call(git_reference_peel(&git.GetData().object, git.GetData().reference, GIT_OBJ_COMMIT)); - const git_oid * local_commit_id = git_object_id(git.GetData().object); + git.Call(git_reference_peel( + &git.GetData().object, git.GetData().reference, GIT_OBJ_COMMIT)); + const git_oid* local_commit_id = git_object_id(git.GetData().object); git_object_free(git.GetData().object); git.GetData().object = nullptr; @@ -267,7 +306,8 @@ bool Masterlist::Update(const boost::filesystem::path& path, const std::string& } if (!GitHelper::IsFileDifferent(repoPath, filename)) { if (logger) { - logger->info("Local branch and masterlist file are already up to date."); + logger->info( + "Local branch and masterlist file are already up to date."); } return false; } @@ -279,13 +319,16 @@ bool Masterlist::Update(const boost::filesystem::path& path, const std::string& } if (updateBranchHead) { - // The remote branch reference points to a particular - // commit. Update the local branch reference to point - // to the same commit. + // The remote branch reference points to a particular + // commit. Update the local branch reference to point + // to the same commit. if (logger) { logger->trace("Syncing local branch head with remote branch head."); } - git.Call(git_reference_set_target(&git.GetData().reference2, git.GetData().reference, remote_commit_id, "Setting branch reference.")); + git.Call(git_reference_set_target(&git.GetData().reference2, + git.GetData().reference, + remote_commit_id, + "Setting branch reference.")); git_reference_free(git.GetData().reference2); git.GetData().reference2 = nullptr; @@ -297,21 +340,22 @@ bool Masterlist::Update(const boost::filesystem::path& path, const std::string& if (logger) { logger->trace("Performing a Git checkout of HEAD."); } - git.Call(git_checkout_head(git.GetData().repo, &git.GetData().checkout_options)); + git.Call(git_checkout_head(git.GetData().repo, + &git.GetData().checkout_options)); } } } - // Now whether the repository was cloned or updated, the working directory contains - // the latest masterlist. Try parsing it: on failure, detach the HEAD back one commit - // and try again. + // Now whether the repository was cloned or updated, the working directory + // contains the latest masterlist. Try parsing it: on failure, detach the HEAD + // back one commit and try again. bool parsingFailed = false; do { // Get the HEAD revision's short ID. string revision = git.GetHeadShortId(); - //Now try parsing the masterlist. + // Now try parsing the masterlist. if (logger) { logger->debug("Testing masterlist parsing."); } @@ -322,9 +366,11 @@ bool Masterlist::Update(const boost::filesystem::path& path, const std::string& } catch (std::exception& e) { parsingFailed = true; - //There was an error, roll back one revision. + // There was an error, roll back one revision. if (logger) { - logger->error("Masterlist parsing failed. Masterlist revision {}: {}", revision, e.what()); + logger->error("Masterlist parsing failed. Masterlist revision {}: {}", + revision, + e.what()); } git.CheckoutRevision("HEAD^"); } diff --git a/src/api/masterlist.h b/src/api/masterlist.h index 8b2d1a0b..3bd79d5e 100644 --- a/src/api/masterlist.h +++ b/src/api/masterlist.h @@ -39,7 +39,8 @@ public: const std::string& repoURL, const std::string& repoBranch); - static MasterlistInfo GetInfo(const boost::filesystem::path& path, bool shortID); + static MasterlistInfo GetInfo(const boost::filesystem::path& path, + bool shortID); static bool IsLatest(const boost::filesystem::path& path, const std::string& repoBranch); diff --git a/src/api/metadata/condition_evaluator.cpp b/src/api/metadata/condition_evaluator.cpp index 60b33163..32b582af 100644 --- a/src/api/metadata/condition_evaluator.cpp +++ b/src/api/metadata/condition_evaluator.cpp @@ -35,15 +35,19 @@ using boost::format; namespace loot { -ConditionEvaluator::ConditionEvaluator() : gameType_(GameType::tes4), gameCache_(nullptr), loadOrderHandler_(nullptr) {} -ConditionEvaluator::ConditionEvaluator(const GameType gameType, - const boost::filesystem::path& dataPath, - std::shared_ptr gameCache, - std::shared_ptr loadOrderHandler) : - gameType_(gameType), - dataPath_(dataPath), - gameCache_(gameCache), - loadOrderHandler_(loadOrderHandler) {} +ConditionEvaluator::ConditionEvaluator() : + gameType_(GameType::tes4), + gameCache_(nullptr), + loadOrderHandler_(nullptr) {} +ConditionEvaluator::ConditionEvaluator( + const GameType gameType, + const boost::filesystem::path& dataPath, + std::shared_ptr gameCache, + std::shared_ptr loadOrderHandler) : + gameType_(gameType), + dataPath_(dataPath), + gameCache_(gameCache), + loadOrderHandler_(loadOrderHandler) {} bool ConditionEvaluator::evaluate(const std::string& condition) const { if (shouldParseOnly()) { @@ -71,7 +75,8 @@ bool ConditionEvaluator::evaluate(const std::string& condition) const { return result; } -bool ConditionEvaluator::evaluate(const PluginCleaningData& cleaningData, const std::string& pluginName) const { +bool ConditionEvaluator::evaluate(const PluginCleaningData& cleaningData, + const std::string& pluginName) const { if (shouldParseOnly() || pluginName.empty()) return false; @@ -81,7 +86,8 @@ bool ConditionEvaluator::evaluate(const PluginCleaningData& cleaningData, const // Get the CRC from the game plugin cache if possible. try { crc = gameCache_->GetPlugin(pluginName)->GetCRC(); - } catch (...) {} + } catch (...) { + } // Otherwise calculate it from the file. if (crc == 0) { @@ -95,7 +101,8 @@ bool ConditionEvaluator::evaluate(const PluginCleaningData& cleaningData, const return cleaningData.GetCRC() == crc; } -PluginMetadata ConditionEvaluator::evaluateAll(const PluginMetadata& pluginMetadata) const { +PluginMetadata ConditionEvaluator::evaluateAll( + const PluginMetadata& pluginMetadata) const { if (shouldParseOnly()) return pluginMetadata; @@ -178,14 +185,15 @@ bool ConditionEvaluator::fileExists(const std::string& filePath) const { } catch (...) { // Not a loaded plugin, check the filesystem. if (hasPluginFileExtension(filePath, gameType_)) - return boost::filesystem::exists(dataPath_ / filePath) - || boost::filesystem::exists(dataPath_ / (filePath + ".ghost")); + return boost::filesystem::exists(dataPath_ / filePath) || + boost::filesystem::exists(dataPath_ / (filePath + ".ghost")); else return boost::filesystem::exists(dataPath_ / filePath); } } -bool ConditionEvaluator::regexMatchExists(const std::string& regexString) const { +bool ConditionEvaluator::regexMatchExists( + const std::string& regexString) const { auto pathRegex = splitRegex(regexString); if (shouldParseOnly()) @@ -195,14 +203,15 @@ bool ConditionEvaluator::regexMatchExists(const std::string& regexString) const [](const std::string&) { return true; }); } -bool ConditionEvaluator::regexMatchesExist(const std::string& regexString) const { +bool ConditionEvaluator::regexMatchesExist( + const std::string& regexString) const { auto pathRegex = splitRegex(regexString); if (shouldParseOnly()) return false; - return areRegexMatchesInDataDirectory(pathRegex, - [](const std::string&) { return true; }); + return areRegexMatchesInDataDirectory( + pathRegex, [](const std::string&) { return true; }); } bool ConditionEvaluator::isPluginActive(const std::string& pluginName) const { @@ -217,31 +226,34 @@ bool ConditionEvaluator::isPluginActive(const std::string& pluginName) const { return loadOrderHandler_->IsPluginActive(pluginName); } -bool ConditionEvaluator::isPluginMatchingRegexActive(const std::string& regexString) const { +bool ConditionEvaluator::isPluginMatchingRegexActive( + const std::string& regexString) const { auto pathRegex = splitRegex(regexString); if (shouldParseOnly()) return false; - return isRegexMatchInDataDirectory(pathRegex, - [&](const std::string& filename) { - return loadOrderHandler_->IsPluginActive(filename); - }); + return isRegexMatchInDataDirectory( + pathRegex, [&](const std::string& filename) { + return loadOrderHandler_->IsPluginActive(filename); + }); } -bool ConditionEvaluator::arePluginsActive(const std::string& regexString) const { +bool ConditionEvaluator::arePluginsActive( + const std::string& regexString) const { auto pathRegex = splitRegex(regexString); if (shouldParseOnly()) return false; - return areRegexMatchesInDataDirectory(pathRegex, - [&](const std::string& filename) { - return loadOrderHandler_->IsPluginActive(filename); - }); + return areRegexMatchesInDataDirectory( + pathRegex, [&](const std::string& filename) { + return loadOrderHandler_->IsPluginActive(filename); + }); } -bool ConditionEvaluator::checksumMatches(const std::string& filePath, const uint32_t checksum) const { +bool ConditionEvaluator::checksumMatches(const std::string& filePath, + const uint32_t checksum) const { validatePath(filePath); if (shouldParseOnly()) @@ -255,12 +267,14 @@ bool ConditionEvaluator::checksumMatches(const std::string& filePath, const uint // Get the CRC from the game plugin cache if possible. try { realChecksum = gameCache_->GetPlugin(filePath)->GetCRC(); - } catch (...) {} + } catch (...) { + } if (realChecksum == 0) { if (boost::filesystem::exists(dataPath_ / filePath)) realChecksum = GetCrc32(dataPath_ / filePath); - else if (hasPluginFileExtension(filePath, gameType_) && boost::filesystem::exists(dataPath_ / (filePath + ".ghost"))) + else if (hasPluginFileExtension(filePath, gameType_) && + boost::filesystem::exists(dataPath_ / (filePath + ".ghost"))) realChecksum = GetCrc32(dataPath_ / (filePath + ".ghost")); } } @@ -268,7 +282,9 @@ bool ConditionEvaluator::checksumMatches(const std::string& filePath, const uint return checksum == realChecksum; } -bool ConditionEvaluator::compareVersions(const std::string & filePath, const std::string & testVersion, const std::string & comparator) const { +bool ConditionEvaluator::compareVersions(const std::string& filePath, + const std::string& testVersion, + const std::string& comparator) const { if (!fileExists(filePath)) return comparator == "!=" || comparator == "<" || comparator == "<="; @@ -280,12 +296,12 @@ bool ConditionEvaluator::compareVersions(const std::string & filePath, const std logger->trace("Version extracted: {}", trueVersion.AsString()); } - return ((comparator == "==" && trueVersion == givenVersion) - || (comparator == "!=" && trueVersion != givenVersion) - || (comparator == "<" && trueVersion < givenVersion) - || (comparator == ">" && trueVersion > givenVersion) - || (comparator == "<=" && trueVersion <= givenVersion) - || (comparator == ">=" && trueVersion >= givenVersion)); + return ((comparator == "==" && trueVersion == givenVersion) || + (comparator == "!=" && trueVersion != givenVersion) || + (comparator == "<" && trueVersion < givenVersion) || + (comparator == ">" && trueVersion > givenVersion) || + (comparator == "<=" && trueVersion <= givenVersion) || + (comparator == ">=" && trueVersion >= givenVersion)); } void ConditionEvaluator::validatePath(const boost::filesystem::path& path) { @@ -300,7 +316,8 @@ void ConditionEvaluator::validatePath(const boost::filesystem::path& path) { continue; if (component == ".." && temp.filename() == "..") { - throw ConditionSyntaxError((format("Invalid file path: %1%") % path.string()).str()); + throw ConditionSyntaxError( + (format("Invalid file path: %1%") % path.string()).str()); } temp /= component; @@ -310,11 +327,14 @@ void ConditionEvaluator::validateRegex(const std::string& regexString) { try { std::regex(regexString, std::regex::ECMAScript | std::regex::icase); } catch (std::regex_error& e) { - throw ConditionSyntaxError((format("Invalid regex string \"%1%\": %2%") % regexString % e.what()).str()); + throw ConditionSyntaxError( + (format("Invalid regex string \"%1%\": %2%") % regexString % e.what()) + .str()); } } -boost::filesystem::path ConditionEvaluator::getRegexParentPath(const std::string& regexString) { +boost::filesystem::path ConditionEvaluator::getRegexParentPath( + const std::string& regexString) { size_t pos = regexString.rfind('/'); if (pos == std::string::npos) @@ -323,7 +343,8 @@ boost::filesystem::path ConditionEvaluator::getRegexParentPath(const std::string return boost::filesystem::path(regexString.substr(0, pos)); } -std::string ConditionEvaluator::getRegexFilename(const std::string& regexString) { +std::string ConditionEvaluator::getRegexFilename( + const std::string& regexString) { size_t pos = regexString.rfind('/'); if (pos == std::string::npos) @@ -332,11 +353,12 @@ std::string ConditionEvaluator::getRegexFilename(const std::string& regexString) return regexString.substr(pos + 1); } -std::pair ConditionEvaluator::splitRegex(const std::string& regexString) { - // Can't support a regex string where all path components may be regex, since this could - // lead to massive scanning if an unfortunately-named directory is encountered. - // As such, only the filename portion can be a regex. Need to separate that from the rest - // of the string. +std::pair ConditionEvaluator::splitRegex( + const std::string& regexString) { + // Can't support a regex string where all path components may be regex, since + // this could lead to massive scanning if an unfortunately-named directory is + // encountered. As such, only the filename portion can be a regex. Need to + // separate that from the rest of the string. validateRegex(regexString); @@ -349,67 +371,83 @@ std::pair ConditionEvaluator::splitRegex(co try { reg = std::regex(filename, std::regex::ECMAScript | std::regex::icase); } catch (std::regex_error& e) { - throw ConditionSyntaxError((format("Invalid regex string \"%1%\": %2%") % filename % e.what()).str()); + throw ConditionSyntaxError( + (format("Invalid regex string \"%1%\": %2%") % filename % e.what()) + .str()); } return std::pair(parent, reg); } -bool ConditionEvaluator::isGameSubdirectory(const boost::filesystem::path& path) const { +bool ConditionEvaluator::isGameSubdirectory( + const boost::filesystem::path& path) const { boost::filesystem::path parentPath = dataPath_ / path; - return boost::filesystem::exists(parentPath) && boost::filesystem::is_directory(parentPath); + return boost::filesystem::exists(parentPath) && + boost::filesystem::is_directory(parentPath); } -bool ConditionEvaluator::isRegexMatchInDataDirectory(const std::pair& pathRegex, - const std::function condition) const { - // Now we have a valid parent path and a regex filename. Check that the - // parent path exists and is a directory. +bool ConditionEvaluator::isRegexMatchInDataDirectory( + const std::pair& pathRegex, + const std::function condition) const { + // Now we have a valid parent path and a regex filename. Check that the + // parent path exists and is a directory. if (!isGameSubdirectory(pathRegex.first)) { auto logger = getLogger(); if (logger) { - logger->trace("The path \"{}\" is not a game subdirectory.", pathRegex.first.string()); + logger->trace("The path \"{}\" is not a game subdirectory.", + pathRegex.first.string()); } return false; } - return std::any_of(boost::filesystem::directory_iterator(dataPath_ / pathRegex.first), - boost::filesystem::directory_iterator(), - [&](const boost::filesystem::directory_entry& entry) { - const std::string filename = entry.path().filename().string(); - return std::regex_match(filename, pathRegex.second) && condition(filename); - }); + return std::any_of( + boost::filesystem::directory_iterator(dataPath_ / pathRegex.first), + boost::filesystem::directory_iterator(), + [&](const boost::filesystem::directory_entry& entry) { + const std::string filename = entry.path().filename().string(); + return std::regex_match(filename, pathRegex.second) && + condition(filename); + }); } -bool ConditionEvaluator::areRegexMatchesInDataDirectory(const std::pair& pathRegex, - const std::function condition) const { +bool ConditionEvaluator::areRegexMatchesInDataDirectory( + const std::pair& pathRegex, + const std::function condition) const { bool foundOneFile = false; - return isRegexMatchInDataDirectory(pathRegex, [&](const std::string& filename) { - if (condition(filename)) { - if (foundOneFile) - return true; + return isRegexMatchInDataDirectory(pathRegex, + [&](const std::string& filename) { + if (condition(filename)) { + if (foundOneFile) + return true; - foundOneFile = true; - } + foundOneFile = true; + } - return false; - }); + return false; + }); } -bool ConditionEvaluator::parseCondition(const std::string & condition) const { +bool ConditionEvaluator::parseCondition(const std::string& condition) const { if (condition.empty()) return true; - ConditionGrammar grammar(*this); + ConditionGrammar + grammar(*this); boost::spirit::qi::space_type skipper; std::string::const_iterator begin = condition.begin(); std::string::const_iterator end = condition.end(); bool evaluation; - bool parseResult = boost::spirit::qi::phrase_parse(begin, end, grammar, skipper, evaluation); + bool parseResult = + boost::spirit::qi::phrase_parse(begin, end, grammar, skipper, evaluation); if (!parseResult || begin != end) { - throw ConditionSyntaxError((boost::format("Failed to parse condition \"%1%\": only partially matched expected syntax.") % condition).str()); + throw ConditionSyntaxError( + (boost::format("Failed to parse condition \"%1%\": only partially " + "matched expected syntax.") % + condition) + .str()); } return evaluation; @@ -428,7 +466,9 @@ Version ConditionEvaluator::getVersion(const std::string& filePath) const { // if it appears to be valid, otherwise treat it as a non // plugin file. if (Plugin::IsValid(filePath, gameType_, dataPath_)) - return Version(Plugin(gameType_, dataPath_, loadOrderHandler_, filePath, true).GetVersion()); + return Version( + Plugin(gameType_, dataPath_, loadOrderHandler_, filePath, true) + .GetVersion()); return Version(dataPath_ / filePath); } diff --git a/src/api/metadata/condition_evaluator.h b/src/api/metadata/condition_evaluator.h index 87e612d9..5bfeb0a2 100644 --- a/src/api/metadata/condition_evaluator.h +++ b/src/api/metadata/condition_evaluator.h @@ -46,7 +46,8 @@ public: std::shared_ptr loadOrderHandler); bool evaluate(const std::string& condition) const; - bool evaluate(const PluginCleaningData& cleaningData, const std::string& pluginName) const; + bool evaluate(const PluginCleaningData& cleaningData, + const std::string& pluginName) const; PluginMetadata evaluateAll(const PluginMetadata& pluginMetadata) const; bool fileExists(const std::string& filePath) const; @@ -63,21 +64,27 @@ public: bool compareVersions(const std::string& filePath, const std::string& testVersion, const std::string& comparator) const; + private: static void validatePath(const boost::filesystem::path& path); static void validateRegex(const std::string& regexString); - static boost::filesystem::path getRegexParentPath(const std::string& regexString); + static boost::filesystem::path getRegexParentPath( + const std::string& regexString); static std::string getRegexFilename(const std::string& regexString); - // Split a regex string into the non-regex filesystem parent path, and the regex filename. - static std::pair splitRegex(const std::string& regexString); + // Split a regex string into the non-regex filesystem parent path, and the + // regex filename. + static std::pair splitRegex( + const std::string& regexString); bool isGameSubdirectory(const boost::filesystem::path& path) const; - bool isRegexMatchInDataDirectory(const std::pair& pathRegex, - const std::function condition) const; - bool areRegexMatchesInDataDirectory(const std::pair& pathRegex, - const std::function condition) const; + bool isRegexMatchInDataDirectory( + const std::pair& pathRegex, + const std::function condition) const; + bool areRegexMatchesInDataDirectory( + const std::pair& pathRegex, + const std::function condition) const; bool parseCondition(const std::string& condition) const; diff --git a/src/api/metadata/condition_grammar.h b/src/api/metadata/condition_grammar.h index 893b8b2d..6a3138af 100644 --- a/src/api/metadata/condition_grammar.h +++ b/src/api/metadata/condition_grammar.h @@ -33,81 +33,93 @@ #define BOOST_SPIRIT_USE_PHOENIX_V3 1 #endif -#include -#include #include #include #include +#include #include #include -#include #include +#include +#include -#include "loot/exception/condition_syntax_error.h" #include "api/game/game.h" #include "api/helpers/logging.h" #include "api/helpers/version.h" #include "api/metadata/condition_evaluator.h" #include "api/plugin/plugin.h" +#include "loot/exception/condition_syntax_error.h" namespace loot { template -class ConditionGrammar : public boost::spirit::qi::grammar < Iterator, bool(), Skipper > { +class ConditionGrammar + : public boost::spirit::qi::grammar { public: - ConditionGrammar(const ConditionEvaluator& evaluator) : ConditionGrammar::base_type(expression_, "condition grammar"), evaluator_(evaluator) { + ConditionGrammar(const ConditionEvaluator& evaluator) : + ConditionGrammar::base_type(expression_, "condition grammar"), + evaluator_(evaluator) { using boost::spirit::unicode::char_; using boost::spirit::unicode::string; namespace phoenix = boost::phoenix; namespace qi = boost::spirit::qi; expression_ = - qi::eps > - compound_[qi::labels::_val = qi::labels::_1] - >> *((qi::lit("or") >> compound_)[qi::labels::_val = qi::labels::_val || qi::labels::_1]) - ; + qi::eps > compound_[qi::labels::_val = qi::labels::_1] >> + *((qi::lit("or") >> + compound_)[qi::labels::_val = qi::labels::_val || qi::labels::_1]); compound_ = - condition_[qi::labels::_val = qi::labels::_1] - >> *((qi::lit("and") >> condition_)[qi::labels::_val = qi::labels::_val && qi::labels::_1]) - ; + condition_[qi::labels::_val = qi::labels::_1] >> + *((qi::lit("and") >> + condition_)[qi::labels::_val = qi::labels::_val && qi::labels::_1]); condition_ = - function_[qi::labels::_val = qi::labels::_1] - | (qi::lit("not") > condition_)[qi::labels::_val = !qi::labels::_1] - | ('(' > expression_ > ')')[qi::labels::_val = qi::labels::_1] - ; + function_[qi::labels::_val = qi::labels::_1] | + (qi::lit("not") > condition_)[qi::labels::_val = !qi::labels::_1] | + ('(' > expression_ > ')')[qi::labels::_val = qi::labels::_1]; function_ = - ("file(" > quotedStr_ > ')')[phoenix::bind(&ConditionGrammar::CheckFile, this, qi::labels::_val, qi::labels::_1)] - | ("many(" > quotedStr_ > ')')[phoenix::bind(&ConditionGrammar::CheckMany, this, qi::labels::_val, qi::labels::_1)] - | ("checksum(" > filePath_ > ',' > qi::hex > ')')[phoenix::bind(&ConditionGrammar::CheckSum, this, qi::labels::_val, qi::labels::_1, qi::labels::_2)] - | ("version(" > filePath_ > ',' > quotedStr_ > ',' > comparator_ > ')')[phoenix::bind(&ConditionGrammar::CheckVersion, this, qi::labels::_val, qi::labels::_1, qi::labels::_2, qi::labels::_3)] - | ("active(" > quotedStr_ > ')')[phoenix::bind(&ConditionGrammar::CheckActive, this, qi::labels::_val, qi::labels::_1)] - | ("many_active(" > quotedStr_ > ')')[phoenix::bind(&ConditionGrammar::CheckManyActive, this, qi::labels::_val, qi::labels::_1)] - ; + ("file(" > quotedStr_ > ')')[phoenix::bind(&ConditionGrammar::CheckFile, + this, + qi::labels::_val, + qi::labels::_1)] | + ("many(" > quotedStr_ > ')')[phoenix::bind(&ConditionGrammar::CheckMany, + this, + qi::labels::_val, + qi::labels::_1)] | + ("checksum(" > filePath_ > ',' > qi::hex > + ')')[phoenix::bind(&ConditionGrammar::CheckSum, + this, + qi::labels::_val, + qi::labels::_1, + qi::labels::_2)] | + ("version(" > filePath_ > ',' > quotedStr_ > ',' > comparator_ > + ')')[phoenix::bind(&ConditionGrammar::CheckVersion, + this, + qi::labels::_val, + qi::labels::_1, + qi::labels::_2, + qi::labels::_3)] | + ("active(" > quotedStr_ > + ')')[phoenix::bind(&ConditionGrammar::CheckActive, + this, + qi::labels::_val, + qi::labels::_1)] | + ("many_active(" > quotedStr_ > + ')')[phoenix::bind(&ConditionGrammar::CheckManyActive, + this, + qi::labels::_val, + qi::labels::_1)]; quotedStr_ %= '"' > +(char_ - '"') > '"'; filePath_ %= '"' > +(char_ - invalidPathChars_) > '"'; - invalidPathChars_ %= - char_(':') - | char_('*') - | char_('?') - | char_('"') - | char_('<') - | char_('>') - | char_('|') - ; + invalidPathChars_ %= char_(':') | char_('*') | char_('?') | char_('"') | + char_('<') | char_('>') | char_('|'); - comparator_ %= - string("==") - | string("!=") - | string("<=") - | string(">=") - | string("<") - | string(">") - ; + comparator_ %= string("==") | string("!=") | string("<=") | string(">=") | + string("<") | string(">"); expression_.name("expression"); compound_.name("compound condition"); @@ -118,14 +130,62 @@ public: comparator_.name("comparator"); invalidPathChars_.name("invalid file path characters"); - qi::on_error(expression_, phoenix::bind(&ConditionGrammar::SyntaxError, this, qi::labels::_1, qi::labels::_2, qi::labels::_3, qi::labels::_4)); - qi::on_error(compound_, phoenix::bind(&ConditionGrammar::SyntaxError, this, qi::labels::_1, qi::labels::_2, qi::labels::_3, qi::labels::_4)); - qi::on_error(condition_, phoenix::bind(&ConditionGrammar::SyntaxError, this, qi::labels::_1, qi::labels::_2, qi::labels::_3, qi::labels::_4)); - qi::on_error(function_, phoenix::bind(&ConditionGrammar::SyntaxError, this, qi::labels::_1, qi::labels::_2, qi::labels::_3, qi::labels::_4)); - qi::on_error(quotedStr_, phoenix::bind(&ConditionGrammar::SyntaxError, this, qi::labels::_1, qi::labels::_2, qi::labels::_3, qi::labels::_4)); - qi::on_error(filePath_, phoenix::bind(&ConditionGrammar::SyntaxError, this, qi::labels::_1, qi::labels::_2, qi::labels::_3, qi::labels::_4)); - qi::on_error(comparator_, phoenix::bind(&ConditionGrammar::SyntaxError, this, qi::labels::_1, qi::labels::_2, qi::labels::_3, qi::labels::_4)); - qi::on_error(invalidPathChars_, phoenix::bind(&ConditionGrammar::SyntaxError, this, qi::labels::_1, qi::labels::_2, qi::labels::_3, qi::labels::_4)); + qi::on_error(expression_, + phoenix::bind(&ConditionGrammar::SyntaxError, + this, + qi::labels::_1, + qi::labels::_2, + qi::labels::_3, + qi::labels::_4)); + qi::on_error(compound_, + phoenix::bind(&ConditionGrammar::SyntaxError, + this, + qi::labels::_1, + qi::labels::_2, + qi::labels::_3, + qi::labels::_4)); + qi::on_error(condition_, + phoenix::bind(&ConditionGrammar::SyntaxError, + this, + qi::labels::_1, + qi::labels::_2, + qi::labels::_3, + qi::labels::_4)); + qi::on_error(function_, + phoenix::bind(&ConditionGrammar::SyntaxError, + this, + qi::labels::_1, + qi::labels::_2, + qi::labels::_3, + qi::labels::_4)); + qi::on_error(quotedStr_, + phoenix::bind(&ConditionGrammar::SyntaxError, + this, + qi::labels::_1, + qi::labels::_2, + qi::labels::_3, + qi::labels::_4)); + qi::on_error(filePath_, + phoenix::bind(&ConditionGrammar::SyntaxError, + this, + qi::labels::_1, + qi::labels::_2, + qi::labels::_3, + qi::labels::_4)); + qi::on_error(comparator_, + phoenix::bind(&ConditionGrammar::SyntaxError, + this, + qi::labels::_1, + qi::labels::_2, + qi::labels::_3, + qi::labels::_4)); + qi::on_error(invalidPathChars_, + phoenix::bind(&ConditionGrammar::SyntaxError, + this, + qi::labels::_1, + qi::labels::_2, + qi::labels::_3, + qi::labels::_4)); logger_ = getLogger(); } @@ -138,7 +198,7 @@ private: return strpbrk(file.c_str(), ":\\*?|") != nullptr; } - //Eval's exact paths. Check for files and ghosted plugins. + // Eval's exact paths. Check for files and ghosted plugins. void CheckFile(bool& result, const std::string& file) const { if (logger_) { logger_->trace("Checking to see if the file \"{}\" exists.", file); @@ -157,14 +217,19 @@ private: void CheckMany(bool& result, const std::string& regexStr) const { if (logger_) { - logger_->trace("Checking to see if more than one file matching the regex \"{}\" exists.", regexStr); + logger_->trace( + "Checking to see if more than one file matching the regex \"{}\" " + "exists.", + regexStr); } result = false; result = evaluator_.regexMatchesExist(regexStr); } - void CheckSum(bool& result, const std::string& file, const uint32_t checksum) { + void CheckSum(bool& result, + const std::string& file, + const uint32_t checksum) { if (logger_) { logger_->trace("Checking the CRC of the file \"{}\".", file); } @@ -173,7 +238,10 @@ private: result = evaluator_.checksumMatches(file, checksum); } - void CheckVersion(bool& result, const std::string& file, const std::string& version, const std::string& comparator) const { + void CheckVersion(bool& result, + const std::string& file, + const std::string& version, + const std::string& comparator) const { if (logger_) { logger_->trace("Checking the version of the file \"{}\".", file); } @@ -200,23 +268,35 @@ private: void CheckManyActive(bool& result, const std::string& regexStr) const { if (logger_) { - logger_->trace("Checking to see if more than one file matching the regex \"{}\" is active.", regexStr); + logger_->trace( + "Checking to see if more than one file matching the regex \"{}\" is " + "active.", + regexStr); } result = false; result = evaluator_.arePluginsActive(regexStr); } - void SyntaxError(Iterator const& first, Iterator const& last, Iterator const& errorpos, boost::spirit::info const& what) { + void SyntaxError(Iterator const& first, + Iterator const& last, + Iterator const& errorpos, + boost::spirit::info const& what) { std::string condition(first, last); std::string context(errorpos, last); boost::trim(context); - throw ConditionSyntaxError((boost::format("Failed to parse condition \"%1%\": expected \"%2%\" at \"%3%\".") % condition % what.tag % context).str()); + throw ConditionSyntaxError( + (boost::format("Failed to parse condition \"%1%\": expected \"%2%\" at " + "\"%3%\".") % + condition % what.tag % context) + .str()); } - boost::spirit::qi::rule expression_, compound_, condition_, function_; - boost::spirit::qi::rule quotedStr_, filePath_, comparator_; + boost::spirit::qi::rule expression_, compound_, + condition_, function_; + boost::spirit::qi::rule quotedStr_, filePath_, + comparator_; boost::spirit::qi::rule invalidPathChars_; const ConditionEvaluator& evaluator_; diff --git a/src/api/metadata/conditional_metadata.cpp b/src/api/metadata/conditional_metadata.cpp index 85737f86..dc52f1b1 100644 --- a/src/api/metadata/conditional_metadata.cpp +++ b/src/api/metadata/conditional_metadata.cpp @@ -33,15 +33,12 @@ using std::string; namespace loot { ConditionalMetadata::ConditionalMetadata() {} -ConditionalMetadata::ConditionalMetadata(const string& condition) : condition_(condition) {} +ConditionalMetadata::ConditionalMetadata(const string& condition) : + condition_(condition) {} -bool ConditionalMetadata::IsConditional() const { - return !condition_.empty(); -} +bool ConditionalMetadata::IsConditional() const { return !condition_.empty(); } -std::string ConditionalMetadata::GetCondition() const { - return condition_; -} +std::string ConditionalMetadata::GetCondition() const { return condition_; } void ConditionalMetadata::ParseCondition() const { if (!condition_.empty()) { diff --git a/src/api/metadata/file.cpp b/src/api/metadata/file.cpp index 49448a7b..dd9d8768 100644 --- a/src/api/metadata/file.cpp +++ b/src/api/metadata/file.cpp @@ -31,20 +31,22 @@ namespace loot { File::File() {} -File::File(const std::string& name, const std::string& display, const std::string& condition) - : name_(name), display_(display), ConditionalMetadata(condition) {} +File::File(const std::string& name, + const std::string& display, + const std::string& condition) : + name_(name), + display_(display), + ConditionalMetadata(condition) {} -bool File::operator < (const File& rhs) const { +bool File::operator<(const File& rhs) const { return boost::ilexicographical_compare(GetName(), rhs.GetName()); } -bool File::operator == (const File& rhs) const { +bool File::operator==(const File& rhs) const { return boost::iequals(GetName(), rhs.GetName()); } -std::string File::GetName() const { - return name_; -} +std::string File::GetName() const { return name_; } std::string File::GetDisplayName() const { if (display_.empty()) diff --git a/src/api/metadata/location.cpp b/src/api/metadata/location.cpp index 56b42236..b2410ba3 100644 --- a/src/api/metadata/location.cpp +++ b/src/api/metadata/location.cpp @@ -29,21 +29,19 @@ namespace loot { Location::Location() {} -Location::Location(const std::string& url, const std::string& name) : url_(url), name_(name) {} +Location::Location(const std::string& url, const std::string& name) : + url_(url), + name_(name) {} -bool Location::operator < (const Location& rhs) const { +bool Location::operator<(const Location& rhs) const { return boost::ilexicographical_compare(url_, rhs.GetURL()); } -bool Location::operator == (const Location& rhs) const { +bool Location::operator==(const Location& rhs) const { return boost::iequals(url_, rhs.GetURL()); } -std::string Location::GetURL() const { - return url_; -} +std::string Location::GetURL() const { return url_; } -std::string Location::GetName() const { - return name_; -} +std::string Location::GetName() const { return name_; } } diff --git a/src/api/metadata/message.cpp b/src/api/metadata/message.cpp index 0f2ec943..b25ffa4d 100644 --- a/src/api/metadata/message.cpp +++ b/src/api/metadata/message.cpp @@ -31,44 +31,51 @@ namespace loot { Message::Message() : type_(MessageType::say) {} -Message::Message(const MessageType type, const std::string& content, - const std::string& condition) : type_(type), ConditionalMetadata(condition) { +Message::Message(const MessageType type, + const std::string& content, + const std::string& condition) : + type_(type), + ConditionalMetadata(condition) { content_.push_back(MessageContent(content)); } -Message::Message(const MessageType type, const std::vector& content, - const std::string& condition) : type_(type), content_(content), ConditionalMetadata(condition) { +Message::Message(const MessageType type, + const std::vector& content, + const std::string& condition) : + type_(type), + content_(content), + ConditionalMetadata(condition) { if (content.size() > 1) { bool englishStringExists = false; - for (const auto &mc : content) { + for (const auto& mc : content) { if (mc.GetLanguage() == MessageContent::defaultLanguage) englishStringExists = true; } if (!englishStringExists) - throw std::invalid_argument("bad conversion: multilingual messages must contain an English content string"); + throw std::invalid_argument( + "bad conversion: multilingual messages must contain an English " + "content string"); } } -bool Message::operator < (const Message& rhs) const { +bool Message::operator<(const Message& rhs) const { if (!content_.empty() && !rhs.GetContent().empty()) - return boost::ilexicographical_compare(GetContent(MessageContent::defaultLanguage).GetText(), rhs.GetContent(MessageContent::defaultLanguage).GetText()); + return boost::ilexicographical_compare( + GetContent(MessageContent::defaultLanguage).GetText(), + rhs.GetContent(MessageContent::defaultLanguage).GetText()); else if (content_.empty() && !rhs.GetContent().empty()) return true; else return false; } -bool Message::operator == (const Message& rhs) const { +bool Message::operator==(const Message& rhs) const { return (content_ == rhs.GetContent()); } -MessageType Message::GetType() const { - return type_; -} +MessageType Message::GetType() const { return type_; } -std::vector Message::GetContent() const { - return content_; -} +std::vector Message::GetContent() const { return content_; } MessageContent Message::GetContent(const std::string& language) const { return MessageContent::Choose(content_, language); } diff --git a/src/api/metadata/message_content.cpp b/src/api/metadata/message_content.cpp index a2f43ad8..1454dd7b 100644 --- a/src/api/metadata/message_content.cpp +++ b/src/api/metadata/message_content.cpp @@ -31,21 +31,20 @@ const std::string MessageContent::defaultLanguage = "en"; MessageContent::MessageContent() : language_(MessageContent::defaultLanguage) {} -MessageContent::MessageContent(const std::string& text, const std::string& language) : text_(text), language_(language) {} +MessageContent::MessageContent(const std::string& text, + const std::string& language) : + text_(text), + language_(language) {} -std::string MessageContent::GetText() const { - return text_; -} +std::string MessageContent::GetText() const { return text_; } -std::string MessageContent::GetLanguage() const { - return language_; -} +std::string MessageContent::GetLanguage() const { return language_; } -bool MessageContent::operator < (const MessageContent& rhs) const { +bool MessageContent::operator<(const MessageContent& rhs) const { return boost::ilexicographical_compare(text_, rhs.GetText()); } -bool MessageContent::operator == (const MessageContent& rhs) const { +bool MessageContent::operator==(const MessageContent& rhs) const { return (boost::iequals(text_, rhs.GetText())); } MessageContent MessageContent::Choose(const std::vector content, @@ -56,7 +55,7 @@ MessageContent MessageContent::Choose(const std::vector content, return content[0]; else { MessageContent english; - for (const auto &mc : content) { + for (const auto& mc : content) { if (mc.GetLanguage() == language) { return mc; } else if (mc.GetLanguage() == MessageContent::defaultLanguage) diff --git a/src/api/metadata/plugin_cleaning_data.cpp b/src/api/metadata/plugin_cleaning_data.cpp index be3ab448..0055153e 100644 --- a/src/api/metadata/plugin_cleaning_data.cpp +++ b/src/api/metadata/plugin_cleaning_data.cpp @@ -31,50 +31,53 @@ namespace loot { PluginCleaningData::PluginCleaningData() : crc_(0), itm_(0), ref_(0), nav_(0) {} -PluginCleaningData::PluginCleaningData(uint32_t crc, const std::string& utility) - : crc_(crc), utility_(utility), itm_(0), ref_(0), nav_(0) {} +PluginCleaningData::PluginCleaningData(uint32_t crc, + const std::string& utility) : + crc_(crc), + utility_(utility), + itm_(0), + ref_(0), + nav_(0) {} PluginCleaningData::PluginCleaningData(uint32_t crc, const std::string& utility, const std::vector& info, unsigned int itm, unsigned int ref, - unsigned int nav) - : crc_(crc), itm_(itm), ref_(ref), nav_(nav), utility_(utility), info_(info) {} + unsigned int nav) : + crc_(crc), + itm_(itm), + ref_(ref), + nav_(nav), + utility_(utility), + info_(info) {} -bool PluginCleaningData::operator < (const PluginCleaningData& rhs) const { +bool PluginCleaningData::operator<(const PluginCleaningData& rhs) const { return crc_ < rhs.GetCRC(); } -bool PluginCleaningData::operator == (const PluginCleaningData& rhs) const { +bool PluginCleaningData::operator==(const PluginCleaningData& rhs) const { return crc_ == rhs.GetCRC(); } -uint32_t PluginCleaningData::GetCRC() const { - return crc_; -} +uint32_t PluginCleaningData::GetCRC() const { return crc_; } -unsigned int PluginCleaningData::GetITMCount() const { - return itm_; -} +unsigned int PluginCleaningData::GetITMCount() const { return itm_; } unsigned int PluginCleaningData::GetDeletedReferenceCount() const { return ref_; } -unsigned int PluginCleaningData::GetDeletedNavmeshCount() const { - return nav_; -} +unsigned int PluginCleaningData::GetDeletedNavmeshCount() const { return nav_; } -std::string PluginCleaningData::GetCleaningUtility() const { - return utility_; -} +std::string PluginCleaningData::GetCleaningUtility() const { return utility_; } std::vector PluginCleaningData::GetInfo() const { return info_; } -MessageContent PluginCleaningData::ChooseInfo(const std::string& language) const { +MessageContent PluginCleaningData::ChooseInfo( + const std::string& language) const { auto logger = getLogger(); if (logger) { logger->trace("Choosing dirty info content."); diff --git a/src/api/metadata/plugin_metadata.cpp b/src/api/metadata/plugin_metadata.cpp index cbb78751..2242d8a9 100644 --- a/src/api/metadata/plugin_metadata.cpp +++ b/src/api/metadata/plugin_metadata.cpp @@ -42,8 +42,10 @@ using std::vector; namespace loot { PluginMetadata::PluginMetadata() : enabled_(true) {} -PluginMetadata::PluginMetadata(const std::string& n) : name_(n), enabled_(true) { - //If the name passed ends in '.ghost', that should be trimmed. +PluginMetadata::PluginMetadata(const std::string& n) : + name_(n), + enabled_(true) { + // If the name passed ends in '.ghost', that should be trimmed. if (boost::iends_with(name_, ".ghost")) name_ = name_.substr(0, name_.length() - 6); } @@ -57,8 +59,8 @@ void PluginMetadata::MergeMetadata(const PluginMetadata& plugin) { if (plugin.HasNameOnly()) return; -// For 'enabled' and 'priority' metadata, use the given plugin's values, -// but if the 'priority' user value is not explicit, ignore it. + // For 'enabled' and 'priority' metadata, use the given plugin's values, + // but if the 'priority' user value is not explicit, ignore it. enabled_ = plugin.IsEnabled(); if (plugin.localPriority_.IsExplicit()) { @@ -76,14 +78,16 @@ void PluginMetadata::MergeMetadata(const PluginMetadata& plugin) { // these strings. loadAfter_.insert(begin(plugin.loadAfter_), end(plugin.loadAfter_)); requirements_.insert(begin(plugin.requirements_), end(plugin.requirements_)); - incompatibilities_.insert(begin(plugin.incompatibilities_), end(plugin.incompatibilities_)); + incompatibilities_.insert(begin(plugin.incompatibilities_), + end(plugin.incompatibilities_)); // Merge Bash Tags too. Conditions are ignored during comparison, but // if a tag is added and removed, both instances will be in the set. tags_.insert(begin(plugin.tags_), end(plugin.tags_)); // Messages are in an ordered list, and should be fully merged. - messages_.insert(end(messages_), begin(plugin.messages_), end(plugin.messages_)); + messages_.insert( + end(messages_), begin(plugin.messages_), end(plugin.messages_)); dirtyInfo_.insert(begin(plugin.dirtyInfo_), end(plugin.dirtyInfo_)); cleanInfo_.insert(begin(plugin.cleanInfo_), end(plugin.cleanInfo_)); @@ -102,7 +106,7 @@ PluginMetadata PluginMetadata::NewMetadata(const PluginMetadata& plugin) const { PluginMetadata p(*this); - //Compare this plugin against the given plugin. + // Compare this plugin against the given plugin. set filesDiff; set_difference(begin(loadAfter_), end(loadAfter_), @@ -174,45 +178,29 @@ PluginMetadata PluginMetadata::NewMetadata(const PluginMetadata& plugin) const { return p; } -std::string PluginMetadata::GetName() const { - return name_; -} +std::string PluginMetadata::GetName() const { return name_; } std::string PluginMetadata::GetLowercasedName() const { return boost::locale::to_lower(name_); } -bool PluginMetadata::IsEnabled() const { - return enabled_; -} +bool PluginMetadata::IsEnabled() const { return enabled_; } -Priority PluginMetadata::GetLocalPriority() const { - return localPriority_; -} +Priority PluginMetadata::GetLocalPriority() const { return localPriority_; } -Priority PluginMetadata::GetGlobalPriority() const { - return globalPriority_; -} +Priority PluginMetadata::GetGlobalPriority() const { return globalPriority_; } -std::set PluginMetadata::GetLoadAfterFiles() const { - return loadAfter_; -} +std::set PluginMetadata::GetLoadAfterFiles() const { return loadAfter_; } -std::set PluginMetadata::GetRequirements() const { - return requirements_; -} +std::set PluginMetadata::GetRequirements() const { return requirements_; } std::set PluginMetadata::GetIncompatibilities() const { return incompatibilities_; } -std::vector PluginMetadata::GetMessages() const { - return messages_; -} +std::vector PluginMetadata::GetMessages() const { return messages_; } -std::set PluginMetadata::GetTags() const { - return tags_; -} +std::set PluginMetadata::GetTags() const { return tags_; } std::set PluginMetadata::GetDirtyInfo() const { return dirtyInfo_; @@ -222,22 +210,22 @@ std::set PluginMetadata::GetCleanInfo() const { return cleanInfo_; } -std::set PluginMetadata::GetLocations() const { - return locations_; -} +std::set PluginMetadata::GetLocations() const { return locations_; } -std::vector PluginMetadata::GetSimpleMessages(const std::string& language) const { +std::vector PluginMetadata::GetSimpleMessages( + const std::string& language) const { std::vector simpleMessages(messages_.size()); - std::transform(begin(messages_), end(messages_), begin(simpleMessages), [&](const Message& message) { - return message.ToSimpleMessage(language); - }); + std::transform(begin(messages_), + end(messages_), + begin(simpleMessages), + [&](const Message& message) { + return message.ToSimpleMessage(language); + }); return simpleMessages; } -void PluginMetadata::SetEnabled(const bool e) { - enabled_ = e; -} +void PluginMetadata::SetEnabled(const bool e) { enabled_ = e; } void PluginMetadata::SetLocalPriority(const Priority& priority) { localPriority_ = priority; @@ -263,11 +251,10 @@ void PluginMetadata::SetMessages(const std::vector& m) { messages_ = m; } -void PluginMetadata::SetTags(const std::set& t) { - tags_ = t; -} +void PluginMetadata::SetTags(const std::set& t) { tags_ = t; } -void PluginMetadata::SetDirtyInfo(const std::set& dirtyInfo) { +void PluginMetadata::SetDirtyInfo( + const std::set& dirtyInfo) { dirtyInfo_ = dirtyInfo; } @@ -280,47 +267,44 @@ void PluginMetadata::SetLocations(const std::set& locations) { } bool PluginMetadata::HasNameOnly() const { - return !localPriority_.IsExplicit() - && !globalPriority_.IsExplicit() - && loadAfter_.empty() - && requirements_.empty() - && incompatibilities_.empty() - && messages_.empty() - && tags_.empty() - && dirtyInfo_.empty() - && cleanInfo_.empty() - && locations_.empty(); + return !localPriority_.IsExplicit() && !globalPriority_.IsExplicit() && + loadAfter_.empty() && requirements_.empty() && + incompatibilities_.empty() && messages_.empty() && tags_.empty() && + dirtyInfo_.empty() && cleanInfo_.empty() && locations_.empty(); } bool PluginMetadata::IsRegexPlugin() const { - // Treat as regex if the plugin filename contains any of ":\*?|" as - // they are not valid Windows filename characters, but have meaning - // in regexes. + // Treat as regex if the plugin filename contains any of ":\*?|" as + // they are not valid Windows filename characters, but have meaning + // in regexes. return strpbrk(name_.c_str(), ":\\*?|") != nullptr; } -bool PluginMetadata::operator == (const PluginMetadata& rhs) const { +bool PluginMetadata::operator==(const PluginMetadata& rhs) const { if (IsRegexPlugin() == rhs.IsRegexPlugin()) return boost::iequals(name_, rhs.GetName()); if (IsRegexPlugin()) - return regex_match(rhs.GetName(), regex(name_, regex::ECMAScript | regex::icase)); + return regex_match(rhs.GetName(), + regex(name_, regex::ECMAScript | regex::icase)); else - return regex_match(name_, regex(rhs.GetName(), regex::ECMAScript | regex::icase)); + return regex_match(name_, + regex(rhs.GetName(), regex::ECMAScript | regex::icase)); } -bool PluginMetadata::operator != (const PluginMetadata& rhs) const { +bool PluginMetadata::operator!=(const PluginMetadata& rhs) const { return !(*this == rhs); } -bool PluginMetadata::operator == (const std::string& rhs) const { +bool PluginMetadata::operator==(const std::string& rhs) const { if (IsRegexPlugin()) - return regex_match(PluginMetadata(rhs).GetName(), regex(name_, regex::ECMAScript | regex::icase)); + return regex_match(PluginMetadata(rhs).GetName(), + regex(name_, regex::ECMAScript | regex::icase)); else return boost::iequals(name_, PluginMetadata(rhs).GetName()); } -bool PluginMetadata::operator != (const std::string& rhs) const { +bool PluginMetadata::operator!=(const std::string& rhs) const { return !(*this == rhs); } } diff --git a/src/api/metadata/priority.cpp b/src/api/metadata/priority.cpp index 38be1fdf..53cd3f17 100644 --- a/src/api/metadata/priority.cpp +++ b/src/api/metadata/priority.cpp @@ -27,8 +27,7 @@ namespace loot { Priority::Priority() : value_(0), isExplicitZeroValue_(false) {} -Priority::Priority(const int value) - : isExplicitZeroValue_(true) { +Priority::Priority(const int value) : isExplicitZeroValue_(true) { if (value > 127) { value_ = 127; } else if (value < -127) { @@ -38,31 +37,27 @@ Priority::Priority(const int value) } } -short Priority::GetValue() const { - return value_; -} +short Priority::GetValue() const { return value_; } bool Priority::IsExplicit() const { return value_ != 0 || isExplicitZeroValue_; } -bool Priority::operator < (const Priority& rhs) const { +bool Priority::operator<(const Priority& rhs) const { return value_ < rhs.value_; } -bool Priority::operator > (const Priority& rhs) const { +bool Priority::operator>(const Priority& rhs) const { return value_ > rhs.value_; } -bool Priority::operator >= (const Priority& rhs) const { +bool Priority::operator>=(const Priority& rhs) const { return value_ >= rhs.value_; } -bool Priority::operator == (const Priority& rhs) const { +bool Priority::operator==(const Priority& rhs) const { return value_ == rhs.value_; } -bool Priority::operator > (const uint8_t rhs) const { - return value_ > rhs; -} +bool Priority::operator>(const uint8_t rhs) const { return value_ > rhs; } } diff --git a/src/api/metadata/tag.cpp b/src/api/metadata/tag.cpp index 65b6d6f0..0a684775 100644 --- a/src/api/metadata/tag.cpp +++ b/src/api/metadata/tag.cpp @@ -29,24 +29,26 @@ namespace loot { Tag::Tag() : addTag_(true) {} -Tag::Tag(const std::string& tag, const bool isAddition, const std::string& condition) : name_(tag), addTag_(isAddition), ConditionalMetadata(condition) {} +Tag::Tag(const std::string& tag, + const bool isAddition, + const std::string& condition) : + name_(tag), + addTag_(isAddition), + ConditionalMetadata(condition) {} -bool Tag::operator < (const Tag& rhs) const { +bool Tag::operator<(const Tag& rhs) const { if (addTag_ != rhs.IsAddition()) return (addTag_ && !rhs.IsAddition()); else return boost::ilexicographical_compare(GetName(), rhs.GetName()); } -bool Tag::operator == (const Tag& rhs) const { - return (addTag_ == rhs.IsAddition() && boost::iequals(GetName(), rhs.GetName())); +bool Tag::operator==(const Tag& rhs) const { + return (addTag_ == rhs.IsAddition() && + boost::iequals(GetName(), rhs.GetName())); } -bool Tag::IsAddition() const { - return addTag_; -} +bool Tag::IsAddition() const { return addTag_; } -std::string Tag::GetName() const { - return name_; -} +std::string Tag::GetName() const { return name_; } } diff --git a/src/api/metadata/yaml/file.h b/src/api/metadata/yaml/file.h index 571ce218..dc62cefa 100644 --- a/src/api/metadata/yaml/file.h +++ b/src/api/metadata/yaml/file.h @@ -48,11 +48,14 @@ struct convert { static bool decode(const Node& node, loot::File& rhs) { if (!node.IsMap() && !node.IsScalar()) - throw RepresentationException(node.Mark(), "bad conversion: 'file' object must be a map or scalar"); + throw RepresentationException( + node.Mark(), "bad conversion: 'file' object must be a map or scalar"); if (node.IsMap()) { if (!node["name"]) - throw RepresentationException(node.Mark(), "bad conversion: 'name' key missing from 'file' map object"); + throw RepresentationException( + node.Mark(), + "bad conversion: 'name' key missing from 'file' map object"); std::string name = node["name"].as(); std::string condition, display; @@ -64,29 +67,34 @@ struct convert { } else rhs = loot::File(node.as()); - // Test condition syntax. + // Test condition syntax. try { rhs.ParseCondition(); } catch (std::exception& e) { - throw RepresentationException(node.Mark(), std::string("bad conversion: invalid condition syntax: ") + e.what()); + throw RepresentationException( + node.Mark(), + std::string("bad conversion: invalid condition syntax: ") + e.what()); } return true; } }; -inline Emitter& operator << (Emitter& out, const loot::File& rhs) { - if (!rhs.IsConditional() && (rhs.GetDisplayName().empty() || rhs.GetDisplayName() == rhs.GetName())) +inline Emitter& operator<<(Emitter& out, const loot::File& rhs) { + if (!rhs.IsConditional() && + (rhs.GetDisplayName().empty() || rhs.GetDisplayName() == rhs.GetName())) out << YAML::SingleQuoted << rhs.GetName(); else { - out << BeginMap - << Key << "name" << Value << YAML::SingleQuoted << rhs.GetName(); + out << BeginMap << Key << "name" << Value << YAML::SingleQuoted + << rhs.GetName(); if (rhs.IsConditional()) - out << Key << "condition" << Value << YAML::SingleQuoted << rhs.GetCondition(); + out << Key << "condition" << Value << YAML::SingleQuoted + << rhs.GetCondition(); if (rhs.GetDisplayName() != rhs.GetName()) - out << Key << "display" << Value << YAML::SingleQuoted << rhs.GetDisplayName(); + out << Key << "display" << Value << YAML::SingleQuoted + << rhs.GetDisplayName(); out << EndMap; } diff --git a/src/api/metadata/yaml/location.h b/src/api/metadata/yaml/location.h index 5e27a7ce..0f499ba0 100644 --- a/src/api/metadata/yaml/location.h +++ b/src/api/metadata/yaml/location.h @@ -46,14 +46,18 @@ struct convert { static bool decode(const Node& node, loot::Location& rhs) { if (!node.IsMap() && !node.IsScalar()) - throw RepresentationException(node.Mark(), "bad conversion: 'location' object must be a map or scalar"); + throw RepresentationException( + node.Mark(), + "bad conversion: 'location' object must be a map or scalar"); std::string url; std::string name; if (node.IsMap()) { if (!node["link"]) - throw RepresentationException(node.Mark(), "bad conversion: 'link' key missing from 'location' map object"); + throw RepresentationException( + node.Mark(), + "bad conversion: 'link' key missing from 'location' map object"); url = node["link"].as(); if (node["name"]) @@ -67,14 +71,13 @@ struct convert { } }; -inline Emitter& operator << (Emitter& out, const loot::Location& rhs) { +inline Emitter& operator<<(Emitter& out, const loot::Location& rhs) { if (rhs.GetName().empty()) out << YAML::SingleQuoted << rhs.GetURL(); else { - out << BeginMap - << Key << "link" << Value << YAML::SingleQuoted << rhs.GetURL() - << Key << "name" << Value << YAML::SingleQuoted << rhs.GetName() - << EndMap; + out << BeginMap << Key << "link" << Value << YAML::SingleQuoted + << rhs.GetURL() << Key << "name" << Value << YAML::SingleQuoted + << rhs.GetName() << EndMap; } return out; } diff --git a/src/api/metadata/yaml/message.h b/src/api/metadata/yaml/message.h index 05cb3727..ba618b38 100644 --- a/src/api/metadata/yaml/message.h +++ b/src/api/metadata/yaml/message.h @@ -27,9 +27,9 @@ #include #include +#include #include #include -#include #include "loot/metadata/message.h" @@ -55,11 +55,16 @@ struct convert { static bool decode(const Node& node, loot::Message& rhs) { if (!node.IsMap()) - throw RepresentationException(node.Mark(), "bad conversion: 'message' object must be a map"); + throw RepresentationException( + node.Mark(), "bad conversion: 'message' object must be a map"); if (!node["type"]) - throw RepresentationException(node.Mark(), "bad conversion: 'type' key missing from 'message' object"); + throw RepresentationException( + node.Mark(), + "bad conversion: 'type' key missing from 'message' object"); if (!node["content"]) - throw RepresentationException(node.Mark(), "bad conversion: 'content' key missing from 'message' object"); + throw RepresentationException( + node.Mark(), + "bad conversion: 'content' key missing from 'message' object"); std::string type; type = node["type"].as(); @@ -72,25 +77,30 @@ struct convert { std::vector content; if (node["content"].IsSequence()) - content = node["content"].as< std::vector >(); + content = node["content"].as>(); else { - content.push_back(loot::MessageContent(node["content"].as())); + content.push_back( + loot::MessageContent(node["content"].as())); } - //Check now that at least one item in content is English if there are multiple items. + // Check now that at least one item in content is English if there are + // multiple items. if (content.size() > 1) { bool found = false; - for (const auto &mc : content) { + for (const auto& mc : content) { if (mc.GetLanguage() == loot::MessageContent::defaultLanguage) found = true; } if (!found) - throw RepresentationException(node.Mark(), "bad conversion: multilingual messages must contain an English content string"); + throw RepresentationException(node.Mark(), + "bad conversion: multilingual messages " + "must contain an English content string"); } // Make any substitutions at this point. if (node["subs"]) { - std::vector subs = node["subs"].as>(); + std::vector subs = + node["subs"].as>(); for (auto& mc : content) { boost::format f(mc.GetText()); @@ -101,7 +111,10 @@ struct convert { try { mc = loot::MessageContent(f.str(), mc.GetLanguage()); } catch (boost::io::format_error& e) { - throw RepresentationException(node.Mark(), std::string("bad conversion: content substitution error: ") + e.what()); + throw RepresentationException( + node.Mark(), + std::string("bad conversion: content substitution error: ") + + e.what()); } } } @@ -116,14 +129,16 @@ struct convert { try { rhs.ParseCondition(); } catch (std::exception& e) { - throw RepresentationException(node.Mark(), std::string("bad conversion: invalid condition syntax: ") + e.what()); + throw RepresentationException( + node.Mark(), + std::string("bad conversion: invalid condition syntax: ") + e.what()); } return true; } }; -inline Emitter& operator << (Emitter& out, const loot::Message& rhs) { +inline Emitter& operator<<(Emitter& out, const loot::Message& rhs) { out << BeginMap; if (rhs.GetType() == loot::MessageType::say) @@ -134,12 +149,14 @@ inline Emitter& operator << (Emitter& out, const loot::Message& rhs) { out << Key << "type" << Value << "error"; if (rhs.GetContent().size() == 1) - out << Key << "content" << Value << YAML::SingleQuoted << rhs.GetContent().front().GetText(); + out << Key << "content" << Value << YAML::SingleQuoted + << rhs.GetContent().front().GetText(); else out << Key << "content" << Value << rhs.GetContent(); if (rhs.IsConditional()) - out << Key << "condition" << Value << YAML::SingleQuoted << rhs.GetCondition(); + out << Key << "condition" << Value << YAML::SingleQuoted + << rhs.GetCondition(); out << EndMap; diff --git a/src/api/metadata/yaml/message_content.h b/src/api/metadata/yaml/message_content.h index 31a93b25..d7e9815d 100644 --- a/src/api/metadata/yaml/message_content.h +++ b/src/api/metadata/yaml/message_content.h @@ -43,11 +43,17 @@ struct convert { static bool decode(const Node& node, loot::MessageContent& rhs) { if (!node.IsMap()) - throw RepresentationException(node.Mark(), "bad conversion: 'message content' object must be a map"); + throw RepresentationException( + node.Mark(), + "bad conversion: 'message content' object must be a map"); if (!node["text"]) - throw RepresentationException(node.Mark(), "bad conversion: 'text' key missing from 'message content' object"); + throw RepresentationException( + node.Mark(), + "bad conversion: 'text' key missing from 'message content' object"); if (!node["lang"]) - throw RepresentationException(node.Mark(), "bad conversion: 'lang' key missing from 'message content' object"); + throw RepresentationException( + node.Mark(), + "bad conversion: 'lang' key missing from 'message content' object"); std::string text = node["text"].as(); std::string lang = node["lang"].as(); @@ -58,7 +64,7 @@ struct convert { } }; -inline Emitter& operator << (Emitter& out, const loot::MessageContent& rhs) { +inline Emitter& operator<<(Emitter& out, const loot::MessageContent& rhs) { out << BeginMap; out << Key << "lang" << Value << rhs.GetLanguage(); diff --git a/src/api/metadata/yaml/plugin_cleaning_data.h b/src/api/metadata/yaml/plugin_cleaning_data.h index 797b399c..f461ea65 100644 --- a/src/api/metadata/yaml/plugin_cleaning_data.h +++ b/src/api/metadata/yaml/plugin_cleaning_data.h @@ -53,11 +53,16 @@ struct convert { static bool decode(const Node& node, loot::PluginCleaningData& rhs) { if (!node.IsMap()) - throw RepresentationException(node.Mark(), "bad conversion: 'cleaning data' object must be a map"); + throw RepresentationException( + node.Mark(), "bad conversion: 'cleaning data' object must be a map"); if (!node["crc"]) - throw RepresentationException(node.Mark(), "bad conversion: 'crc' key missing from 'cleaning data' object"); + throw RepresentationException( + node.Mark(), + "bad conversion: 'crc' key missing from 'cleaning data' object"); if (!node["util"]) - throw RepresentationException(node.Mark(), "bad conversion: 'util' key missing from 'cleaning data' object"); + throw RepresentationException( + node.Mark(), + "bad conversion: 'util' key missing from 'cleaning data' object"); uint32_t crc = node["crc"].as(); int itm = 0, ref = 0, nav = 0; @@ -80,15 +85,18 @@ struct convert { } } - //Check now that at least one item in info is English if there are multiple items. + // Check now that at least one item in info is English if there are multiple + // items. if (info.size() > 1) { bool found = false; - for (const auto &mc : info) { + for (const auto& mc : info) { if (mc.GetLanguage() == loot::MessageContent::defaultLanguage) found = true; } if (!found) - throw RepresentationException(node.Mark(), "bad conversion: multilingual messages must contain an English info string"); + throw RepresentationException(node.Mark(), + "bad conversion: multilingual messages " + "must contain an English info string"); } rhs = loot::PluginCleaningData(crc, utility, info, itm, ref, nav); @@ -97,14 +105,14 @@ struct convert { } }; -inline Emitter& operator << (Emitter& out, const loot::PluginCleaningData& rhs) { - out << BeginMap - << Key << "crc" << Value << Hex << rhs.GetCRC() << Dec - << Key << "util" << Value << YAML::SingleQuoted << rhs.GetCleaningUtility(); +inline Emitter& operator<<(Emitter& out, const loot::PluginCleaningData& rhs) { + out << BeginMap << Key << "crc" << Value << Hex << rhs.GetCRC() << Dec << Key + << "util" << Value << YAML::SingleQuoted << rhs.GetCleaningUtility(); if (!rhs.GetInfo().empty()) { if (rhs.GetInfo().size() == 1) - out << Key << "info" << Value << YAML::SingleQuoted << rhs.GetInfo().front().GetText(); + out << Key << "info" << Value << YAML::SingleQuoted + << rhs.GetInfo().front().GetText(); else out << Key << "info" << Value << rhs.GetInfo(); } diff --git a/src/api/metadata/yaml/plugin_metadata.h b/src/api/metadata/yaml/plugin_metadata.h index a9723b9d..8848286e 100644 --- a/src/api/metadata/yaml/plugin_metadata.h +++ b/src/api/metadata/yaml/plugin_metadata.h @@ -37,8 +37,8 @@ #include "api/metadata/yaml/file.h" #include "api/metadata/yaml/location.h" -#include "api/metadata/yaml/message_content.h" #include "api/metadata/yaml/message.h" +#include "api/metadata/yaml/message_content.h" #include "api/metadata/yaml/plugin_cleaning_data.h" #include "api/metadata/yaml/set.h" #include "api/metadata/yaml/tag.h" @@ -81,9 +81,13 @@ struct convert { static bool decode(const Node& node, loot::PluginMetadata& rhs) { if (!node.IsMap()) - throw RepresentationException(node.Mark(), "bad conversion: 'plugin metadata' object must be a map"); + throw RepresentationException( + node.Mark(), + "bad conversion: 'plugin metadata' object must be a map"); if (!node["name"]) - throw RepresentationException(node.Mark(), "bad conversion: 'name' key missing from 'plugin metadata' object"); + throw RepresentationException( + node.Mark(), + "bad conversion: 'name' key missing from 'plugin metadata' object"); rhs = loot::PluginMetadata(node["name"].as()); @@ -92,7 +96,10 @@ struct convert { try { std::regex(rhs.GetName(), std::regex::ECMAScript | std::regex::icase); } catch (std::regex_error& e) { - throw RepresentationException(node.Mark(), std::string("bad conversion: invalid regex in 'name' key: ") + e.what()); + throw RepresentationException( + node.Mark(), + std::string("bad conversion: invalid regex in 'name' key: ") + + e.what()); } } @@ -121,15 +128,23 @@ struct convert { rhs.SetTags(node["tag"].as>()); if (node["dirty"]) { if (rhs.IsRegexPlugin()) - throw RepresentationException(node.Mark(), "bad conversion: 'dirty' key must not be present in a regex 'plugin metadata' object"); + throw RepresentationException(node.Mark(), + "bad conversion: 'dirty' key must not be " + "present in a regex 'plugin metadata' " + "object"); else - rhs.SetDirtyInfo(node["dirty"].as>()); + rhs.SetDirtyInfo( + node["dirty"].as>()); } if (node["clean"]) { if (rhs.IsRegexPlugin()) - throw RepresentationException(node.Mark(), "bad conversion: 'clean' key must not be present in a regex 'plugin metadata' object"); + throw RepresentationException(node.Mark(), + "bad conversion: 'clean' key must not be " + "present in a regex 'plugin metadata' " + "object"); else - rhs.SetCleanInfo(node["clean"].as>()); + rhs.SetCleanInfo( + node["clean"].as>()); } if (node["url"]) rhs.SetLocations(node["url"].as>()); @@ -138,10 +153,10 @@ struct convert { } }; -inline Emitter& operator << (Emitter& out, const loot::PluginMetadata& rhs) { +inline Emitter& operator<<(Emitter& out, const loot::PluginMetadata& rhs) { if (!rhs.HasNameOnly()) { - out << BeginMap - << Key << "name" << Value << YAML::SingleQuoted << rhs.GetName(); + out << BeginMap << Key << "name" << Value << YAML::SingleQuoted + << rhs.GetName(); if (!rhs.IsEnabled()) out << Key << "enabled" << Value << rhs.IsEnabled(); @@ -151,7 +166,8 @@ inline Emitter& operator << (Emitter& out, const loot::PluginMetadata& rhs) { } if (rhs.GetGlobalPriority().IsExplicit()) { - out << Key << "global_priority" << Value << rhs.GetGlobalPriority().GetValue(); + out << Key << "global_priority" << Value + << rhs.GetGlobalPriority().GetValue(); } if (!rhs.GetLoadAfterFiles().empty()) diff --git a/src/api/metadata/yaml/set.h b/src/api/metadata/yaml/set.h index e8d7ad25..6c68d284 100644 --- a/src/api/metadata/yaml/set.h +++ b/src/api/metadata/yaml/set.h @@ -35,7 +35,7 @@ template struct convert> { static Node encode(const std::set& rhs) { Node node; - for (const auto &element : rhs) { + for (const auto& element : rhs) { node.push_back(element); } return node; @@ -43,21 +43,23 @@ struct convert> { static bool decode(const Node& node, std::set& rhs) { if (!node.IsSequence()) - throw RepresentationException(node.Mark(), "bad conversion: set must be a sequence of elements"); + throw RepresentationException( + node.Mark(), "bad conversion: set must be a sequence of elements"); rhs.clear(); - for (const auto &element : node) { + for (const auto& element : node) { if (!rhs.insert(element.template as()).second) - throw RepresentationException(node.Mark(), "bad conversion: set elements must be unique"); + throw RepresentationException( + node.Mark(), "bad conversion: set elements must be unique"); } return true; } }; template -Emitter& operator << (Emitter& out, const std::set& rhs) { +Emitter& operator<<(Emitter& out, const std::set& rhs) { out << BeginSeq; - for (const auto &element : rhs) { + for (const auto& element : rhs) { out << element; } out << EndSeq; @@ -69,7 +71,7 @@ template struct convert> { static Node encode(const std::unordered_set& rhs) { Node node; - for (const auto &element : rhs) { + for (const auto& element : rhs) { node.push_back(element); } return node; @@ -77,21 +79,25 @@ struct convert> { static bool decode(const Node& node, std::unordered_set& rhs) { if (!node.IsSequence()) - throw RepresentationException(node.Mark(), "bad conversion: unordered set must be a sequence of elements"); + throw RepresentationException( + node.Mark(), + "bad conversion: unordered set must be a sequence of elements"); rhs.clear(); - for (const auto &element : node) { + for (const auto& element : node) { if (!rhs.insert(element.template as()).second) - throw RepresentationException(node.Mark(), "bad conversion: unordered set elements must be unique"); + throw RepresentationException( + node.Mark(), + "bad conversion: unordered set elements must be unique"); } return true; } }; template -Emitter& operator << (Emitter& out, const std::unordered_set& rhs) { +Emitter& operator<<(Emitter& out, const std::unordered_set& rhs) { out << BeginSeq; - for (const auto &element : rhs) { + for (const auto& element : rhs) { out << element; } out << EndSeq; diff --git a/src/api/metadata/yaml/tag.h b/src/api/metadata/yaml/tag.h index aa7d36d6..ed7c55d9 100644 --- a/src/api/metadata/yaml/tag.h +++ b/src/api/metadata/yaml/tag.h @@ -46,12 +46,15 @@ struct convert { static bool decode(const Node& node, loot::Tag& rhs) { if (!node.IsMap() && !node.IsScalar()) - throw RepresentationException(node.Mark(), "bad conversion: 'tag' object must be a map or scalar"); + throw RepresentationException( + node.Mark(), "bad conversion: 'tag' object must be a map or scalar"); std::string condition, tag; if (node.IsMap()) { if (!node["name"]) - throw RepresentationException(node.Mark(), "bad conversion: 'name' key missing from 'tag' map object"); + throw RepresentationException( + node.Mark(), + "bad conversion: 'name' key missing from 'tag' map object"); tag = node["name"].as(); if (node["condition"]) @@ -64,18 +67,20 @@ struct convert { else rhs = loot::Tag(tag, true, condition); - // Test condition syntax. + // Test condition syntax. try { rhs.ParseCondition(); } catch (std::exception& e) { - throw RepresentationException(node.Mark(), std::string("bad conversion: invalid condition syntax: ") + e.what()); + throw RepresentationException( + node.Mark(), + std::string("bad conversion: invalid condition syntax: ") + e.what()); } return true; } }; -inline Emitter& operator << (Emitter& out, const loot::Tag& rhs) { +inline Emitter& operator<<(Emitter& out, const loot::Tag& rhs) { if (!rhs.IsConditional()) { if (rhs.IsAddition()) out << rhs.GetName(); @@ -88,8 +93,8 @@ inline Emitter& operator << (Emitter& out, const loot::Tag& rhs) { else out << Key << "name" << Value << ('-' + rhs.GetName()); - out << Key << "condition" << Value << YAML::SingleQuoted << rhs.GetCondition() - << EndMap; + out << Key << "condition" << Value << YAML::SingleQuoted + << rhs.GetCondition() << EndMap; } return out; diff --git a/src/api/metadata_list.cpp b/src/api/metadata_list.cpp index 322213b5..87fb1e60 100644 --- a/src/api/metadata_list.cpp +++ b/src/api/metadata_list.cpp @@ -27,11 +27,11 @@ #include #include -#include "loot/exception/file_access_error.h" #include "api/game/game.h" #include "api/helpers/logging.h" #include "api/metadata/condition_evaluator.h" #include "api/metadata/yaml/plugin_metadata.h" +#include "loot/exception/file_access_error.h" namespace loot { void MetadataList::Load(const boost::filesystem::path& filepath) { @@ -50,7 +50,8 @@ void MetadataList::Load(const boost::filesystem::path& filepath) { in.close(); if (!metadataList.IsMap()) - throw FileAccessError("The root of the metadata file " + filepath.string() + " is not a YAML map."); + throw FileAccessError("The root of the metadata file " + filepath.string() + + " is not a YAML map."); if (metadataList["plugins"]) { for (const auto& node : metadataList["plugins"]) { @@ -58,7 +59,8 @@ void MetadataList::Load(const boost::filesystem::path& filepath) { if (plugin.IsRegexPlugin()) regexPlugins_.push_back(plugin); else if (!plugins_.insert(plugin).second) - throw FileAccessError("More than one entry exists for \"" + plugin.GetName() + "\""); + throw FileAccessError("More than one entry exists for \"" + + plugin.GetName() + "\""); } } if (metadataList["globals"]) @@ -115,18 +117,15 @@ void MetadataList::Clear() { std::list MetadataList::Plugins() const { std::list pluginList(plugins_.begin(), plugins_.end()); - pluginList.insert(pluginList.end(), regexPlugins_.begin(), regexPlugins_.end()); + pluginList.insert( + pluginList.end(), regexPlugins_.begin(), regexPlugins_.end()); return pluginList; } -std::vector MetadataList::Messages() const { - return messages_; -} +std::vector MetadataList::Messages() const { return messages_; } -std::set MetadataList::BashTags() const { - return bashTags_; -} +std::set MetadataList::BashTags() const { return bashTags_; } // Merges multiple matching regex entries if any are found. PluginMetadata MetadataList::FindPlugin(const PluginMetadata& plugin) const { @@ -137,7 +136,7 @@ PluginMetadata MetadataList::FindPlugin(const PluginMetadata& plugin) const { if (it != plugins_.end()) match = *it; -// Now we want to also match possibly multiple regex entries. + // Now we want to also match possibly multiple regex entries. auto regIt = find(regexPlugins_.begin(), regexPlugins_.end(), plugin); while (regIt != regexPlugins_.end()) { match.MergeMetadata(*regIt); @@ -153,7 +152,9 @@ void MetadataList::AddPlugin(const PluginMetadata& plugin) { regexPlugins_.push_back(plugin); else { if (!plugins_.insert(plugin).second) - throw std::invalid_argument("Cannot add \"" + plugin.GetName() + "\" to the metadata list as another entry already exists."); + throw std::invalid_argument( + "Cannot add \"" + plugin.GetName() + + "\" to the metadata list as another entry already exists."); } } @@ -172,7 +173,8 @@ void MetadataList::AppendMessage(const Message& message) { messages_.push_back(message); } -void MetadataList::EvalAllConditions(const ConditionEvaluator& conditionEvaluator) { +void MetadataList::EvalAllConditions( + const ConditionEvaluator& conditionEvaluator) { if (unevaluatedPlugins_.empty()) unevaluatedPlugins_.swap(plugins_); else diff --git a/src/api/plugin/plugin.cpp b/src/api/plugin/plugin.cpp index 01817f86..d244cc8f 100644 --- a/src/api/plugin/plugin.cpp +++ b/src/api/plugin/plugin.cpp @@ -46,27 +46,29 @@ Plugin::Plugin(const GameType gameType, std::shared_ptr loadOrderHandler, const std::string& name, const bool headerOnly) : - name_(name), - esPlugin(nullptr), - isEmpty_(true), - isActive_(false), - loadsArchive_(false), - crc_(0), - numOverrideRecords_(0) { + name_(name), + esPlugin(nullptr), + isEmpty_(true), + isActive_(false), + loadsArchive_(false), + crc_(0), + numOverrideRecords_(0) { auto logger = getLogger(); try { boost::filesystem::path filepath = dataPath / name_; // In case the plugin is ghosted. - if (!boost::filesystem::exists(filepath) && boost::filesystem::exists(filepath.string() + ".ghost")) + if (!boost::filesystem::exists(filepath) && + boost::filesystem::exists(filepath.string() + ".ghost")) filepath += ".ghost"; Load(filepath, gameType, headerOnly); auto ret = esp_plugin_is_empty(esPlugin.get(), &isEmpty_); if (ret != ESP_OK) { - throw FileAccessError(name + " : Libespm error code: " + std::to_string(ret)); + throw FileAccessError(name + + " : Libespm error code: " + std::to_string(ret)); } if (!headerOnly) { @@ -78,15 +80,18 @@ Plugin::Plugin(const GameType gameType, if (logger) { logger->trace("{}: Counting override FormIDs.", name_); } - ret = esp_plugin_count_override_records(esPlugin.get(), &numOverrideRecords_); + ret = esp_plugin_count_override_records(esPlugin.get(), + &numOverrideRecords_); if (ret != ESP_OK) { - throw FileAccessError(name + " : Libespm error code: " + std::to_string(ret)); + throw FileAccessError(name + + " : Libespm error code: " + std::to_string(ret)); } } - //Also read Bash Tags applied and version string in description. + // Also read Bash Tags applied and version string in description. if (logger) { - logger->trace("{}: Attempting to extract Bash Tags from the description.", name_); + logger->trace("{}: Attempting to extract Bash Tags from the description.", + name_); } string text = GetDescription(); @@ -101,7 +106,7 @@ Plugin::Plugin(const GameType gameType, std::vector bashTags; boost::split(bashTags, text, [](char c) { return c == ','; }); - for (auto &tag : bashTags) { + for (auto& tag : bashTags) { boost::trim(tag); tags_.insert(Tag(tag)); @@ -117,9 +122,12 @@ Plugin::Plugin(const GameType gameType, loadsArchive_ = LoadsArchive(name_, gameType, dataPath); } catch (std::exception& e) { if (logger) { - logger->error("Cannot read plugin file \"{}\". Details: {}", name_, e.what()); + logger->error( + "Cannot read plugin file \"{}\". Details: {}", name_, e.what()); } - throw FileAccessError((boost::format("Cannot read \"%1%\". Details: %2%") % name % e.what()).str()); + throw FileAccessError( + (boost::format("Cannot read \"%1%\". Details: %2%") % name % e.what()) + .str()); } if (logger) { @@ -127,9 +135,7 @@ Plugin::Plugin(const GameType gameType, } } -std::string Plugin::GetName() const { - return name_; -} +std::string Plugin::GetName() const { return name_; } std::string Plugin::GetLowercasedName() const { return boost::locale::to_lower(name_); @@ -140,11 +146,12 @@ std::string Plugin::GetVersion() const { } std::vector Plugin::GetMasters() const { - char ** masters; + char** masters; uint8_t numMasters; auto ret = esp_plugin_masters(esPlugin.get(), &masters, &numMasters); if (ret != ESP_OK) { - throw FileAccessError(name_ + " : Libespm error code: " + std::to_string(ret)); + throw FileAccessError(name_ + + " : Libespm error code: " + std::to_string(ret)); } std::vector mastersVec(masters, masters + numMasters); @@ -153,19 +160,16 @@ std::vector Plugin::GetMasters() const { return mastersVec; } -std::set Plugin::GetBashTags() const { - return tags_; -} +std::set Plugin::GetBashTags() const { return tags_; } -uint32_t Plugin::GetCRC() const { - return crc_; -} +uint32_t Plugin::GetCRC() const { return crc_; } bool Plugin::IsMaster() const { bool isMaster; auto ret = esp_plugin_is_master(esPlugin.get(), &isMaster); if (ret != ESP_OK) { - throw FileAccessError(name_ + " : Libespm error code: " + std::to_string(ret)); + throw FileAccessError(name_ + + " : Libespm error code: " + std::to_string(ret)); } return isMaster; @@ -175,52 +179,53 @@ bool Plugin::IsLightMaster() const { bool isLightMaster; auto ret = esp_plugin_is_light_master(esPlugin.get(), &isLightMaster); if (ret != ESP_OK) { - throw FileAccessError(name_ + " : Libespm error code: " + std::to_string(ret)); + throw FileAccessError(name_ + + " : Libespm error code: " + std::to_string(ret)); } return isLightMaster; } -bool Plugin::IsEmpty() const { - return isEmpty_; -} +bool Plugin::IsEmpty() const { return isEmpty_; } -bool Plugin::LoadsArchive() const { - return loadsArchive_; -} +bool Plugin::LoadsArchive() const { return loadsArchive_; } bool Plugin::DoFormIDsOverlap(const PluginInterface& plugin) const { try { auto otherPlugin = dynamic_cast(plugin); bool doPluginsOverlap; - auto ret = esp_plugin_do_records_overlap(esPlugin.get(), otherPlugin.esPlugin.get(), &doPluginsOverlap); + auto ret = esp_plugin_do_records_overlap( + esPlugin.get(), otherPlugin.esPlugin.get(), &doPluginsOverlap); if (ret != ESP_OK) { - throw FileAccessError(name_ + " : Libespm error code: " + std::to_string(ret)); + throw FileAccessError(name_ + + " : Libespm error code: " + std::to_string(ret)); } return doPluginsOverlap; } catch (std::bad_cast&) { auto logger = getLogger(); if (logger) { - logger->error("Tried to check if FormIDs overlapped with a non-Plugin implementation of PluginInterface."); + logger->error( + "Tried to check if FormIDs overlapped with a non-Plugin " + "implementation of PluginInterface."); } } return false; } -size_t Plugin::NumOverrideFormIDs() const { - return numOverrideRecords_; -} +size_t Plugin::NumOverrideFormIDs() const { return numOverrideRecords_; } -bool Plugin::IsValid(const std::string& filename, const GameType gameType, const boost::filesystem::path& dataPath) { +bool Plugin::IsValid(const std::string& filename, + const GameType gameType, + const boost::filesystem::path& dataPath) { auto logger = getLogger(); if (logger) { logger->trace("Checking to see if \"{}\" is a valid plugin.", filename); } - //If the filename passed ends in '.ghost', that should be trimmed. + // If the filename passed ends in '.ghost', that should be trimmed. std::string name; if (boost::iends_with(filename, ".ghost")) name = filename.substr(0, filename.length() - 6); @@ -233,7 +238,8 @@ bool Plugin::IsValid(const std::string& filename, const GameType gameType, const bool isValid; auto path = dataPath / filename; - int ret = esp_plugin_is_valid(GetEspluginGameId(gameType), path.string().c_str(), true, &isValid); + int ret = esp_plugin_is_valid( + GetEspluginGameId(gameType), path.string().c_str(), true, &isValid); if (ret != ESP_OK || !isValid) { if (logger) { @@ -241,11 +247,12 @@ bool Plugin::IsValid(const std::string& filename, const GameType gameType, const } } - return (ret == ESP_OK && isValid) - || Plugin::IsValid(filename + ".ghost", gameType, dataPath); + return (ret == ESP_OK && isValid) || + Plugin::IsValid(filename + ".ghost", gameType, dataPath); } -uintmax_t Plugin::GetFileSize(const std::string & filename, const boost::filesystem::path& dataPath) { +uintmax_t Plugin::GetFileSize(const std::string& filename, + const boost::filesystem::path& dataPath) { boost::filesystem::path realPath = dataPath / filename; if (!boost::filesystem::exists(realPath)) realPath += ".ghost"; @@ -253,34 +260,40 @@ uintmax_t Plugin::GetFileSize(const std::string & filename, const boost::filesys return boost::filesystem::file_size(realPath); } -bool Plugin::operator < (const Plugin & rhs) const { - return boost::ilexicographical_compare(name_, rhs.name_);; +bool Plugin::operator<(const Plugin& rhs) const { + return boost::ilexicographical_compare(name_, rhs.name_); + ; } -bool Plugin::IsActive() const { - return isActive_; -} +bool Plugin::IsActive() const { return isActive_; } -void Plugin::Load(const boost::filesystem::path& path, GameType gameType, bool headerOnly) { - ::Plugin * plugin; - int ret = esp_plugin_new(&plugin, GetEspluginGameId(gameType), path.string().c_str()); +void Plugin::Load(const boost::filesystem::path& path, + GameType gameType, + bool headerOnly) { + ::Plugin* plugin; + int ret = esp_plugin_new( + &plugin, GetEspluginGameId(gameType), path.string().c_str()); if (ret != ESP_OK) { - throw FileAccessError(path.string() + " : Libespm error code: " + std::to_string(ret)); + throw FileAccessError(path.string() + + " : Libespm error code: " + std::to_string(ret)); } - esPlugin = std::shared_ptr::type>(plugin, esp_plugin_free); + esPlugin = std::shared_ptr::type>( + plugin, esp_plugin_free); ret = esp_plugin_parse(esPlugin.get(), headerOnly); if (ret != ESP_OK) { - throw FileAccessError(path.string() + " : Libespm error code: " + std::to_string(ret)); + throw FileAccessError(path.string() + + " : Libespm error code: " + std::to_string(ret)); } } std::string Plugin::GetDescription() const { - char * description; + char* description; auto ret = esp_plugin_description(esPlugin.get(), &description); if (ret != ESP_OK) { - throw FileAccessError(name_ + " : Libespm error code: " + std::to_string(ret)); + throw FileAccessError(name_ + + " : Libespm error code: " + std::to_string(ret)); } if (description == nullptr) { return ""; @@ -299,18 +312,27 @@ std::string Plugin::GetArchiveFileExtension(const GameType gameType) { return ".bsa"; } -bool Plugin::LoadsArchive(const std::string& pluginName, const GameType gameType, const boost::filesystem::path& dataPath) { +bool Plugin::LoadsArchive(const std::string& pluginName, + const GameType gameType, + const boost::filesystem::path& dataPath) { // Get whether the plugin loads an archive (BSA/BA2) or not. const string archiveExtension = GetArchiveFileExtension(gameType); if (gameType == GameType::tes5) { // Skyrim plugins only load BSAs that exactly match their basename. - return boost::filesystem::exists(dataPath / (pluginName.substr(0, pluginName.length() - 4) + archiveExtension)); - } else if (gameType != GameType::tes4 || boost::iends_with(pluginName, ".esp")) { - //Oblivion .esp files and FO3, FNV, FO4 plugins can load archives which begin with the plugin basename. + return boost::filesystem::exists( + dataPath / + (pluginName.substr(0, pluginName.length() - 4) + archiveExtension)); + } else if (gameType != GameType::tes4 || + boost::iends_with(pluginName, ".esp")) { + // Oblivion .esp files and FO3, FNV, FO4 plugins can load archives which + // begin with the plugin basename. string basename = pluginName.substr(0, pluginName.length() - 4); - for (boost::filesystem::directory_iterator it(dataPath); it != boost::filesystem::directory_iterator(); ++it) { - if (boost::iequals(it->path().extension().string(), archiveExtension) && boost::istarts_with(it->path().filename().string(), basename)) { + for (boost::filesystem::directory_iterator it(dataPath); + it != boost::filesystem::directory_iterator(); + ++it) { + if (boost::iequals(it->path().extension().string(), archiveExtension) && + boost::istarts_with(it->path().filename().string(), basename)) { return true; } } @@ -321,25 +343,27 @@ bool Plugin::LoadsArchive(const std::string& pluginName, const GameType gameType unsigned int Plugin::GetEspluginGameId(GameType gameType) { switch (gameType) { - case GameType::tes4: - return ESP_GAME_OBLIVION; - case GameType::tes5: - return ESP_GAME_SKYRIM; - case GameType::tes5se: - return ESP_GAME_SKYRIMSE; - case GameType::fo3: - return ESP_GAME_FALLOUT3; - case GameType::fonv: - return ESP_GAME_FALLOUTNV; - default: - return ESP_GAME_FALLOUT4; + case GameType::tes4: + return ESP_GAME_OBLIVION; + case GameType::tes5: + return ESP_GAME_SKYRIM; + case GameType::tes5se: + return ESP_GAME_SKYRIMSE; + case GameType::fo3: + return ESP_GAME_FALLOUT3; + case GameType::fonv: + return ESP_GAME_FALLOUTNV; + default: + return ESP_GAME_FALLOUT4; } } bool hasPluginFileExtension(const std::string& filename, GameType gameType) { - bool espOrEsm = boost::iends_with(filename, ".esp") || boost::iends_with(filename, ".esm"); - bool lightMaster = (gameType == GameType::fo4 || gameType == GameType::tes5se) - && boost::iends_with(filename, ".esl"); + bool espOrEsm = boost::iends_with(filename, ".esp") || + boost::iends_with(filename, ".esm"); + bool lightMaster = + (gameType == GameType::fo4 || gameType == GameType::tes5se) && + boost::iends_with(filename, ".esl"); return espOrEsm || lightMaster; } diff --git a/src/api/plugin/plugin.h b/src/api/plugin/plugin.h index be0a90ff..ff5ccec0 100644 --- a/src/api/plugin/plugin.h +++ b/src/api/plugin/plugin.h @@ -35,8 +35,8 @@ #include #include "api/game/load_order_handler.h" -#include "loot/metadata/plugin_metadata.h" #include "loot/enum/game_type.h" +#include "loot/metadata/plugin_metadata.h" #include "loot/plugin_interface.h" namespace loot { @@ -63,31 +63,40 @@ public: bool IsActive() const; - //Load ordering functions. + // Load ordering functions. size_t NumOverrideFormIDs() const; // Validity checks. - static bool IsValid(const std::string& filename, const GameType gameType, const boost::filesystem::path& dataPath); - static uintmax_t GetFileSize(const std::string& filename, const boost::filesystem::path& dataPath); + static bool IsValid(const std::string& filename, + const GameType gameType, + const boost::filesystem::path& dataPath); + static uintmax_t GetFileSize(const std::string& filename, + const boost::filesystem::path& dataPath); + + bool operator<(const Plugin& rhs) const; - bool operator < (const Plugin& rhs) const; private: - void Load(const boost::filesystem::path& path, GameType gameType, bool headerOnly); + void Load(const boost::filesystem::path& path, + GameType gameType, + bool headerOnly); std::string GetDescription() const; static std::string GetArchiveFileExtension(const GameType gameType); - static bool LoadsArchive(const std::string& pluginName, const GameType gameType, const boost::filesystem::path& dataPath); + static bool LoadsArchive(const std::string& pluginName, + const GameType gameType, + const boost::filesystem::path& dataPath); static unsigned int GetEspluginGameId(GameType gameType); - bool isEmpty_; // Does the plugin contain any records other than the TES4 header? + bool isEmpty_; // Does the plugin contain any records other than the TES4 + // header? bool isActive_; bool loadsArchive_; const std::string name_; - std::string version_; //Obtained from description field. + std::string version_; // Obtained from description field. uint32_t crc_; std::set tags_; - //Useful caches. + // Useful caches. size_t numOverrideRecords_; std::shared_ptr::type> esPlugin; diff --git a/src/api/plugin/plugin_sorter.cpp b/src/api/plugin/plugin_sorter.cpp index 5e1ab115..126ebd50 100644 --- a/src/api/plugin/plugin_sorter.cpp +++ b/src/api/plugin/plugin_sorter.cpp @@ -32,30 +32,28 @@ #include #include -#include "loot/exception/cyclic_interaction_error.h" #include "api/game/game.h" #include "api/helpers/logging.h" #include "api/metadata/condition_evaluator.h" +#include "loot/exception/cyclic_interaction_error.h" using std::list; using std::string; using std::vector; namespace loot { -PluginSortingData::PluginSortingData(const Plugin& plugin, const PluginMetadata&& metadata) - : plugin_(plugin), PluginMetadata(metadata) {} +PluginSortingData::PluginSortingData(const Plugin& plugin, + const PluginMetadata&& metadata) : + plugin_(plugin), + PluginMetadata(metadata) {} -std::string PluginSortingData::GetName() const { - return plugin_.GetName(); -} +std::string PluginSortingData::GetName() const { return plugin_.GetName(); } bool PluginSortingData::IsMaster() const { return plugin_.IsMaster() || plugin_.IsLightMaster(); } -bool PluginSortingData::LoadsArchive() const { - return plugin_.LoadsArchive(); -} +bool PluginSortingData::LoadsArchive() const { return plugin_.LoadsArchive(); } std::vector PluginSortingData::GetMasters() const { return plugin_.GetMasters(); @@ -65,7 +63,8 @@ size_t PluginSortingData::NumOverrideFormIDs() const { return plugin_.NumOverrideFormIDs(); } -bool PluginSortingData::DoFormIDsOverlap(const PluginSortingData& plugin) const { +bool PluginSortingData::DoFormIDsOverlap( + const PluginSortingData& plugin) const { return plugin_.DoFormIDsOverlap(plugin.plugin_); } @@ -85,8 +84,8 @@ public: auto it = find(begin(trail), end(trail), name); if (it != end(trail)) { - // Erase everything from this position onwards, as it doesn't - // contribute to a forward-cycle. + // Erase everything from this position onwards, as it doesn't + // contribute to a forward-cycle. trail.erase(it, end(trail)); } @@ -105,7 +104,8 @@ public: } backCycle.erase(backCycle.length() - 2); - throw CyclicInteractionError(graph[source].GetName(), graph[target].GetName(), backCycle); + throw CyclicInteractionError( + graph[source].GetName(), graph[target].GetName(), backCycle); } private: @@ -144,12 +144,12 @@ std::vector PluginSorter::Sort(Game& game) { oldLoadOrder_ = game.GetLoadOrder(); if (logger_) { logger_->info("Fetched existing load order: "); - for (const auto &plugin : oldLoadOrder_) { + for (const auto& plugin : oldLoadOrder_) { logger_->info("\t\t{}", plugin); } } - //Now add the interactions between plugins to the graph as edges. + // Now add the interactions between plugins to the graph as edges. if (logger_) { logger_->info("Adding edges to plugin graph."); logger_->debug("Adding non-overlap edges."); @@ -178,17 +178,24 @@ std::vector PluginSorter::Sort(Game& game) { } CheckForCycles(); - //Now we can sort. + // Now we can sort. if (logger_) { logger_->debug("Performing a topological sort."); } list sortedVertices; - boost::topological_sort(graph_, std::front_inserter(sortedVertices), boost::vertex_index_map(vertexIndexMap_)); + boost::topological_sort(graph_, + std::front_inserter(sortedVertices), + boost::vertex_index_map(vertexIndexMap_)); // Check that the sorted path is Hamiltonian (ie. unique). for (auto it = sortedVertices.begin(); it != sortedVertices.end(); ++it) { - if (next(it) != sortedVertices.end() && !boost::edge(*it, *next(it), graph_).second && logger_) { - logger_->error("The calculated load order is not unique. No edge exists between {} and {}.", graph_[*it].GetName(), graph_[*next(it)].GetName()); + if (next(it) != sortedVertices.end() && + !boost::edge(*it, *next(it), graph_).second && logger_) { + logger_->error( + "The calculated load order is not unique. No edge exists between {} " + "and {}.", + graph_[*it].GetName(), + graph_[*next(it)].GetName()); } } @@ -197,7 +204,7 @@ std::vector PluginSorter::Sort(Game& game) { logger_->info("Calculated order: "); } vector plugins; - for (const auto &vertex : sortedVertices) { + for (const auto& vertex : sortedVertices) { plugins.push_back(graph_[vertex].GetName()); if (logger_) { logger_->info("\t{}", plugins.back()); @@ -209,7 +216,9 @@ std::vector PluginSorter::Sort(Game& game) { void PluginSorter::AddPluginVertices(Game& game) { if (logger_) { - logger_->info("Merging masterlist, userlist into plugin list, evaluating conditions and checking for install validity."); + logger_->info( + "Merging masterlist, userlist into plugin list, evaluating conditions " + "and checking for install validity."); } // The resolution of tie-breaks in the plugin graph may be dependent @@ -233,29 +242,35 @@ void PluginSorter::AddPluginVertices(Game& game) { // Using a set of plugin names followed by finding the matching key // in the unordered map, as it's probably faster than copying the // full plugin objects then sorting them. - for (const auto &plugin : game.GetCache()->GetPlugins()) { + for (const auto& plugin : game.GetCache()->GetPlugins()) { if (logger_) { - logger_->trace("Getting and evaluating metadata for plugin {}", plugin->GetName()); + logger_->trace("Getting and evaluating metadata for plugin {}", + plugin->GetName()); } - auto metadata = game.GetDatabase()->GetPluginMetadata(plugin->GetName(), true, true); + auto metadata = + game.GetDatabase()->GetPluginMetadata(plugin->GetName(), true, true); if (logger_) { - logger_->trace("Getting and evaluating metadata for plugin \"{}\"", plugin->GetName()); + logger_->trace("Getting and evaluating metadata for plugin \"{}\"", + plugin->GetName()); } - vertex_t v = boost::add_vertex(PluginSortingData(*plugin, std::move(metadata)), graph_); + vertex_t v = boost::add_vertex( + PluginSortingData(*plugin, std::move(metadata)), graph_); } // Prebuild an index map, which std::list-based VertexList graphs don't have. vertexIndexMap_ = vertex_map_t(indexMap_); size_t i = 0; BGL_FORALL_VERTICES(v, graph_, PluginGraph) - put(vertexIndexMap_, v, i++); + put(vertexIndexMap_, v, i++); } -bool PluginSorter::GetVertexByName(const std::string& name, vertex_t& vertexOut) const { - for (const auto& vertex : boost::make_iterator_range(boost::vertices(graph_))) { +bool PluginSorter::GetVertexByName(const std::string& name, + vertex_t& vertexOut) const { + for (const auto& vertex : + boost::make_iterator_range(boost::vertices(graph_))) { if (boost::iequals(graph_[vertex].GetName(), name)) { vertexOut = vertex; return true; @@ -266,12 +281,17 @@ bool PluginSorter::GetVertexByName(const std::string& name, vertex_t& vertexOut) } void PluginSorter::CheckForCycles() const { - boost::depth_first_search(graph_, visitor(CycleDetector()).vertex_index_map(vertexIndexMap_)); + boost::depth_first_search( + graph_, visitor(CycleDetector()).vertex_index_map(vertexIndexMap_)); } -bool PluginSorter::EdgeCreatesCycle(const vertex_t& fromVertex, const vertex_t& toVertex) const { +bool PluginSorter::EdgeCreatesCycle(const vertex_t& fromVertex, + const vertex_t& toVertex) const { try { - boost::breadth_first_search(graph_, toVertex, visitor(PathDetector(fromVertex)).vertex_index_map(vertexIndexMap_)); + boost::breadth_first_search( + graph_, + toVertex, + visitor(PathDetector(fromVertex)).vertex_index_map(vertexIndexMap_)); } catch (PathFoundException&) { return true; } @@ -279,12 +299,12 @@ bool PluginSorter::EdgeCreatesCycle(const vertex_t& fromVertex, const vertex_t& } void PluginSorter::PropagatePriorities() { - /* If a plugin has a priority value > 0, that value should be - inherited by all plugins that have edges coming from that - plugin, ie. those that load after it, unless the plugin being - compared itself has a larger value. */ + /* If a plugin has a priority value > 0, that value should be + inherited by all plugins that have edges coming from that + plugin, ie. those that load after it, unless the plugin being + compared itself has a larger value. */ - // Find all vertices with priorities > 0. + // Find all vertices with priorities > 0. std::vector positivePriorityVertices; vertex_it vit, vitend; tie(vit, vitend) = boost::vertices(graph_); @@ -292,77 +312,91 @@ void PluginSorter::PropagatePriorities() { vitend, std::back_inserter(positivePriorityVertices), [&](const vertex_t& vertex) { - return graph_[vertex].GetLocalPriority() > 0 - || graph_[vertex].GetGlobalPriority() > 0; - }); + return graph_[vertex].GetLocalPriority() > 0 || + graph_[vertex].GetGlobalPriority() > 0; + }); // To reduce the number of priorities that will need setting, // sort the vertices in order of decreasing priority. std::sort(begin(positivePriorityVertices), end(positivePriorityVertices), [&](const vertex_t& lhs, const vertex_t& rhs) { - return graph_[lhs].GetLocalPriority() > graph_[rhs].GetLocalPriority() - || graph_[lhs].GetGlobalPriority() > graph_[rhs].GetGlobalPriority(); - }); + return graph_[lhs].GetLocalPriority() > + graph_[rhs].GetLocalPriority() || + graph_[lhs].GetGlobalPriority() > + graph_[rhs].GetGlobalPriority(); + }); // Create a color map. std::vector colorVec(num_vertices(graph_)); - boost::iterator_property_map colorMap(&colorVec.front(), vertexIndexMap_); + boost::iterator_property_map + colorMap(&colorVec.front(), vertexIndexMap_); // Now loop over the vertices. For each one, do a depth-first // search, setting priorities until an equal or larger value is // encountered. for (const vertex_t& vertex : positivePriorityVertices) { if (logger_) { - logger_->trace("Doing DFS for {} which has local priority {} and global priority {}", - graph_[vertex].GetName(), - graph_[vertex].GetLocalPriority().GetValue(), - graph_[vertex].GetGlobalPriority().GetValue()); + logger_->trace( + "Doing DFS for {} which has local priority {} and global priority {}", + graph_[vertex].GetName(), + graph_[vertex].GetLocalPriority().GetValue(), + graph_[vertex].GetGlobalPriority().GetValue()); } boost::dfs_visitor<> visitor; - boost::depth_first_visit(graph_, - vertex, - visitor, - colorMap, - [&](const vertex_t& currentVertex, const PluginGraph& graph) { - // depth_first_search takes a const graph, so cast it if modifying a vertex. - if (graph[currentVertex].GetLocalPriority() < graph[vertex].GetLocalPriority()) { - if (logger_) { - logger_->trace("Overriding local priority for {} from {} to {}", - graph[currentVertex].GetName(), - graph[currentVertex].GetLocalPriority().GetValue(), - graph[vertex].GetLocalPriority().GetValue()); - } - const_cast(graph)[currentVertex].SetLocalPriority(graph[vertex].GetLocalPriority()); + boost::depth_first_visit( + graph_, + vertex, + visitor, + colorMap, + [&](const vertex_t& currentVertex, const PluginGraph& graph) { + // depth_first_search takes a const graph, so cast it if modifying a + // vertex. + if (graph[currentVertex].GetLocalPriority() < + graph[vertex].GetLocalPriority()) { + if (logger_) { + logger_->trace("Overriding local priority for {} from {} to {}", + graph[currentVertex].GetName(), + graph[currentVertex].GetLocalPriority().GetValue(), + graph[vertex].GetLocalPriority().GetValue()); + } + const_cast(graph)[currentVertex].SetLocalPriority( + graph[vertex].GetLocalPriority()); - return false; - } + return false; + } - if (graph[currentVertex].GetGlobalPriority() < graph[vertex].GetGlobalPriority()) { - if (logger_) { - logger_->trace("Overriding global priority for {} from {} to {}", - graph[currentVertex].GetName(), - graph[currentVertex].GetGlobalPriority().GetValue(), - graph[vertex].GetGlobalPriority().GetValue()); - } - const_cast(graph)[currentVertex].SetGlobalPriority(graph[vertex].GetGlobalPriority()); + if (graph[currentVertex].GetGlobalPriority() < + graph[vertex].GetGlobalPriority()) { + if (logger_) { + logger_->trace( + "Overriding global priority for {} from {} to {}", + graph[currentVertex].GetName(), + graph[currentVertex].GetGlobalPriority().GetValue(), + graph[vertex].GetGlobalPriority().GetValue()); + } + const_cast(graph)[currentVertex].SetGlobalPriority( + graph[vertex].GetGlobalPriority()); - return false; - } + return false; + } - return currentVertex != vertex - && graph[currentVertex].GetLocalPriority() >= graph[vertex].GetLocalPriority() - && graph[currentVertex].GetGlobalPriority() >= graph[vertex].GetGlobalPriority(); - }); + return currentVertex != vertex && + graph[currentVertex].GetLocalPriority() >= + graph[vertex].GetLocalPriority() && + graph[currentVertex].GetGlobalPriority() >= + graph[vertex].GetGlobalPriority(); + }); } } -void PluginSorter::AddEdge(const vertex_t& fromVertex, const vertex_t& toVertex) { +void PluginSorter::AddEdge(const vertex_t& fromVertex, + const vertex_t& toVertex) { if (!boost::edge(fromVertex, toVertex, graph_).second) { if (logger_) { logger_->trace("Adding edge from \"{}\" to \"{}\".", - graph_[fromVertex].GetName(), - graph_[toVertex].GetName()); + graph_[fromVertex].GetName(), + graph_[toVertex].GetName()); } boost::add_edge(fromVertex, toVertex, graph_); @@ -370,12 +404,13 @@ void PluginSorter::AddEdge(const vertex_t& fromVertex, const vertex_t& toVertex) } void PluginSorter::AddSpecificEdges() { - //Add edges for all relationships that aren't overlaps or priority differences. + // Add edges for all relationships that aren't overlaps or priority + // differences. vertex_it vit, vitend; for (tie(vit, vitend) = boost::vertices(graph_); vit != vitend; ++vit) { if (logger_) { logger_->trace("Adding specific edges to vertex for \"{}\".", - graph_[*vit].GetName()); + graph_[*vit].GetName()); logger_->trace("Adding edges for master flag differences."); } @@ -399,7 +434,7 @@ void PluginSorter::AddSpecificEdges() { if (logger_) { logger_->trace("Adding in-edges for masters."); } - for (const auto &master : graph_[*vit].GetMasters()) { + for (const auto& master : graph_[*vit].GetMasters()) { if (GetVertexByName(master, parentVertex)) AddEdge(parentVertex, *vit); } @@ -407,7 +442,7 @@ void PluginSorter::AddSpecificEdges() { if (logger_) { logger_->trace("Adding in-edges for requirements."); } - for (const auto &file : graph_[*vit].GetRequirements()) { + for (const auto& file : graph_[*vit].GetRequirements()) { if (GetVertexByName(file.GetName(), parentVertex)) AddEdge(parentVertex, *vit); } @@ -415,7 +450,7 @@ void PluginSorter::AddSpecificEdges() { if (logger_) { logger_->trace("Adding in-edges for 'load after's."); } - for (const auto &file : graph_[*vit].GetLoadAfterFiles()) { + for (const auto& file : graph_[*vit].GetLoadAfterFiles()) { if (GetVertexByName(file.GetName(), parentVertex)) AddEdge(parentVertex, *vit); } @@ -423,36 +458,44 @@ void PluginSorter::AddSpecificEdges() { } void PluginSorter::AddPriorityEdges() { - for (const auto& vertex : boost::make_iterator_range(boost::vertices(graph_))) { + for (const auto& vertex : + boost::make_iterator_range(boost::vertices(graph_))) { if (logger_) { logger_->trace("Adding priority difference edges to vertex for \"{}\".", - graph_[vertex].GetName()); + graph_[vertex].GetName()); } // If the plugin has a global priority of zero and doesn't load // an archive and has no override records, skip it. Plugins without // override records can only conflict with plugins that override // the records they add, so any edge necessary will be added when // evaluating that plugin. - if (graph_[vertex].GetGlobalPriority().GetValue() == 0 - && graph_[vertex].NumOverrideFormIDs() == 0 - && !graph_[vertex].LoadsArchive()) { + if (graph_[vertex].GetGlobalPriority().GetValue() == 0 && + graph_[vertex].NumOverrideFormIDs() == 0 && + !graph_[vertex].LoadsArchive()) { continue; } - for (const auto& otherVertex : boost::make_iterator_range(boost::vertices(graph_))) { - // If the plugins have equal priority, or have non-global - // priorities but don't conflict, don't add a priority edge. - if ((graph_[vertex].GetLocalPriority() == graph_[otherVertex].GetLocalPriority() && graph_[vertex].GetGlobalPriority() == graph_[otherVertex].GetGlobalPriority()) - || (graph_[vertex].GetGlobalPriority().GetValue() == 0 - && graph_[otherVertex].GetGlobalPriority().GetValue() == 0 - && !graph_[vertex].DoFormIDsOverlap(graph_[otherVertex]))) { + for (const auto& otherVertex : + boost::make_iterator_range(boost::vertices(graph_))) { + // If the plugins have equal priority, or have non-global + // priorities but don't conflict, don't add a priority edge. + if ((graph_[vertex].GetLocalPriority() == + graph_[otherVertex].GetLocalPriority() && + graph_[vertex].GetGlobalPriority() == + graph_[otherVertex].GetGlobalPriority()) || + (graph_[vertex].GetGlobalPriority().GetValue() == 0 && + graph_[otherVertex].GetGlobalPriority().GetValue() == 0 && + !graph_[vertex].DoFormIDsOverlap(graph_[otherVertex]))) { continue; } vertex_t toVertex, fromVertex; - if (graph_[vertex].GetGlobalPriority() < graph_[otherVertex].GetGlobalPriority() - || (graph_[vertex].GetGlobalPriority() == graph_[otherVertex].GetGlobalPriority() - && graph_[vertex].GetLocalPriority() < graph_[otherVertex].GetLocalPriority())) { + if (graph_[vertex].GetGlobalPriority() < + graph_[otherVertex].GetGlobalPriority() || + (graph_[vertex].GetGlobalPriority() == + graph_[otherVertex].GetGlobalPriority() && + graph_[vertex].GetLocalPriority() < + graph_[otherVertex].GetLocalPriority())) { fromVertex = vertex; toVertex = otherVertex; } else { @@ -467,31 +510,37 @@ void PluginSorter::AddPriorityEdges() { } void PluginSorter::AddOverlapEdges() { - for (const auto& vertex : boost::make_iterator_range(boost::vertices(graph_))) { + for (const auto& vertex : + boost::make_iterator_range(boost::vertices(graph_))) { if (logger_) { logger_->trace("Adding overlap edges to vertex for \"{}\".", - graph_[vertex].GetName()); + graph_[vertex].GetName()); } if (graph_[vertex].NumOverrideFormIDs() == 0) { if (logger_) { - logger_->trace("Skipping vertex for \"{}\": the plugin contains no override records.", - graph_[vertex].GetName()); + logger_->trace( + "Skipping vertex for \"{}\": the plugin contains no override " + "records.", + graph_[vertex].GetName()); } continue; } - for (const auto& otherVertex : boost::make_iterator_range(boost::vertices(graph_))) { + for (const auto& otherVertex : + boost::make_iterator_range(boost::vertices(graph_))) { if (vertex == otherVertex || boost::edge(vertex, otherVertex, graph_).second || boost::edge(otherVertex, vertex, graph_).second || - graph_[vertex].NumOverrideFormIDs() == graph_[otherVertex].NumOverrideFormIDs() || + graph_[vertex].NumOverrideFormIDs() == + graph_[otherVertex].NumOverrideFormIDs() || !graph_[vertex].DoFormIDsOverlap(graph_[otherVertex])) { continue; } vertex_t toVertex, fromVertex; - if (graph_[vertex].NumOverrideFormIDs() > graph_[otherVertex].NumOverrideFormIDs()) { + if (graph_[vertex].NumOverrideFormIDs() > + graph_[otherVertex].NumOverrideFormIDs()) { fromVertex = vertex; toVertex = otherVertex; } else { @@ -505,7 +554,8 @@ void PluginSorter::AddOverlapEdges() { } } -int PluginSorter::ComparePlugins(const std::string& plugin1, const std::string& plugin2) const { +int PluginSorter::ComparePlugins(const std::string& plugin1, + const std::string& plugin2) const { auto it1 = find(begin(oldLoadOrder_), end(oldLoadOrder_), plugin1); auto it2 = find(begin(oldLoadOrder_), end(oldLoadOrder_), plugin2); @@ -514,15 +564,16 @@ int PluginSorter::ComparePlugins(const std::string& plugin1, const std::string& else if (it1 == end(oldLoadOrder_) && it2 != end(oldLoadOrder_)) return 1; else if (it1 != end(oldLoadOrder_) && it2 != end(oldLoadOrder_)) { - if (distance(begin(oldLoadOrder_), it1) < distance(begin(oldLoadOrder_), it2)) + if (distance(begin(oldLoadOrder_), it1) < + distance(begin(oldLoadOrder_), it2)) return -1; else return 1; } else { - // Neither plugin has a load order position. Need to use another - // comparison to get an ordering. + // Neither plugin has a load order position. Need to use another + // comparison to get an ordering. - // Compare plugin basenames. + // Compare plugin basenames. string name1 = boost::locale::to_lower(plugin1); name1 = name1.substr(0, name1.length() - 4); string name2 = boost::locale::to_lower(plugin2); @@ -533,8 +584,8 @@ int PluginSorter::ComparePlugins(const std::string& plugin1, const std::string& else if (name2 < name1) return 1; else { - // Could be a .esp and .esm plugin with the same basename, - // compare whole filenames. + // Could be a .esp and .esm plugin with the same basename, + // compare whole filenames. if (plugin1 < plugin2) return -1; else @@ -545,20 +596,27 @@ int PluginSorter::ComparePlugins(const std::string& plugin1, const std::string& } void PluginSorter::AddTieBreakEdges() { - // In order for the sort to be performed stably, there must be only one possible result. - // This can be enforced by adding edges between all vertices that aren't already linked. - // Use existing load order to decide the direction of these edges. - for (const auto& vertex : boost::make_iterator_range(boost::vertices(graph_))) { + // In order for the sort to be performed stably, there must be only one + // possible result. This can be enforced by adding edges between all vertices + // that aren't already linked. Use existing load order to decide the direction + // of these edges. + for (const auto& vertex : + boost::make_iterator_range(boost::vertices(graph_))) { if (logger_) { - logger_->trace("Adding tie-break edges to vertex for \"{}\"", graph_[vertex].GetName()); + logger_->trace("Adding tie-break edges to vertex for \"{}\"", + graph_[vertex].GetName()); } - for (const auto& otherVertex : boost::make_iterator_range(boost::vertices(graph_))) { - if (vertex == otherVertex || boost::edge(vertex, otherVertex, graph_).second || boost::edge(otherVertex, vertex, graph_).second) + for (const auto& otherVertex : + boost::make_iterator_range(boost::vertices(graph_))) { + if (vertex == otherVertex || + boost::edge(vertex, otherVertex, graph_).second || + boost::edge(otherVertex, vertex, graph_).second) continue; vertex_t toVertex, fromVertex; - if (ComparePlugins(graph_[vertex].GetName(), graph_[otherVertex].GetName()) < 0) { + if (ComparePlugins(graph_[vertex].GetName(), + graph_[otherVertex].GetName()) < 0) { fromVertex = vertex; toVertex = otherVertex; } else { diff --git a/src/api/plugin/plugin_sorter.h b/src/api/plugin/plugin_sorter.h index 2f5337b6..09fced0c 100644 --- a/src/api/plugin/plugin_sorter.h +++ b/src/api/plugin/plugin_sorter.h @@ -27,9 +27,9 @@ #include +#include #include #include -#include #include "api/game/game.h" #include "api/plugin/plugin.h" @@ -52,23 +52,31 @@ public: using PluginMetadata::SetGlobalPriority; using PluginMetadata::GetRequirements; using PluginMetadata::GetLoadAfterFiles; + private: const Plugin& plugin_; }; -typedef boost::adjacency_list PluginGraph; +typedef boost::adjacency_list + PluginGraph; typedef boost::graph_traits::vertex_descriptor vertex_t; -typedef boost::associative_property_map> vertex_map_t; +typedef boost::associative_property_map> + vertex_map_t; class PluginSorter { public: std::vector Sort(Game& game); + private: bool GetVertexByName(const std::string& name, vertex_t& vertex) const; void CheckForCycles() const; bool EdgeCreatesCycle(const vertex_t& u, const vertex_t& v) const; - int ComparePlugins(const std::string& plugin1, const std::string& plugin2) const; + int ComparePlugins(const std::string& plugin1, + const std::string& plugin2) const; void PropagatePriorities(); diff --git a/src/tests/api/interface/api_game_operations_test.h b/src/tests/api/interface/api_game_operations_test.h index b7aa00f2..342b22a2 100644 --- a/src/tests/api/interface/api_game_operations_test.h +++ b/src/tests/api/interface/api_game_operations_test.h @@ -34,19 +34,24 @@ namespace test { class ApiGameOperationsTest : public CommonGameTestFixture { protected: ApiGameOperationsTest() : - handle_(nullptr), - masterlistPath(localPath / "masterlist.yaml"), - noteMessage("Do not clean ITM records, they are intentional and required for the mod to function."), - warningMessage("Check you are using v2+. If not, Update. v1 has a severe bug with the Mystic Emporium disappearing."), - errorMessage("Obsolete. Remove this and install Enhanced Weather."), - generalMasterlistMessage("A general masterlist message.") {} + handle_(nullptr), + masterlistPath(localPath / "masterlist.yaml"), + noteMessage( + "Do not clean ITM records, they are intentional and required for " + "the mod to function."), + warningMessage( + "Check you are using v2+. If not, Update. v1 has a severe bug with " + "the Mystic Emporium disappearing."), + errorMessage("Obsolete. Remove this and install Enhanced Weather."), + generalMasterlistMessage("A general masterlist message.") {} virtual void SetUp() { CommonGameTestFixture::SetUp(); ASSERT_FALSE(boost::filesystem::exists(masterlistPath)); - handle_ = CreateGameHandle(GetParam(), dataPath.parent_path().string(), localPath.string()); + handle_ = CreateGameHandle( + GetParam(), dataPath.parent_path().string(), localPath.string()); } virtual void TearDown() { @@ -60,55 +65,54 @@ protected: using std::endl; boost::filesystem::ofstream masterlist(masterlistPath); - masterlist - << "bash_tags:" << endl - << " - Actors.ACBS" << endl - << " - C.Climate" << endl - << "globals:" << endl - << " - type: say" << endl - << " content: '" << generalMasterlistMessage << "'" << endl - << " condition: 'file(\"" << missingEsp << "\")'" << endl - << "plugins:" << endl - << " - name: " << blankEsm << endl - << " after:" << endl - << " - " << masterFile << endl - << " msg:" << endl - << " - type: say" << endl - << " content: '" << noteMessage << "'" << endl - << " condition: 'file(\"" << missingEsp << "\")'" << endl - << " tag:" << endl - << " - Actors.ACBS" << endl - << " - Actors.AIData" << endl - << " - '-C.Water'" << endl - << " - name: " << blankDifferentEsm << endl - << " after:" << endl - << " - " << blankMasterDependentEsm << endl - << " msg:" << endl - << " - type: warn" << endl - << " content: '" << warningMessage << "'" << endl - << " dirty:" << endl - << " - crc: 0x7d22f9df" << endl - << " util: TES4Edit" << endl - << " udr: 4" << endl - << " - name: " << blankDifferentEsp << endl - << " after:" << endl - << " - " << blankPluginDependentEsp << endl - << " msg:" << endl - << " - type: error" << endl - << " content: '" << errorMessage << "'" << endl - << " - name: " << blankEsp << endl - << " after:" << endl - << " - " << blankDifferentMasterDependentEsp << endl - << " - name: " << blankDifferentMasterDependentEsp << endl - << " after:" << endl - << " - " << blankMasterDependentEsp << endl - << " msg:" << endl - << " - type: say" << endl - << " content: '" << noteMessage << "'" << endl - << " - type: warn" << endl - << " content: '" << warningMessage << "'" << endl - << " - type: error" << endl - << " content: '" << errorMessage << "'" << endl; + masterlist << "bash_tags:" << endl + << " - Actors.ACBS" << endl + << " - C.Climate" << endl + << "globals:" << endl + << " - type: say" << endl + << " content: '" << generalMasterlistMessage << "'" << endl + << " condition: 'file(\"" << missingEsp << "\")'" << endl + << "plugins:" << endl + << " - name: " << blankEsm << endl + << " after:" << endl + << " - " << masterFile << endl + << " msg:" << endl + << " - type: say" << endl + << " content: '" << noteMessage << "'" << endl + << " condition: 'file(\"" << missingEsp << "\")'" << endl + << " tag:" << endl + << " - Actors.ACBS" << endl + << " - Actors.AIData" << endl + << " - '-C.Water'" << endl + << " - name: " << blankDifferentEsm << endl + << " after:" << endl + << " - " << blankMasterDependentEsm << endl + << " msg:" << endl + << " - type: warn" << endl + << " content: '" << warningMessage << "'" << endl + << " dirty:" << endl + << " - crc: 0x7d22f9df" << endl + << " util: TES4Edit" << endl + << " udr: 4" << endl + << " - name: " << blankDifferentEsp << endl + << " after:" << endl + << " - " << blankPluginDependentEsp << endl + << " msg:" << endl + << " - type: error" << endl + << " content: '" << errorMessage << "'" << endl + << " - name: " << blankEsp << endl + << " after:" << endl + << " - " << blankDifferentMasterDependentEsp << endl + << " - name: " << blankDifferentMasterDependentEsp << endl + << " after:" << endl + << " - " << blankMasterDependentEsp << endl + << " msg:" << endl + << " - type: say" << endl + << " content: '" << noteMessage << "'" << endl + << " - type: warn" << endl + << " content: '" << warningMessage << "'" << endl + << " - type: error" << endl + << " content: '" << errorMessage << "'" << endl; masterlist.close(); } diff --git a/src/tests/api/interface/create_game_handle_test.h b/src/tests/api/interface/create_game_handle_test.h index 7c658f82..e76f7985 100644 --- a/src/tests/api/interface/create_game_handle_test.h +++ b/src/tests/api/interface/create_game_handle_test.h @@ -36,21 +36,29 @@ namespace test { class CreateGameHandleTest : public CommonGameTestFixture { protected: CreateGameHandleTest() : - handle_(nullptr), - gamePathSymlink(dataPath.parent_path().string() + ".symlink"), - localPathSymlink(localPath.string() + ".symlink"), - gamePathJunctionLink(dataPath.parent_path().string() + ".junction"), - localPathJunctionLink(localPath.string() + ".junction") {} + handle_(nullptr), + gamePathSymlink(dataPath.parent_path().string() + ".symlink"), + localPathSymlink(localPath.string() + ".symlink"), + gamePathJunctionLink(dataPath.parent_path().string() + ".junction"), + localPathJunctionLink(localPath.string() + ".junction") {} void SetUp() { CommonGameTestFixture::SetUp(); - boost::filesystem::create_directory_symlink(dataPath.parent_path(), gamePathSymlink); + boost::filesystem::create_directory_symlink(dataPath.parent_path(), + gamePathSymlink); boost::filesystem::create_directory_symlink(localPath, localPathSymlink); #ifdef _WIN32 - system(("mklink /J \"" + boost::filesystem::absolute(gamePathJunctionLink).string() + "\" \"" + boost::filesystem::absolute(dataPath).parent_path().string() + "\"").c_str()); - system(("mklink /J \"" + boost::filesystem::absolute(localPathJunctionLink).string() + "\" \"" + boost::filesystem::absolute(localPath).string() + "\"").c_str()); + system(("mklink /J \"" + + boost::filesystem::absolute(gamePathJunctionLink).string() + + "\" \"" + + boost::filesystem::absolute(dataPath).parent_path().string() + "\"") + .c_str()); + system(("mklink /J \"" + + boost::filesystem::absolute(localPathJunctionLink).string() + + "\" \"" + boost::filesystem::absolute(localPath).string() + "\"") + .c_str()); #endif } @@ -75,50 +83,67 @@ protected: // but we only have the one so no prefix is necessary. INSTANTIATE_TEST_CASE_P(, CreateGameHandleTest, - ::testing::Values( - GameType::tes4, - GameType::tes5, - GameType::fo3, - GameType::fonv, - GameType::fo4, - GameType::tes5se)); + ::testing::Values(GameType::tes4, + GameType::tes5, + GameType::fo3, + GameType::fonv, + GameType::fo4, + GameType::tes5se)); -TEST_P(CreateGameHandleTest, shouldSucceedIfPassedValidParametersWithRelativePaths) { - EXPECT_NO_THROW(handle_ = CreateGameHandle(GetParam(), dataPath.parent_path().string(), localPath.string())); +TEST_P(CreateGameHandleTest, + shouldSucceedIfPassedValidParametersWithRelativePaths) { + EXPECT_NO_THROW(handle_ = CreateGameHandle(GetParam(), + dataPath.parent_path().string(), + localPath.string())); EXPECT_NE(nullptr, handle_); } -TEST_P(CreateGameHandleTest, shouldSucceedIfPassedValidParametersWithAbsolutePaths) { - boost::filesystem::path game = boost::filesystem::current_path() / dataPath.parent_path(); +TEST_P(CreateGameHandleTest, + shouldSucceedIfPassedValidParametersWithAbsolutePaths) { + boost::filesystem::path game = + boost::filesystem::current_path() / dataPath.parent_path(); boost::filesystem::path local = boost::filesystem::current_path() / localPath; - EXPECT_NO_THROW(handle_ = CreateGameHandle(GetParam(), dataPath.parent_path().string(), localPath.string())); + EXPECT_NO_THROW(handle_ = CreateGameHandle(GetParam(), + dataPath.parent_path().string(), + localPath.string())); EXPECT_NE(nullptr, handle_); } TEST_P(CreateGameHandleTest, shouldThrowIfPassedAGamePathThatDoesNotExist) { - EXPECT_THROW(CreateGameHandle(GetParam(), missingPath.string(), localPath.string()), std::invalid_argument); + EXPECT_THROW( + CreateGameHandle(GetParam(), missingPath.string(), localPath.string()), + std::invalid_argument); } TEST_P(CreateGameHandleTest, shouldThrowIfPassedALocalPathThatDoesNotExist) { - EXPECT_THROW(CreateGameHandle(GetParam(), dataPath.parent_path().string(), missingPath.string()), std::invalid_argument); + EXPECT_THROW( + CreateGameHandle( + GetParam(), dataPath.parent_path().string(), missingPath.string()), + std::invalid_argument); } #ifdef _WIN32 TEST_P(CreateGameHandleTest, shouldReturnOkIfPassedAnEmptyLocalPathString) { - EXPECT_NO_THROW(handle_ = CreateGameHandle(GetParam(), dataPath.parent_path().string(), "")); + EXPECT_NO_THROW(handle_ = CreateGameHandle( + GetParam(), dataPath.parent_path().string(), "")); EXPECT_NE(nullptr, handle_); } #endif TEST_P(CreateGameHandleTest, shouldReturnOkIfPassedGameAndLocalPathSymlinks) { - EXPECT_NO_THROW(handle_ = CreateGameHandle(GetParam(), gamePathSymlink.string(), localPathSymlink.string())); + EXPECT_NO_THROW(handle_ = CreateGameHandle(GetParam(), + gamePathSymlink.string(), + localPathSymlink.string())); EXPECT_NE(nullptr, handle_); } #ifdef _WIN32 -TEST_P(CreateGameHandleTest, shouldReturnOkIfPassedGameAndLocalPathJunctionLinks) { - EXPECT_NO_THROW(handle_ = CreateGameHandle(GetParam(), gamePathJunctionLink.string(), localPathJunctionLink.string())); +TEST_P(CreateGameHandleTest, + shouldReturnOkIfPassedGameAndLocalPathJunctionLinks) { + EXPECT_NO_THROW(handle_ = CreateGameHandle(GetParam(), + gamePathJunctionLink.string(), + localPathJunctionLink.string())); EXPECT_NE(nullptr, handle_); } #endif diff --git a/src/tests/api/interface/database_interface_test.h b/src/tests/api/interface/database_interface_test.h index f0b63221..16a453c5 100644 --- a/src/tests/api/interface/database_interface_test.h +++ b/src/tests/api/interface/database_interface_test.h @@ -34,13 +34,13 @@ namespace test { class DatabaseInterfaceTest : public ApiGameOperationsTest { protected: DatabaseInterfaceTest() : - db_(nullptr), - userlistPath_(localPath / "userlist.yaml"), - url_("https://github.com/loot/testing-metadata.git"), - branch_("master"), - oldBranch_("old-branch"), - minimalOutputPath_(localPath / "minimal.yml"), - generalUserlistMessage("A general userlist message.") {} + db_(nullptr), + userlistPath_(localPath / "userlist.yaml"), + url_("https://github.com/loot/testing-metadata.git"), + branch_("master"), + oldBranch_("old-branch"), + minimalOutputPath_(localPath / "minimal.yml"), + generalUserlistMessage("A general userlist message.") {} void SetUp() { ApiGameOperationsTest::SetUp(); @@ -53,8 +53,8 @@ protected: void TearDown() { if (boost::filesystem::exists(minimalOutputPath_)) { boost::filesystem::permissions(minimalOutputPath_, - boost::filesystem::perms::add_perms - | boost::filesystem::perms::owner_write); + boost::filesystem::perms::add_perms | + boost::filesystem::perms::owner_write); } ApiGameOperationsTest::TearDown(); @@ -63,7 +63,8 @@ protected: ASSERT_NO_THROW(boost::filesystem::remove(userlistPath_)); // Also remove the ".git" folder if it has been created. - ASSERT_NO_THROW(boost::filesystem::remove_all(masterlistPath.parent_path() / ".git")); + ASSERT_NO_THROW( + boost::filesystem::remove_all(masterlistPath.parent_path() / ".git")); ASSERT_NO_THROW(boost::filesystem::remove(minimalOutputPath_)); } @@ -72,18 +73,17 @@ protected: using std::endl; std::stringstream expectedContent; - expectedContent - << "plugins:" << endl - << " - name: '" << blankDifferentEsm << "'" << endl - << " dirty:" << endl - << " - crc: 0x7d22f9df" << endl - << " util: 'TES4Edit'" << endl - << " udr: 4" << endl - << " - name: '" << blankEsm << "'" << endl - << " tag:" << endl - << " - Actors.ACBS" << endl - << " - Actors.AIData" << endl - << " - -C.Water"; + expectedContent << "plugins:" << endl + << " - name: '" << blankDifferentEsm << "'" << endl + << " dirty:" << endl + << " - crc: 0x7d22f9df" << endl + << " util: 'TES4Edit'" << endl + << " udr: 4" << endl + << " - name: '" << blankEsm << "'" << endl + << " tag:" << endl + << " - Actors.ACBS" << endl + << " - Actors.AIData" << endl + << " - -C.Water"; return expectedContent.str(); } @@ -100,23 +100,22 @@ protected: using std::endl; boost::filesystem::ofstream userlist(userlistPath_); - userlist - << "bash_tags:" << endl - << " - RaceRelations" << endl - << " - C.Lighting" << endl - << "globals:" << endl - << " - type: say" << endl - << " content: '" << generalUserlistMessage << "'" << endl - << "plugins:" << endl - << " - name: " << blankEsm << endl - << " after:" << endl - << " - " << blankDifferentEsm << endl - << " - name: " << blankDifferentEsp << endl - << " inc:" << endl - << " - " << blankEsp << endl - << " tag:" << endl - << " - name: C.Climate" << endl - << " condition: 'file(\"" << missingEsp << "\")'" << endl; + userlist << "bash_tags:" << endl + << " - RaceRelations" << endl + << " - C.Lighting" << endl + << "globals:" << endl + << " - type: say" << endl + << " content: '" << generalUserlistMessage << "'" << endl + << "plugins:" << endl + << " - name: " << blankEsm << endl + << " after:" << endl + << " - " << blankDifferentEsm << endl + << " - name: " << blankDifferentEsp << endl + << " inc:" << endl + << " - " << blankEsp << endl + << " tag:" << endl + << " - name: C.Climate" << endl + << " condition: 'file(\"" << missingEsp << "\")'" << endl; userlist.close(); } @@ -135,16 +134,18 @@ protected: // but we only have the one so no prefix is necessary. INSTANTIATE_TEST_CASE_P(, DatabaseInterfaceTest, - ::testing::Values( - GameType::tes4, - GameType::tes5, - GameType::fo3, - GameType::fonv, - GameType::fo4, - GameType::tes5se)); + ::testing::Values(GameType::tes4, + GameType::tes5, + GameType::fo3, + GameType::fonv, + GameType::fo4, + GameType::tes5se)); -TEST_P(DatabaseInterfaceTest, loadListsShouldSucceedEvenIfGameHandleIsDiscarded) { - db_ = CreateGameHandle(GetParam(), dataPath.parent_path().string(), localPath.string())->GetDatabase(); +TEST_P(DatabaseInterfaceTest, + loadListsShouldSucceedEvenIfGameHandleIsDiscarded) { + db_ = CreateGameHandle( + GetParam(), dataPath.parent_path().string(), localPath.string()) + ->GetDatabase(); ASSERT_NO_THROW(GenerateMasterlist()); @@ -155,55 +156,72 @@ TEST_P(DatabaseInterfaceTest, loadListsShouldThrowIfNoMasterlistIsPresent) { EXPECT_THROW(db_->LoadLists(masterlistPath.string(), ""), FileAccessError); } -TEST_P(DatabaseInterfaceTest, loadListsShouldThrowIfAMasterlistIsPresentButAUserlistDoesNotExistAtTheGivenPath) { +TEST_P( + DatabaseInterfaceTest, + loadListsShouldThrowIfAMasterlistIsPresentButAUserlistDoesNotExistAtTheGivenPath) { ASSERT_NO_THROW(GenerateMasterlist()); - EXPECT_THROW(db_->LoadLists(masterlistPath.string(), userlistPath_.string()), FileAccessError); + EXPECT_THROW(db_->LoadLists(masterlistPath.string(), userlistPath_.string()), + FileAccessError); } -TEST_P(DatabaseInterfaceTest, loadListsShouldSucceedIfTheMasterlistIsPresentAndTheUserlistPathIsAnEmptyString) { +TEST_P( + DatabaseInterfaceTest, + loadListsShouldSucceedIfTheMasterlistIsPresentAndTheUserlistPathIsAnEmptyString) { ASSERT_NO_THROW(GenerateMasterlist()); EXPECT_NO_THROW(db_->LoadLists(masterlistPath.string(), "")); } -TEST_P(DatabaseInterfaceTest, loadListsShouldSucceedIfTheMasterlistAndUserlistAreBothPresent) { +TEST_P(DatabaseInterfaceTest, + loadListsShouldSucceedIfTheMasterlistAndUserlistAreBothPresent) { ASSERT_NO_THROW(GenerateMasterlist()); ASSERT_NO_THROW(boost::filesystem::copy(masterlistPath, userlistPath_)); - EXPECT_NO_THROW(db_->LoadLists(masterlistPath.string(), userlistPath_.string())); + EXPECT_NO_THROW( + db_->LoadLists(masterlistPath.string(), userlistPath_.string())); } -TEST_P(DatabaseInterfaceTest, writeUserMetadataShouldThrowIfTheFileAlreadyExistsAndTheOverwriteArgumentIsFalse) { +TEST_P( + DatabaseInterfaceTest, + writeUserMetadataShouldThrowIfTheFileAlreadyExistsAndTheOverwriteArgumentIsFalse) { ASSERT_NO_THROW(db_->WriteUserMetadata(minimalOutputPath_.string(), false)); ASSERT_TRUE(boost::filesystem::exists(minimalOutputPath_)); - EXPECT_THROW(db_->WriteUserMetadata(minimalOutputPath_.string(), false), FileAccessError); + EXPECT_THROW(db_->WriteUserMetadata(minimalOutputPath_.string(), false), + FileAccessError); } -TEST_P(DatabaseInterfaceTest, writeUserMetadataShouldReturnOkAndWriteToFileIfTheArgumentsAreValidAndTheOverwriteArgumentIsTrue) { +TEST_P( + DatabaseInterfaceTest, + writeUserMetadataShouldReturnOkAndWriteToFileIfTheArgumentsAreValidAndTheOverwriteArgumentIsTrue) { EXPECT_NO_THROW(db_->WriteUserMetadata(minimalOutputPath_.string(), true)); EXPECT_TRUE(boost::filesystem::exists(minimalOutputPath_)); } -TEST_P(DatabaseInterfaceTest, writeUserMetadataShouldReturnOkIfTheFileAlreadyExistsAndTheOverwriteArgumentIsTrue) { +TEST_P( + DatabaseInterfaceTest, + writeUserMetadataShouldReturnOkIfTheFileAlreadyExistsAndTheOverwriteArgumentIsTrue) { ASSERT_NO_THROW(db_->WriteUserMetadata(minimalOutputPath_.string(), false)); ASSERT_TRUE(boost::filesystem::exists(minimalOutputPath_)); EXPECT_NO_THROW(db_->WriteUserMetadata(minimalOutputPath_.string(), true)); } -TEST_P(DatabaseInterfaceTest, writeUserMetadataShouldThrowIfPathGivenExistsAndIsReadOnly) { +TEST_P(DatabaseInterfaceTest, + writeUserMetadataShouldThrowIfPathGivenExistsAndIsReadOnly) { ASSERT_NO_THROW(db_->WriteUserMetadata(minimalOutputPath_.string(), false)); ASSERT_TRUE(boost::filesystem::exists(minimalOutputPath_)); boost::filesystem::permissions(minimalOutputPath_, - boost::filesystem::perms::remove_perms - | boost::filesystem::perms::owner_write); + boost::filesystem::perms::remove_perms | + boost::filesystem::perms::owner_write); - EXPECT_THROW(db_->WriteUserMetadata(minimalOutputPath_.string(), true), FileAccessError); + EXPECT_THROW(db_->WriteUserMetadata(minimalOutputPath_.string(), true), + FileAccessError); } -TEST_P(DatabaseInterfaceTest, writeUserMetadataShouldShouldNotWriteMasterlistMetadata) { +TEST_P(DatabaseInterfaceTest, + writeUserMetadataShouldShouldNotWriteMasterlistMetadata) { ASSERT_NO_THROW(GenerateMasterlist()); ASSERT_NO_THROW(db_->LoadLists(masterlistPath.string(), "")); @@ -220,148 +238,199 @@ TEST_P(DatabaseInterfaceTest, writeUserMetadataShouldShouldWriteUserMetadata) { masterlist << "bash_tags:\n []\nglobals:\n []\nplugins:\n []"; masterlist.close(); - ASSERT_NO_THROW(db_->LoadLists(masterlistPath.string(), userlistPath_.string())); + ASSERT_NO_THROW( + db_->LoadLists(masterlistPath.string(), userlistPath_.string())); EXPECT_NO_THROW(db_->WriteUserMetadata(minimalOutputPath_.string(), true)); EXPECT_FALSE(GetFileContent(minimalOutputPath_).empty()); } -TEST_P(DatabaseInterfaceTest, updateMasterlistShouldThrowIfTheMasterlistPathGivenIsInvalid) { - EXPECT_THROW(db_->UpdateMasterlist(";//\?", url_, branch_), std::invalid_argument); +TEST_P(DatabaseInterfaceTest, + updateMasterlistShouldThrowIfTheMasterlistPathGivenIsInvalid) { + EXPECT_THROW(db_->UpdateMasterlist(";//\?", url_, branch_), + std::invalid_argument); } -TEST_P(DatabaseInterfaceTest, updateMasterlistShouldThrowIfTheMasterlistPathGivenIsEmpty) { +TEST_P(DatabaseInterfaceTest, + updateMasterlistShouldThrowIfTheMasterlistPathGivenIsEmpty) { EXPECT_THROW(db_->UpdateMasterlist("", url_, branch_), std::invalid_argument); } -TEST_P(DatabaseInterfaceTest, updateMasterlistShouldThrowIfTheRepositoryUrlGivenCannotBeFound) { - EXPECT_THROW(db_->UpdateMasterlist(masterlistPath.string(), "https://github.com/loot/oblivion-does-not-exist.git", branch_), std::system_error); +TEST_P(DatabaseInterfaceTest, + updateMasterlistShouldThrowIfTheRepositoryUrlGivenCannotBeFound) { + EXPECT_THROW(db_->UpdateMasterlist( + masterlistPath.string(), + "https://github.com/loot/oblivion-does-not-exist.git", + branch_), + std::system_error); } -TEST_P(DatabaseInterfaceTest, updateMasterlistShouldThrowIfTheRepositoryUrlGivenIsEmpty) { - EXPECT_THROW(db_->UpdateMasterlist(masterlistPath.string(), "", branch_), std::invalid_argument); +TEST_P(DatabaseInterfaceTest, + updateMasterlistShouldThrowIfTheRepositoryUrlGivenIsEmpty) { + EXPECT_THROW(db_->UpdateMasterlist(masterlistPath.string(), "", branch_), + std::invalid_argument); } -TEST_P(DatabaseInterfaceTest, updateMasterlistShouldThrowIfTheRepositoryBranchGivenCannotBeFound) { - EXPECT_THROW(db_->UpdateMasterlist(masterlistPath.string(), url_, "missing-branch"), std::system_error); +TEST_P(DatabaseInterfaceTest, + updateMasterlistShouldThrowIfTheRepositoryBranchGivenCannotBeFound) { + EXPECT_THROW( + db_->UpdateMasterlist(masterlistPath.string(), url_, "missing-branch"), + std::system_error); } -TEST_P(DatabaseInterfaceTest, updateMasterlistShouldThrowIfTheRepositoryBranchGivenIsEmpty) { - EXPECT_THROW(db_->UpdateMasterlist(masterlistPath.string(), url_, ""), std::invalid_argument); +TEST_P(DatabaseInterfaceTest, + updateMasterlistShouldThrowIfTheRepositoryBranchGivenIsEmpty) { + EXPECT_THROW(db_->UpdateMasterlist(masterlistPath.string(), url_, ""), + std::invalid_argument); } -TEST_P(DatabaseInterfaceTest, updateMasterlistShouldSucceedIfPassedValidParametersAndOutputTrueIfTheMasterlistWasUpdated) { +TEST_P( + DatabaseInterfaceTest, + updateMasterlistShouldSucceedIfPassedValidParametersAndOutputTrueIfTheMasterlistWasUpdated) { bool updated = false; - EXPECT_NO_THROW(updated = db_->UpdateMasterlist(masterlistPath.string(), url_, branch_)); + EXPECT_NO_THROW( + updated = db_->UpdateMasterlist(masterlistPath.string(), url_, branch_)); EXPECT_TRUE(updated); EXPECT_TRUE(boost::filesystem::exists(masterlistPath)); } -TEST_P(DatabaseInterfaceTest, updateMasterlistShouldSucceedIfCalledRepeatedlyButOnlyOutputTrueForTheFirstCall) { +TEST_P( + DatabaseInterfaceTest, + updateMasterlistShouldSucceedIfCalledRepeatedlyButOnlyOutputTrueForTheFirstCall) { bool updated = false; - EXPECT_NO_THROW(updated = db_->UpdateMasterlist(masterlistPath.string(), url_, branch_)); + EXPECT_NO_THROW( + updated = db_->UpdateMasterlist(masterlistPath.string(), url_, branch_)); EXPECT_TRUE(updated); - EXPECT_NO_THROW(updated = db_->UpdateMasterlist(masterlistPath.string(), url_, branch_)); + EXPECT_NO_THROW( + updated = db_->UpdateMasterlist(masterlistPath.string(), url_, branch_)); EXPECT_FALSE(updated); EXPECT_TRUE(boost::filesystem::exists(masterlistPath)); } -TEST_P(DatabaseInterfaceTest, getMasterlistRevisionShouldThrowIfNoMasterlistIsPresent) { +TEST_P(DatabaseInterfaceTest, + getMasterlistRevisionShouldThrowIfNoMasterlistIsPresent) { MasterlistInfo info; - EXPECT_THROW(info = db_->GetMasterlistRevision(masterlistPath.string(), false), FileAccessError); + EXPECT_THROW( + info = db_->GetMasterlistRevision(masterlistPath.string(), false), + FileAccessError); EXPECT_TRUE(info.revision_id.empty()); EXPECT_TRUE(info.revision_date.empty()); EXPECT_FALSE(info.is_modified); } -TEST_P(DatabaseInterfaceTest, getMasterlistRevisionShouldThrowIfANonVersionControlledMasterlistIsPresent) { +TEST_P( + DatabaseInterfaceTest, + getMasterlistRevisionShouldThrowIfANonVersionControlledMasterlistIsPresent) { ASSERT_NO_THROW(GenerateMasterlist()); MasterlistInfo info; - EXPECT_THROW(info = db_->GetMasterlistRevision(masterlistPath.string(), false), GitStateError); + EXPECT_THROW( + info = db_->GetMasterlistRevision(masterlistPath.string(), false), + GitStateError); EXPECT_TRUE(info.revision_id.empty()); EXPECT_TRUE(info.revision_date.empty()); EXPECT_FALSE(info.is_modified); } -TEST_P(DatabaseInterfaceTest, getMasterlistRevisionShouldOutputLongStringsAndBooleanFalseIfAVersionControlledMasterlistIsPresentAndGetShortIdParameterIsFalse) { - ASSERT_NO_THROW(db_->UpdateMasterlist(masterlistPath.string(), url_, branch_)); +TEST_P( + DatabaseInterfaceTest, + getMasterlistRevisionShouldOutputLongStringsAndBooleanFalseIfAVersionControlledMasterlistIsPresentAndGetShortIdParameterIsFalse) { + ASSERT_NO_THROW( + db_->UpdateMasterlist(masterlistPath.string(), url_, branch_)); MasterlistInfo info; - EXPECT_NO_THROW(info = db_->GetMasterlistRevision(masterlistPath.string(), false)); + EXPECT_NO_THROW( + info = db_->GetMasterlistRevision(masterlistPath.string(), false)); EXPECT_EQ(40, info.revision_id.length()); EXPECT_EQ(10, info.revision_date.length()); EXPECT_FALSE(info.is_modified); } -TEST_P(DatabaseInterfaceTest, getMasterlistRevisionShouldOutputShortStringsAndBooleanFalseIfAVersionControlledMasterlistIsPresentAndGetShortIdParameterIsTrue) { - ASSERT_NO_THROW(db_->UpdateMasterlist(masterlistPath.string(), url_, branch_)); +TEST_P( + DatabaseInterfaceTest, + getMasterlistRevisionShouldOutputShortStringsAndBooleanFalseIfAVersionControlledMasterlistIsPresentAndGetShortIdParameterIsTrue) { + ASSERT_NO_THROW( + db_->UpdateMasterlist(masterlistPath.string(), url_, branch_)); MasterlistInfo info; - EXPECT_NO_THROW(info = db_->GetMasterlistRevision(masterlistPath.string(), false)); + EXPECT_NO_THROW( + info = db_->GetMasterlistRevision(masterlistPath.string(), false)); EXPECT_GE(size_t(40), info.revision_id.length()); EXPECT_LE(size_t(7), info.revision_id.length()); EXPECT_EQ(10, info.revision_date.length()); EXPECT_FALSE(info.is_modified); } -TEST_P(DatabaseInterfaceTest, getMasterlistRevisionShouldSucceedIfAnEditedVersionControlledMasterlistIsPresent) { - ASSERT_NO_THROW(db_->UpdateMasterlist(masterlistPath.string(), url_, branch_)); +TEST_P( + DatabaseInterfaceTest, + getMasterlistRevisionShouldSucceedIfAnEditedVersionControlledMasterlistIsPresent) { + ASSERT_NO_THROW( + db_->UpdateMasterlist(masterlistPath.string(), url_, branch_)); ASSERT_NO_THROW(GenerateMasterlist()); MasterlistInfo info; - EXPECT_NO_THROW(info = db_->GetMasterlistRevision(masterlistPath.string(), false)); + EXPECT_NO_THROW( + info = db_->GetMasterlistRevision(masterlistPath.string(), false)); EXPECT_EQ(40, info.revision_id.length()); EXPECT_EQ(10, info.revision_date.length()); EXPECT_TRUE(info.is_modified); } -TEST_P(DatabaseInterfaceTest, isLatestMasterlistShouldReturnFalseIfTheCurrentRevisionIsNotTheLatestRevisionInTheGivenBranch) { - ASSERT_NO_THROW(db_->UpdateMasterlist(masterlistPath.string(), url_, oldBranch_)); +TEST_P( + DatabaseInterfaceTest, + isLatestMasterlistShouldReturnFalseIfTheCurrentRevisionIsNotTheLatestRevisionInTheGivenBranch) { + ASSERT_NO_THROW( + db_->UpdateMasterlist(masterlistPath.string(), url_, oldBranch_)); EXPECT_FALSE(db_->IsLatestMasterlist(masterlistPath.string(), branch_)); } -TEST_P(DatabaseInterfaceTest, isLatestMasterlistShouldReturnTrueIfTheCurrentRevisionIsTheLatestRevisioninTheGivenBranch) { - ASSERT_NO_THROW(db_->UpdateMasterlist(masterlistPath.string(), url_, branch_)); +TEST_P( + DatabaseInterfaceTest, + isLatestMasterlistShouldReturnTrueIfTheCurrentRevisionIsTheLatestRevisioninTheGivenBranch) { + ASSERT_NO_THROW( + db_->UpdateMasterlist(masterlistPath.string(), url_, branch_)); EXPECT_TRUE(db_->IsLatestMasterlist(masterlistPath.string(), branch_)); } -TEST_P(DatabaseInterfaceTest, getKnownBashTagsShouldReturnAllBashTagsListedInLoadedMetadata) { +TEST_P(DatabaseInterfaceTest, + getKnownBashTagsShouldReturnAllBashTagsListedInLoadedMetadata) { ASSERT_NO_THROW(GenerateMasterlist()); ASSERT_NO_THROW(GenerateUserlist()); - ASSERT_NO_THROW(db_->LoadLists(masterlistPath.string(), userlistPath_.string())); + ASSERT_NO_THROW( + db_->LoadLists(masterlistPath.string(), userlistPath_.string())); auto tags = db_->GetKnownBashTags(); std::set expectedTags({ - "RaceRelations", - "C.Lighting", - "Actors.ACBS", - "C.Climate", + "RaceRelations", "C.Lighting", "Actors.ACBS", "C.Climate", }); EXPECT_EQ(expectedTags, tags); } -TEST_P(DatabaseInterfaceTest, getGeneralMessagesShouldGetGeneralMessagesFromTheMasterlistAndUserlist) { +TEST_P(DatabaseInterfaceTest, + getGeneralMessagesShouldGetGeneralMessagesFromTheMasterlistAndUserlist) { ASSERT_NO_THROW(GenerateMasterlist()); ASSERT_NO_THROW(GenerateUserlist()); - ASSERT_NO_THROW(db_->LoadLists(masterlistPath.string(), userlistPath_.string())); + ASSERT_NO_THROW( + db_->LoadLists(masterlistPath.string(), userlistPath_.string())); auto messages = db_->GetGeneralMessages(); std::vector expectedMessages({ - Message(MessageType::say, generalMasterlistMessage), - Message(MessageType::say, generalUserlistMessage), + Message(MessageType::say, generalMasterlistMessage), + Message(MessageType::say, generalUserlistMessage), }); EXPECT_EQ(expectedMessages, messages); } -TEST_P(DatabaseInterfaceTest, getGeneralMessagesShouldReturnOnlyValidMessagesIfConditionsAreEvaluated) { +TEST_P( + DatabaseInterfaceTest, + getGeneralMessagesShouldReturnOnlyValidMessagesIfConditionsAreEvaluated) { ASSERT_NO_THROW(GenerateMasterlist()); ASSERT_NO_THROW(db_->LoadLists(masterlistPath.string(), "")); @@ -370,40 +439,49 @@ TEST_P(DatabaseInterfaceTest, getGeneralMessagesShouldReturnOnlyValidMessagesIfC EXPECT_TRUE(messages.empty()); } -TEST_P(DatabaseInterfaceTest, getPluginMetadataShouldReturnAnEmptyPluginMetadataObjectIfThePluginHasNoMetadata) { +TEST_P( + DatabaseInterfaceTest, + getPluginMetadataShouldReturnAnEmptyPluginMetadataObjectIfThePluginHasNoMetadata) { auto metadata = db_->GetPluginMetadata(blankEsm); EXPECT_TRUE(metadata.HasNameOnly()); } -TEST_P(DatabaseInterfaceTest, getPluginMetadataShouldReturnMergedMasterAndUserMetadataForTheGivenPluginIfIncludeUserMetadataIsTrue) { +TEST_P( + DatabaseInterfaceTest, + getPluginMetadataShouldReturnMergedMasterAndUserMetadataForTheGivenPluginIfIncludeUserMetadataIsTrue) { ASSERT_NO_THROW(GenerateMasterlist()); ASSERT_NO_THROW(GenerateUserlist()); - ASSERT_NO_THROW(db_->LoadLists(masterlistPath.string(), userlistPath_.string())); + ASSERT_NO_THROW( + db_->LoadLists(masterlistPath.string(), userlistPath_.string())); auto metadata = db_->GetPluginMetadata(blankEsm, true); std::set expectedLoadAfter({ - File(masterFile), - File(blankDifferentEsm), + File(masterFile), File(blankDifferentEsm), }); EXPECT_EQ(expectedLoadAfter, metadata.GetLoadAfterFiles()); } -TEST_P(DatabaseInterfaceTest, getPluginMetadataShouldReturnOnlyMasterlistMetadataForTheGivenPluginIfIncludeUserMetadataIsFalse) { +TEST_P( + DatabaseInterfaceTest, + getPluginMetadataShouldReturnOnlyMasterlistMetadataForTheGivenPluginIfIncludeUserMetadataIsFalse) { ASSERT_NO_THROW(GenerateMasterlist()); ASSERT_NO_THROW(GenerateUserlist()); - ASSERT_NO_THROW(db_->LoadLists(masterlistPath.string(), userlistPath_.string())); + ASSERT_NO_THROW( + db_->LoadLists(masterlistPath.string(), userlistPath_.string())); auto metadata = db_->GetPluginMetadata(blankEsm, false); std::set expectedLoadAfter({ - File(masterFile), + File(masterFile), }); EXPECT_EQ(expectedLoadAfter, metadata.GetLoadAfterFiles()); } -TEST_P(DatabaseInterfaceTest, getPluginMetadataShouldReturnOnlyValidMetadataForTheGivenPluginIfConditionsAreEvaluated) { +TEST_P( + DatabaseInterfaceTest, + getPluginMetadataShouldReturnOnlyValidMetadataForTheGivenPluginIfConditionsAreEvaluated) { ASSERT_NO_THROW(GenerateMasterlist()); ASSERT_NO_THROW(db_->LoadLists(masterlistPath.string(), "")); @@ -412,43 +490,54 @@ TEST_P(DatabaseInterfaceTest, getPluginMetadataShouldReturnOnlyValidMetadataForT EXPECT_TRUE(metadata.GetMessages().empty()); } -TEST_P(DatabaseInterfaceTest, getPluginUserMetadataShouldReturnAnEmptyPluginMetadataObjectIfThePluginHasNoUserMetadata) { +TEST_P( + DatabaseInterfaceTest, + getPluginUserMetadataShouldReturnAnEmptyPluginMetadataObjectIfThePluginHasNoUserMetadata) { ASSERT_NO_THROW(GenerateMasterlist()); ASSERT_NO_THROW(GenerateUserlist()); - ASSERT_NO_THROW(db_->LoadLists(masterlistPath.string(), userlistPath_.string())); + ASSERT_NO_THROW( + db_->LoadLists(masterlistPath.string(), userlistPath_.string())); auto metadata = db_->GetPluginUserMetadata(blankDifferentEsm); EXPECT_TRUE(metadata.HasNameOnly()); } -TEST_P(DatabaseInterfaceTest, getPluginUserMetadataShouldReturnOnlyUserMetadataForTheGivenPlugin) { +TEST_P(DatabaseInterfaceTest, + getPluginUserMetadataShouldReturnOnlyUserMetadataForTheGivenPlugin) { ASSERT_NO_THROW(GenerateMasterlist()); ASSERT_NO_THROW(GenerateUserlist()); - ASSERT_NO_THROW(db_->LoadLists(masterlistPath.string(), userlistPath_.string())); + ASSERT_NO_THROW( + db_->LoadLists(masterlistPath.string(), userlistPath_.string())); auto metadata = db_->GetPluginUserMetadata(blankEsm); std::set expectedLoadAfter({ - File(blankDifferentEsm), + File(blankDifferentEsm), }); EXPECT_EQ(expectedLoadAfter, metadata.GetLoadAfterFiles()); } -TEST_P(DatabaseInterfaceTest, getPluginUserMetadataShouldReturnOnlyValidMetadataForTheGivenPluginIfConditionsAreEvaluated) { +TEST_P( + DatabaseInterfaceTest, + getPluginUserMetadataShouldReturnOnlyValidMetadataForTheGivenPluginIfConditionsAreEvaluated) { ASSERT_NO_THROW(GenerateMasterlist()); ASSERT_NO_THROW(GenerateUserlist()); - ASSERT_NO_THROW(db_->LoadLists(masterlistPath.string(), userlistPath_.string())); + ASSERT_NO_THROW( + db_->LoadLists(masterlistPath.string(), userlistPath_.string())); auto metadata = db_->GetPluginMetadata(blankEsm, false, true); EXPECT_TRUE(metadata.GetMessages().empty()); } -TEST_P(DatabaseInterfaceTest, setPluginUserMetadataShouldReplaceExistingUserMetadataWithTheGivenMetadata) { +TEST_P( + DatabaseInterfaceTest, + setPluginUserMetadataShouldReplaceExistingUserMetadataWithTheGivenMetadata) { ASSERT_NO_THROW(GenerateMasterlist()); ASSERT_NO_THROW(GenerateUserlist()); - ASSERT_NO_THROW(db_->LoadLists(masterlistPath.string(), userlistPath_.string())); + ASSERT_NO_THROW( + db_->LoadLists(masterlistPath.string(), userlistPath_.string())); PluginMetadata newMetadata(blankDifferentEsp); newMetadata.SetRequirements(std::set({File(masterFile)})); @@ -458,16 +547,18 @@ TEST_P(DatabaseInterfaceTest, setPluginUserMetadataShouldReplaceExistingUserMeta auto metadata = db_->GetPluginUserMetadata(blankDifferentEsp); std::set expectedLoadAfter({ - File(blankDifferentEsm), + File(blankDifferentEsm), }); EXPECT_TRUE(metadata.GetIncompatibilities().empty()); EXPECT_EQ(newMetadata.GetRequirements(), metadata.GetRequirements()); } -TEST_P(DatabaseInterfaceTest, setPluginUserMetadataShouldNotAffectExistingMasterlistMetadata) { +TEST_P(DatabaseInterfaceTest, + setPluginUserMetadataShouldNotAffectExistingMasterlistMetadata) { ASSERT_NO_THROW(GenerateMasterlist()); ASSERT_NO_THROW(GenerateUserlist()); - ASSERT_NO_THROW(db_->LoadLists(masterlistPath.string(), userlistPath_.string())); + ASSERT_NO_THROW( + db_->LoadLists(masterlistPath.string(), userlistPath_.string())); PluginMetadata newMetadata(blankEsm); newMetadata.SetRequirements(std::set({File(masterFile)})); @@ -477,15 +568,17 @@ TEST_P(DatabaseInterfaceTest, setPluginUserMetadataShouldNotAffectExistingMaster auto metadata = db_->GetPluginMetadata(blankEsm); std::set expectedLoadAfter({ - File(masterFile), + File(masterFile), }); EXPECT_EQ(expectedLoadAfter, metadata.GetLoadAfterFiles()); } -TEST_P(DatabaseInterfaceTest, discardPluginUserMetadataShouldDiscardAllUserMetadataForTheGivenPlugin) { +TEST_P(DatabaseInterfaceTest, + discardPluginUserMetadataShouldDiscardAllUserMetadataForTheGivenPlugin) { ASSERT_NO_THROW(GenerateMasterlist()); ASSERT_NO_THROW(GenerateUserlist()); - ASSERT_NO_THROW(db_->LoadLists(masterlistPath.string(), userlistPath_.string())); + ASSERT_NO_THROW( + db_->LoadLists(masterlistPath.string(), userlistPath_.string())); db_->DiscardPluginUserMetadata(blankEsm); @@ -493,25 +586,30 @@ TEST_P(DatabaseInterfaceTest, discardPluginUserMetadataShouldDiscardAllUserMetad EXPECT_TRUE(metadata.HasNameOnly()); } -TEST_P(DatabaseInterfaceTest, discardPluginUserMetadataShouldNotDiscardMasterlistMetadataForTheGivenPlugin) { +TEST_P( + DatabaseInterfaceTest, + discardPluginUserMetadataShouldNotDiscardMasterlistMetadataForTheGivenPlugin) { ASSERT_NO_THROW(GenerateMasterlist()); ASSERT_NO_THROW(GenerateUserlist()); - ASSERT_NO_THROW(db_->LoadLists(masterlistPath.string(), userlistPath_.string())); + ASSERT_NO_THROW( + db_->LoadLists(masterlistPath.string(), userlistPath_.string())); db_->DiscardPluginUserMetadata(blankEsm); auto metadata = db_->GetPluginMetadata(blankEsm); std::set expectedLoadAfter({ - File(masterFile), + File(masterFile), }); EXPECT_EQ(expectedLoadAfter, metadata.GetLoadAfterFiles()); } -TEST_P(DatabaseInterfaceTest, discardPluginUserMetadataShouldNotDiscardUserMetadataForOtherPlugins) { +TEST_P(DatabaseInterfaceTest, + discardPluginUserMetadataShouldNotDiscardUserMetadataForOtherPlugins) { ASSERT_NO_THROW(GenerateMasterlist()); ASSERT_NO_THROW(GenerateUserlist()); - ASSERT_NO_THROW(db_->LoadLists(masterlistPath.string(), userlistPath_.string())); + ASSERT_NO_THROW( + db_->LoadLists(masterlistPath.string(), userlistPath_.string())); db_->DiscardPluginUserMetadata(blankEsm); @@ -520,44 +618,48 @@ TEST_P(DatabaseInterfaceTest, discardPluginUserMetadataShouldNotDiscardUserMetad EXPECT_FALSE(metadata.HasNameOnly()); } -TEST_P(DatabaseInterfaceTest, discardPluginUserMetadataShouldNotDiscardGeneralMessages) { +TEST_P(DatabaseInterfaceTest, + discardPluginUserMetadataShouldNotDiscardGeneralMessages) { ASSERT_NO_THROW(GenerateMasterlist()); ASSERT_NO_THROW(GenerateUserlist()); - ASSERT_NO_THROW(db_->LoadLists(masterlistPath.string(), userlistPath_.string())); + ASSERT_NO_THROW( + db_->LoadLists(masterlistPath.string(), userlistPath_.string())); db_->DiscardPluginUserMetadata(blankEsm); auto messages = db_->GetGeneralMessages(); std::vector expectedMessages({ - Message(MessageType::say, generalMasterlistMessage), - Message(MessageType::say, generalUserlistMessage), + Message(MessageType::say, generalMasterlistMessage), + Message(MessageType::say, generalUserlistMessage), }); EXPECT_EQ(expectedMessages, messages); } -TEST_P(DatabaseInterfaceTest, discardPluginUserMetadataShouldNotDiscardKnownBashTags) { +TEST_P(DatabaseInterfaceTest, + discardPluginUserMetadataShouldNotDiscardKnownBashTags) { ASSERT_NO_THROW(GenerateMasterlist()); ASSERT_NO_THROW(GenerateUserlist()); - ASSERT_NO_THROW(db_->LoadLists(masterlistPath.string(), userlistPath_.string())); + ASSERT_NO_THROW( + db_->LoadLists(masterlistPath.string(), userlistPath_.string())); db_->DiscardPluginUserMetadata(blankEsm); auto tags = db_->GetKnownBashTags(); std::set expectedTags({ - "RaceRelations", - "C.Lighting", - "Actors.ACBS", - "C.Climate", + "RaceRelations", "C.Lighting", "Actors.ACBS", "C.Climate", }); EXPECT_EQ(expectedTags, tags); } -TEST_P(DatabaseInterfaceTest, discardAllUserMetadataShouldDiscardAllUserMetadataAndNoMasterlistMetadata) { +TEST_P( + DatabaseInterfaceTest, + discardAllUserMetadataShouldDiscardAllUserMetadataAndNoMasterlistMetadata) { ASSERT_NO_THROW(GenerateMasterlist()); ASSERT_NO_THROW(GenerateUserlist()); - ASSERT_NO_THROW(db_->LoadLists(masterlistPath.string(), userlistPath_.string())); + ASSERT_NO_THROW( + db_->LoadLists(masterlistPath.string(), userlistPath_.string())); db_->DiscardAllUserMetadata(); @@ -570,62 +672,72 @@ TEST_P(DatabaseInterfaceTest, discardAllUserMetadataShouldDiscardAllUserMetadata metadata = db_->GetPluginMetadata(blankEsm); std::set expectedLoadAfter({ - File(masterFile), + File(masterFile), }); EXPECT_EQ(expectedLoadAfter, metadata.GetLoadAfterFiles()); auto messages = db_->GetGeneralMessages(); std::vector expectedMessages({ - Message(MessageType::say, generalMasterlistMessage), + Message(MessageType::say, generalMasterlistMessage), }); EXPECT_EQ(expectedMessages, messages); auto tags = db_->GetKnownBashTags(); std::set expectedTags({ - "Actors.ACBS", - "C.Climate", + "Actors.ACBS", "C.Climate", }); EXPECT_EQ(expectedTags, tags); } -TEST_P(DatabaseInterfaceTest, writeMinimalListShouldReturnOkAndWriteToFileIfArgumentsGivenAreValid) { +TEST_P(DatabaseInterfaceTest, + writeMinimalListShouldReturnOkAndWriteToFileIfArgumentsGivenAreValid) { EXPECT_NO_THROW(db_->WriteMinimalList(minimalOutputPath_.string(), false)); EXPECT_TRUE(boost::filesystem::exists(minimalOutputPath_)); } -TEST_P(DatabaseInterfaceTest, writeMinimalListShouldThrowIfTheFileAlreadyExistsAndTheOverwriteArgumentIsFalse) { +TEST_P( + DatabaseInterfaceTest, + writeMinimalListShouldThrowIfTheFileAlreadyExistsAndTheOverwriteArgumentIsFalse) { ASSERT_NO_THROW(db_->WriteMinimalList(minimalOutputPath_.string(), false)); ASSERT_TRUE(boost::filesystem::exists(minimalOutputPath_)); - EXPECT_THROW(db_->WriteMinimalList(minimalOutputPath_.string(), false), FileAccessError); + EXPECT_THROW(db_->WriteMinimalList(minimalOutputPath_.string(), false), + FileAccessError); } -TEST_P(DatabaseInterfaceTest, writeMinimalListShouldReturnOkAndWriteToFileIfTheArgumentsAreValidAndTheOverwriteArgumentIsTrue) { +TEST_P( + DatabaseInterfaceTest, + writeMinimalListShouldReturnOkAndWriteToFileIfTheArgumentsAreValidAndTheOverwriteArgumentIsTrue) { EXPECT_NO_THROW(db_->WriteMinimalList(minimalOutputPath_.string(), true)); EXPECT_TRUE(boost::filesystem::exists(minimalOutputPath_)); } -TEST_P(DatabaseInterfaceTest, writeMinimalListShouldReturnOkIfTheFileAlreadyExistsAndTheOverwriteArgumentIsTrue) { +TEST_P( + DatabaseInterfaceTest, + writeMinimalListShouldReturnOkIfTheFileAlreadyExistsAndTheOverwriteArgumentIsTrue) { ASSERT_NO_THROW(db_->WriteMinimalList(minimalOutputPath_.string(), false)); ASSERT_TRUE(boost::filesystem::exists(minimalOutputPath_)); EXPECT_NO_THROW(db_->WriteMinimalList(minimalOutputPath_.string(), true)); } -TEST_P(DatabaseInterfaceTest, writeMinimalListShouldThrowIfPathGivenExistsAndIsReadOnly) { +TEST_P(DatabaseInterfaceTest, + writeMinimalListShouldThrowIfPathGivenExistsAndIsReadOnly) { ASSERT_NO_THROW(db_->WriteMinimalList(minimalOutputPath_.string(), false)); ASSERT_TRUE(boost::filesystem::exists(minimalOutputPath_)); boost::filesystem::permissions(minimalOutputPath_, - boost::filesystem::perms::remove_perms - | boost::filesystem::perms::owner_write); + boost::filesystem::perms::remove_perms | + boost::filesystem::perms::owner_write); - EXPECT_THROW(db_->WriteMinimalList(minimalOutputPath_.string(), true), FileAccessError); + EXPECT_THROW(db_->WriteMinimalList(minimalOutputPath_.string(), true), + FileAccessError); } -TEST_P(DatabaseInterfaceTest, writeMinimalListShouldWriteOnlyBashTagsAndDirtyInfo) { +TEST_P(DatabaseInterfaceTest, + writeMinimalListShouldWriteOnlyBashTagsAndDirtyInfo) { ASSERT_NO_THROW(GenerateMasterlist()); ASSERT_NO_THROW(db_->LoadLists(masterlistPath.string(), "")); diff --git a/src/tests/api/interface/game_interface_test.h b/src/tests/api/interface/game_interface_test.h index 23a6c18a..5a798ad8 100644 --- a/src/tests/api/interface/game_interface_test.h +++ b/src/tests/api/interface/game_interface_test.h @@ -34,20 +34,20 @@ namespace test { class GameInterfaceTest : public ApiGameOperationsTest { protected: GameInterfaceTest() : - emptyFile("EmptyFile.esm"), - pluginsToLoad({ - masterFile, - blankEsm, - blankDifferentEsm, - blankMasterDependentEsm, - blankDifferentMasterDependentEsm, - blankEsp, - blankDifferentEsp, - blankMasterDependentEsp, - blankDifferentMasterDependentEsp, - blankPluginDependentEsp, - blankDifferentPluginDependentEsp, - }) {} + emptyFile("EmptyFile.esm"), + pluginsToLoad({ + masterFile, + blankEsm, + blankDifferentEsm, + blankMasterDependentEsm, + blankDifferentMasterDependentEsm, + blankEsp, + blankDifferentEsp, + blankMasterDependentEsp, + blankDifferentMasterDependentEsp, + blankPluginDependentEsp, + blankDifferentPluginDependentEsp, + }) {} void TearDown() { ApiGameOperationsTest::TearDown(); @@ -63,13 +63,12 @@ protected: // but we only have the one so no prefix is necessary. INSTANTIATE_TEST_CASE_P(, GameInterfaceTest, - ::testing::Values( - GameType::tes4, - GameType::tes5, - GameType::fo3, - GameType::fonv, - GameType::fo4, - GameType::tes5se)); + ::testing::Values(GameType::tes4, + GameType::tes5, + GameType::fo3, + GameType::fonv, + GameType::fo4, + GameType::tes5se)); TEST_P(GameInterfaceTest, isValidPluginShouldReturnTrueForAValidPlugin) { EXPECT_TRUE(handle_->IsValidPlugin(blankEsm)); @@ -88,7 +87,9 @@ TEST_P(GameInterfaceTest, isValidPluginShouldReturnFalseForAnEmptyFile) { EXPECT_FALSE(handle_->IsValidPlugin(emptyFile)); } -TEST_P(GameInterfaceTest, loadPluginsWithHeadersOnlyTrueShouldLoadTheHeadersOfAllInstalledPlugins) { +TEST_P( + GameInterfaceTest, + loadPluginsWithHeadersOnlyTrueShouldLoadTheHeadersOfAllInstalledPlugins) { handle_->LoadPlugins(pluginsToLoad, true); EXPECT_EQ(11, handle_->GetLoadedPlugins().size()); @@ -101,7 +102,8 @@ TEST_P(GameInterfaceTest, loadPluginsWithHeadersOnlyTrueShouldLoadTheHeadersOfAl EXPECT_EQ(0, plugin->GetCRC()); } -TEST_P(GameInterfaceTest, loadPluginsWithHeadersOnlyFalseShouldFullyLoadAllInstalledPlugins) { +TEST_P(GameInterfaceTest, + loadPluginsWithHeadersOnlyFalseShouldFullyLoadAllInstalledPlugins) { handle_->LoadPlugins(pluginsToLoad, false); EXPECT_EQ(11, handle_->GetLoadedPlugins().size()); @@ -118,51 +120,55 @@ TEST_P(GameInterfaceTest, getPluginThatIsNotCachedShouldThrow) { EXPECT_THROW(handle_->GetPlugin(blankEsm), std::invalid_argument); } -TEST_P(GameInterfaceTest, gettingPluginsShouldReturnAnEmptySetIfNoneHaveBeenLoaded) { +TEST_P(GameInterfaceTest, + gettingPluginsShouldReturnAnEmptySetIfNoneHaveBeenLoaded) { EXPECT_TRUE(handle_->GetLoadedPlugins().empty()); } TEST_P(GameInterfaceTest, sortPluginsShouldSucceedIfPassedValidArguments) { std::vector expectedOrder = { - masterFile, - blankEsm, - blankMasterDependentEsm, - blankDifferentEsm, - blankDifferentMasterDependentEsm, - blankMasterDependentEsp, - blankDifferentMasterDependentEsp, - blankEsp, - blankPluginDependentEsp, - blankDifferentEsp, - blankDifferentPluginDependentEsp, + masterFile, + blankEsm, + blankMasterDependentEsm, + blankDifferentEsm, + blankDifferentMasterDependentEsm, + blankMasterDependentEsp, + blankDifferentMasterDependentEsp, + blankEsp, + blankPluginDependentEsp, + blankDifferentEsp, + blankDifferentPluginDependentEsp, }; ASSERT_NO_THROW(GenerateMasterlist()); - ASSERT_NO_THROW(handle_->GetDatabase()->LoadLists(masterlistPath.string(), "")); + ASSERT_NO_THROW( + handle_->GetDatabase()->LoadLists(masterlistPath.string(), "")); std::vector actualOrder = handle_->SortPlugins({ - blankEsp, - blankPluginDependentEsp, - blankDifferentMasterDependentEsm, - blankMasterDependentEsp, - blankDifferentMasterDependentEsp, - blankDifferentEsp, - blankDifferentPluginDependentEsp, - masterFile, - blankEsm, - blankMasterDependentEsm, - blankDifferentEsm, + blankEsp, + blankPluginDependentEsp, + blankDifferentMasterDependentEsm, + blankMasterDependentEsp, + blankDifferentMasterDependentEsp, + blankDifferentEsp, + blankDifferentPluginDependentEsp, + masterFile, + blankEsm, + blankMasterDependentEsm, + blankDifferentEsm, }); EXPECT_EQ(expectedOrder, actualOrder); } -TEST_P(GameInterfaceTest, isPluginActiveShouldReturnFalseIfTheGivenPluginIsNotActive) { +TEST_P(GameInterfaceTest, + isPluginActiveShouldReturnFalseIfTheGivenPluginIsNotActive) { handle_->LoadCurrentLoadOrderState(); EXPECT_TRUE(handle_->IsPluginActive(blankEsm)); } -TEST_P(GameInterfaceTest, isPluginActiveShouldReturnTrueIfTheGivenPluginIsActive) { +TEST_P(GameInterfaceTest, + isPluginActiveShouldReturnTrueIfTheGivenPluginIsActive) { handle_->LoadCurrentLoadOrderState(); EXPECT_FALSE(handle_->IsPluginActive(blankEsp)); } @@ -175,22 +181,21 @@ TEST_P(GameInterfaceTest, getLoadOrderShouldReturnTheCurrentLoadOrder) { TEST_P(GameInterfaceTest, setLoadOrderShouldSetTheLoadOrder) { handle_->LoadCurrentLoadOrderState(); std::vector loadOrder({ - masterFile, - blankEsm, - blankMasterDependentEsm, - blankDifferentEsm, - blankDifferentMasterDependentEsm, - blankDifferentEsp, - blankDifferentPluginDependentEsp, - blankEsp, - blankMasterDependentEsp, - blankDifferentMasterDependentEsp, - blankPluginDependentEsp, + masterFile, + blankEsm, + blankMasterDependentEsm, + blankDifferentEsm, + blankDifferentMasterDependentEsm, + blankDifferentEsp, + blankDifferentPluginDependentEsp, + blankEsp, + blankMasterDependentEsp, + blankDifferentMasterDependentEsp, + blankPluginDependentEsp, }); EXPECT_NO_THROW(handle_->SetLoadOrder(loadOrder)); - EXPECT_EQ(loadOrder, handle_->GetLoadOrder()); if (GetParam() == GameType::fo4 || GetParam() == GameType::tes5se) @@ -198,7 +203,6 @@ TEST_P(GameInterfaceTest, setLoadOrderShouldSetTheLoadOrder) { EXPECT_EQ(loadOrder, getLoadOrder()); } - } } diff --git a/src/tests/api/interface/is_compatible_test.h b/src/tests/api/interface/is_compatible_test.h index 48198586..de8128d4 100644 --- a/src/tests/api/interface/is_compatible_test.h +++ b/src/tests/api/interface/is_compatible_test.h @@ -31,12 +31,16 @@ along with LOOT. If not, see namespace loot { namespace test { -TEST(IsCompatible, shouldReturnTrueWithEqualMajorAndMinorVersionsAndUnequalPatchVersion) { - EXPECT_TRUE(IsCompatible(LootVersion::major, LootVersion::minor, LootVersion::patch + 1)); +TEST(IsCompatible, + shouldReturnTrueWithEqualMajorAndMinorVersionsAndUnequalPatchVersion) { + EXPECT_TRUE(IsCompatible( + LootVersion::major, LootVersion::minor, LootVersion::patch + 1)); } -TEST(IsCompatible, shouldReturnFalseWithEqualMajorVersionAndUnequalMinorAndPatchVersions) { - EXPECT_FALSE(IsCompatible(LootVersion::major, LootVersion::minor + 1, LootVersion::patch + 1)); +TEST(IsCompatible, + shouldReturnFalseWithEqualMajorVersionAndUnequalMinorAndPatchVersions) { + EXPECT_FALSE(IsCompatible( + LootVersion::major, LootVersion::minor + 1, LootVersion::patch + 1)); } } } diff --git a/src/tests/api/interface/main.cpp b/src/tests/api/interface/main.cpp index 9e3647b7..a6bdb7bf 100644 --- a/src/tests/api/interface/main.cpp +++ b/src/tests/api/interface/main.cpp @@ -33,7 +33,7 @@ #include int main(int argc, char **argv) { - //Set the locale to get encoding conversions working correctly. + // Set the locale to get encoding conversions working correctly. std::locale::global(boost::locale::generator().generate("")); boost::filesystem::path::imbue(std::locale()); loot::InitialiseLocale(""); @@ -46,15 +46,15 @@ namespace loot { namespace test { TEST(SetLoggingCallback, shouldWriteMessagesToGivenCallback) { std::string loggedMessages; - SetLoggingCallback([&](LogLevel level, const char * string) { + SetLoggingCallback([&](LogLevel level, const char *string) { loggedMessages += std::string(string); }); try { CreateGameHandle(GameType::tes4, "", ""); - } - catch (...) { - EXPECT_EQ("Initialising load order data for game of type 0 at: ", loggedMessages); + } catch (...) { + EXPECT_EQ("Initialising load order data for game of type 0 at: ", + loggedMessages); SetLoggingCallback([](LogLevel, const char *) {}); return; diff --git a/src/tests/api/internals/game/game_cache_test.h b/src/tests/api/internals/game/game_cache_test.h index d073458a..84728223 100644 --- a/src/tests/api/internals/game/game_cache_test.h +++ b/src/tests/api/internals/game/game_cache_test.h @@ -35,9 +35,9 @@ namespace test { class GameCacheTest : public CommonGameTestFixture { protected: GameCacheTest() : - condition("Condition"), - conditionLowercase("condition"), - game_(GetParam(), dataPath.parent_path(), localPath) {} + condition("Condition"), + conditionLowercase("condition"), + game_(GetParam(), dataPath.parent_path(), localPath) {} Game game_; GameCache cache_; @@ -50,21 +50,20 @@ protected: // but we only have the one so no prefix is necessary. // Just test with one game_ because if it works for one it will work for them // all. -INSTANTIATE_TEST_CASE_P(, - GameCacheTest, - ::testing::Values( - GameType::tes5)); +INSTANTIATE_TEST_CASE_P(, GameCacheTest, ::testing::Values(GameType::tes5)); TEST_P(GameCacheTest, gettingATrueConditionShouldReturnATrueTruePair) { EXPECT_NO_THROW(cache_.CacheCondition(condition, true)); - EXPECT_EQ(std::make_pair(true, true), cache_.GetCachedCondition(conditionLowercase)); + EXPECT_EQ(std::make_pair(true, true), + cache_.GetCachedCondition(conditionLowercase)); } TEST_P(GameCacheTest, gettingAFalseConditionShouldReturnAFalseTruePair) { EXPECT_NO_THROW(cache_.CacheCondition(condition, false)); - EXPECT_EQ(std::make_pair(false, true), cache_.GetCachedCondition(conditionLowercase)); + EXPECT_EQ(std::make_pair(false, true), + cache_.GetCachedCondition(conditionLowercase)); } TEST_P(GameCacheTest, gettingANonCachedConditionShouldReturnAFalseFalsePair) { @@ -72,15 +71,28 @@ TEST_P(GameCacheTest, gettingANonCachedConditionShouldReturnAFalseFalsePair) { } TEST_P(GameCacheTest, addingAPluginThatDoesNotExistShouldSucceed) { - cache_.AddPlugin(Plugin(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), blankEsm, true)); + cache_.AddPlugin(Plugin(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + blankEsm, + true)); EXPECT_EQ(blankEsm, cache_.GetPlugin(blankEsm)->GetName()); } -TEST_P(GameCacheTest, addingAPluginThatIsAlreadyCachedShouldOverwriteExistingEntry) { - cache_.AddPlugin(Plugin(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), blankEsm, true)); +TEST_P(GameCacheTest, + addingAPluginThatIsAlreadyCachedShouldOverwriteExistingEntry) { + cache_.AddPlugin(Plugin(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + blankEsm, + true)); EXPECT_EQ(0, cache_.GetPlugin(blankEsm)->GetCRC()); - cache_.AddPlugin(Plugin(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), blankEsm, false)); + cache_.AddPlugin(Plugin(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + blankEsm, + false)); EXPECT_EQ(blankEsmCrc, cache_.GetPlugin(blankEsm)->GetCRC()); } @@ -89,22 +101,37 @@ TEST_P(GameCacheTest, gettingAPluginThatIsNotCachedShouldThrow) { } TEST_P(GameCacheTest, gettingAPluginShouldBeCaseInsensitive) { - cache_.AddPlugin(Plugin(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), blankEsm, true)); + cache_.AddPlugin(Plugin(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + blankEsm, + true)); EXPECT_EQ(blankEsm, cache_.GetPlugin(blankEsm)->GetName()); } -TEST_P(GameCacheTest, gettingPluginsShouldReturnAnEmptySetIfNoPluginsHaveBeenCached) { +TEST_P(GameCacheTest, + gettingPluginsShouldReturnAnEmptySetIfNoPluginsHaveBeenCached) { EXPECT_TRUE(cache_.GetPlugins().empty()); } -TEST_P(GameCacheTest, gettingPluginsShouldReturnASetOfCachedPluginsIfPluginsHaveBeenCached) { - cache_.AddPlugin(Plugin(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), blankEsm, true)); - cache_.AddPlugin(Plugin(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), blankMasterDependentEsm, true)); +TEST_P(GameCacheTest, + gettingPluginsShouldReturnASetOfCachedPluginsIfPluginsHaveBeenCached) { + cache_.AddPlugin(Plugin(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + blankEsm, + true)); + cache_.AddPlugin(Plugin(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + blankMasterDependentEsm, + true)); EXPECT_FALSE(cache_.GetPlugins().empty()); } -TEST_P(GameCacheTest, clearingCachedConditionsShouldNotThrowIfNoConditionsAreCached) { +TEST_P(GameCacheTest, + clearingCachedConditionsShouldNotThrowIfNoConditionsAreCached) { EXPECT_NO_THROW(cache_.ClearCachedConditions()); } @@ -113,7 +140,8 @@ TEST_P(GameCacheTest, clearingCachedConditionsShouldClearAnyCachedConditions) { EXPECT_NO_THROW(cache_.ClearCachedConditions()); - EXPECT_EQ(std::make_pair(false, false), cache_.GetCachedCondition(conditionLowercase)); + EXPECT_EQ(std::make_pair(false, false), + cache_.GetCachedCondition(conditionLowercase)); } TEST_P(GameCacheTest, clearingCachedPluginsShouldNotThrowIfNoPluginsAreCached) { @@ -121,7 +149,11 @@ TEST_P(GameCacheTest, clearingCachedPluginsShouldNotThrowIfNoPluginsAreCached) { } TEST_P(GameCacheTest, clearingCachedPluginsShouldClearAnyCachedPlugins) { - cache_.AddPlugin(Plugin(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), blankEsm, true)); + cache_.AddPlugin(Plugin(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + blankEsm, + true)); cache_.ClearCachedPlugins(); EXPECT_TRUE(cache_.GetPlugins().empty()); diff --git a/src/tests/api/internals/game/game_test.h b/src/tests/api/internals/game/game_test.h index 997445e2..deb90f4f 100644 --- a/src/tests/api/internals/game/game_test.h +++ b/src/tests/api/internals/game/game_test.h @@ -35,17 +35,17 @@ class GameTest : public CommonGameTestFixture { protected: void loadInstalledPlugins(Game& game, bool headersOnly) { const std::vector plugins({ - masterFile, - blankEsm, - blankDifferentEsm, - blankMasterDependentEsm, - blankDifferentMasterDependentEsm, - blankEsp, - blankDifferentEsp, - blankMasterDependentEsp, - blankDifferentMasterDependentEsp, - blankPluginDependentEsp, - blankDifferentPluginDependentEsp, + masterFile, + blankEsm, + blankDifferentEsm, + blankMasterDependentEsm, + blankDifferentMasterDependentEsm, + blankEsp, + blankDifferentEsp, + blankMasterDependentEsp, + blankDifferentMasterDependentEsp, + blankPluginDependentEsp, + blankDifferentPluginDependentEsp, }); game.LoadPlugins(plugins, headersOnly); } @@ -55,13 +55,12 @@ protected: // but we only have the one so no prefix is necessary. INSTANTIATE_TEST_CASE_P(, GameTest, - ::testing::Values( - GameType::tes4, - GameType::tes5, - GameType::fo3, - GameType::fonv, - GameType::fo4, - GameType::tes5se)); + ::testing::Values(GameType::tes4, + GameType::tes5, + GameType::fo3, + GameType::fonv, + GameType::fo4, + GameType::tes5se)); TEST_P(GameTest, constructingShouldStoreTheGivenValues) { Game game = Game(GetParam(), dataPath.parent_path(), localPath); @@ -71,8 +70,8 @@ TEST_P(GameTest, constructingShouldStoreTheGivenValues) { } #ifndef _WIN32 - // Testing on Windows will find real game installs in the Registry, so cannot - // test autodetection fully unless on Linux. +// Testing on Windows will find real game installs in the Registry, so cannot +// test autodetection fully unless on Linux. TEST_P(GameTest, constructingShouldThrowOnLinuxIfGamePathIsNotGiven) { EXPECT_THROW(Game(GetParam(), "", localPath), std::invalid_argument); } @@ -90,7 +89,9 @@ TEST_P(GameTest, constructingShouldNotThrowIfGameAndLocalPathsAreNotEmpty) { EXPECT_NO_THROW(Game(GetParam(), dataPath.parent_path(), localPath)); } -TEST_P(GameTest, loadPluginsWithHeadersOnlyTrueShouldLoadTheHeadersOfAllInstalledPlugins) { +TEST_P( + GameTest, + loadPluginsWithHeadersOnlyTrueShouldLoadTheHeadersOfAllInstalledPlugins) { Game game = Game(GetParam(), dataPath.parent_path(), localPath); EXPECT_NO_THROW(loadInstalledPlugins(game, true)); @@ -108,14 +109,16 @@ TEST_P(GameTest, loadPluginsWithHeadersOnlyTrueShouldLoadTheHeadersOfAllInstalle TEST_P(GameTest, loadPluginsWithANonPluginShouldNotAddItToTheLoadedPlugins) { Game game = Game(GetParam(), dataPath.parent_path(), localPath); - ASSERT_THROW(game.LoadPlugins({ nonPluginFile }, false), std::invalid_argument); + ASSERT_THROW(game.LoadPlugins({nonPluginFile}, false), std::invalid_argument); ASSERT_TRUE(game.GetLoadedPlugins().empty()); } -TEST_P(GameTest, loadPluginsWithAnInvalidPluginShouldNotAddItToTheLoadedPlugins) { +TEST_P(GameTest, + loadPluginsWithAnInvalidPluginShouldNotAddItToTheLoadedPlugins) { ASSERT_FALSE(boost::filesystem::exists(dataPath / invalidPlugin)); - ASSERT_NO_THROW(boost::filesystem::copy_file(dataPath / blankEsm, dataPath / invalidPlugin)); + ASSERT_NO_THROW(boost::filesystem::copy_file(dataPath / blankEsm, + dataPath / invalidPlugin)); ASSERT_TRUE(boost::filesystem::exists(dataPath / invalidPlugin)); boost::filesystem::ofstream out(dataPath / invalidPlugin, std::fstream::app); out << "GRUP0"; @@ -123,12 +126,13 @@ TEST_P(GameTest, loadPluginsWithAnInvalidPluginShouldNotAddItToTheLoadedPlugins) Game game = Game(GetParam(), dataPath.parent_path(), localPath); - ASSERT_NO_THROW(game.LoadPlugins({ invalidPlugin }, false)); + ASSERT_NO_THROW(game.LoadPlugins({invalidPlugin}, false)); ASSERT_TRUE(game.GetLoadedPlugins().empty()); } -TEST_P(GameTest, loadPluginsWithHeadersOnlyFalseShouldFullyLoadAllInstalledPlugins) { +TEST_P(GameTest, + loadPluginsWithHeadersOnlyFalseShouldFullyLoadAllInstalledPlugins) { Game game = Game(GetParam(), dataPath.parent_path(), localPath); EXPECT_NO_THROW(loadInstalledPlugins(game, false)); diff --git a/src/tests/api/internals/game/load_order_handler_test.h b/src/tests/api/internals/game/load_order_handler_test.h index 6ade2fd2..3b60e35a 100644 --- a/src/tests/api/internals/game/load_order_handler_test.h +++ b/src/tests/api/internals/game/load_order_handler_test.h @@ -33,26 +33,26 @@ namespace loot { namespace test { class LoadOrderHandlerTest : public CommonGameTestFixture { protected: - LoadOrderHandlerTest() : loadOrderToSet_({ - masterFile, - blankEsm, - blankMasterDependentEsm, - blankDifferentEsm, - blankDifferentMasterDependentEsm, - blankDifferentEsp, - blankDifferentPluginDependentEsp, - blankEsp, - blankMasterDependentEsp, - blankDifferentMasterDependentEsp, - blankPluginDependentEsp, - }) {} + LoadOrderHandlerTest() : + loadOrderToSet_({ + masterFile, + blankEsm, + blankMasterDependentEsm, + blankDifferentEsm, + blankDifferentMasterDependentEsm, + blankDifferentEsp, + blankDifferentPluginDependentEsp, + blankEsp, + blankMasterDependentEsp, + blankDifferentMasterDependentEsp, + blankPluginDependentEsp, + }) {} - void TearDown() { - CommonGameTestFixture::TearDown(); - } + void TearDown() { CommonGameTestFixture::TearDown(); } void initialiseHandler() { - ASSERT_NO_THROW(loadOrderHandler_.Init(GetParam(), dataPath.parent_path(), localPath)); + ASSERT_NO_THROW( + loadOrderHandler_.Init(GetParam(), dataPath.parent_path(), localPath)); } LoadOrderHandler loadOrderHandler_; @@ -63,36 +63,42 @@ protected: // but we only have the one so no prefix is necessary. INSTANTIATE_TEST_CASE_P(, LoadOrderHandlerTest, - ::testing::Values( - GameType::tes4, - GameType::tes5, - GameType::fo3, - GameType::fonv, - GameType::fo4, - GameType::tes5se)); + ::testing::Values(GameType::tes4, + GameType::tes5, + GameType::fo3, + GameType::fonv, + GameType::fo4, + GameType::tes5se)); TEST_P(LoadOrderHandlerTest, initShouldThrowIfNoGamePathIsSet) { EXPECT_THROW(loadOrderHandler_.Init(GetParam(), ""), std::invalid_argument); EXPECT_THROW(loadOrderHandler_.Init(GetParam(), ""), std::invalid_argument); - EXPECT_THROW(loadOrderHandler_.Init(GetParam(), "", localPath), std::invalid_argument); - EXPECT_THROW(loadOrderHandler_.Init(GetParam(), "", localPath), std::invalid_argument); + EXPECT_THROW(loadOrderHandler_.Init(GetParam(), "", localPath), + std::invalid_argument); + EXPECT_THROW(loadOrderHandler_.Init(GetParam(), "", localPath), + std::invalid_argument); } #ifndef _WIN32 TEST_P(LoadOrderHandlerTest, initShouldThrowOnLinuxIfNoLocalPathIsSet) { - EXPECT_THROW(loadOrderHandler_.Init(GetParam(), dataPath.parent_path()), std::system_error); + EXPECT_THROW(loadOrderHandler_.Init(GetParam(), dataPath.parent_path()), + std::system_error); } #endif -TEST_P(LoadOrderHandlerTest, initShouldNotThrowIfAValidGameIdAndGamePathAndLocalPathAreSet) { - EXPECT_NO_THROW(loadOrderHandler_.Init(GetParam(), dataPath.parent_path(), localPath)); +TEST_P(LoadOrderHandlerTest, + initShouldNotThrowIfAValidGameIdAndGamePathAndLocalPathAreSet) { + EXPECT_NO_THROW( + loadOrderHandler_.Init(GetParam(), dataPath.parent_path(), localPath)); } -TEST_P(LoadOrderHandlerTest, isPluginActiveShouldThrowIfTheHandlerHasNotBeenInitialised) { +TEST_P(LoadOrderHandlerTest, + isPluginActiveShouldThrowIfTheHandlerHasNotBeenInitialised) { EXPECT_THROW(loadOrderHandler_.IsPluginActive(masterFile), std::system_error); } -TEST_P(LoadOrderHandlerTest, isPluginActiveShouldReturnFalseIfLoadOrderStateHasNotBeenLoaded) { +TEST_P(LoadOrderHandlerTest, + isPluginActiveShouldReturnFalseIfLoadOrderStateHasNotBeenLoaded) { initialiseHandler(); EXPECT_FALSE(loadOrderHandler_.IsPluginActive(masterFile)); @@ -100,7 +106,8 @@ TEST_P(LoadOrderHandlerTest, isPluginActiveShouldReturnFalseIfLoadOrderStateHasN EXPECT_FALSE(loadOrderHandler_.IsPluginActive(blankEsp)); } -TEST_P(LoadOrderHandlerTest, isPluginActiveShouldReturnCorrectPluginStatesAfterInitialisation) { +TEST_P(LoadOrderHandlerTest, + isPluginActiveShouldReturnCorrectPluginStatesAfterInitialisation) { initialiseHandler(); loadOrderHandler_.LoadCurrentState(); @@ -109,11 +116,13 @@ TEST_P(LoadOrderHandlerTest, isPluginActiveShouldReturnCorrectPluginStatesAfterI EXPECT_FALSE(loadOrderHandler_.IsPluginActive(blankEsp)); } -TEST_P(LoadOrderHandlerTest, getLoadOrderShouldThrowIfTheHandlerHasNotBeenInitialised) { +TEST_P(LoadOrderHandlerTest, + getLoadOrderShouldThrowIfTheHandlerHasNotBeenInitialised) { EXPECT_THROW(loadOrderHandler_.GetLoadOrder(), std::system_error); } -TEST_P(LoadOrderHandlerTest, getLoadOrderShouldReturnAnEmptyVectorIfStateHasNotBeenLoaded) { +TEST_P(LoadOrderHandlerTest, + getLoadOrderShouldReturnAnEmptyVectorIfStateHasNotBeenLoaded) { initialiseHandler(); EXPECT_TRUE(loadOrderHandler_.GetLoadOrder().empty()); @@ -126,8 +135,10 @@ TEST_P(LoadOrderHandlerTest, getLoadOrderShouldReturnTheCurrentLoadOrder) { ASSERT_EQ(getLoadOrder(), loadOrderHandler_.GetLoadOrder()); } -TEST_P(LoadOrderHandlerTest, setLoadOrderShouldThrowIfTheHandlerHasNotBeenInitialised) { - EXPECT_THROW(loadOrderHandler_.SetLoadOrder(loadOrderToSet_), std::system_error); +TEST_P(LoadOrderHandlerTest, + setLoadOrderShouldThrowIfTheHandlerHasNotBeenInitialised) { + EXPECT_THROW(loadOrderHandler_.SetLoadOrder(loadOrderToSet_), + std::system_error); } TEST_P(LoadOrderHandlerTest, setLoadOrderShouldSetTheLoadOrder) { diff --git a/src/tests/api/internals/helpers/crc_test.h b/src/tests/api/internals/helpers/crc_test.h index 89e09fd3..b63ee57b 100644 --- a/src/tests/api/internals/helpers/crc_test.h +++ b/src/tests/api/internals/helpers/crc_test.h @@ -38,10 +38,7 @@ class GetCrc32Test : public CommonGameTestFixture {}; // but we only have the one so no prefix is necessary. // Just test with one game because if it works for one it will work for them // all. -INSTANTIATE_TEST_CASE_P(, - GetCrc32Test, - ::testing::Values( - GameType::tes5)); +INSTANTIATE_TEST_CASE_P(, GetCrc32Test, ::testing::Values(GameType::tes5)); TEST_P(GetCrc32Test, gettingTheCrcOfAMissingFileShouldThrow) { EXPECT_THROW(GetCrc32(dataPath / missingEsp), FileAccessError); diff --git a/src/tests/api/internals/helpers/git_helper_test.h b/src/tests/api/internals/helpers/git_helper_test.h index bec2377d..06c23c55 100644 --- a/src/tests/api/internals/helpers/git_helper_test.h +++ b/src/tests/api/internals/helpers/git_helper_test.h @@ -35,17 +35,20 @@ namespace loot { namespace test { class GitHelperTest : public ::testing::Test { protected: - GitHelperTest() : - parentRepoRoot(GetRepoRoot()) {} + GitHelperTest() : parentRepoRoot(GetRepoRoot()) {} inline void SetUp() { ASSERT_TRUE(boost::filesystem::exists(parentRepoRoot / "README.md")); // Create a backup of CONTRIBUTING.md. ASSERT_TRUE(boost::filesystem::exists(parentRepoRoot / "CONTRIBUTING.md")); - ASSERT_FALSE(boost::filesystem::exists(parentRepoRoot / "CONTRIBUTING.md.copy")); - ASSERT_NO_THROW(boost::filesystem::copy(parentRepoRoot / "CONTRIBUTING.md", parentRepoRoot / "CONTRIBUTING.md.copy")); - ASSERT_TRUE(boost::filesystem::exists(parentRepoRoot / "CONTRIBUTING.md.copy")); + ASSERT_FALSE( + boost::filesystem::exists(parentRepoRoot / "CONTRIBUTING.md.copy")); + ASSERT_NO_THROW( + boost::filesystem::copy(parentRepoRoot / "CONTRIBUTING.md", + parentRepoRoot / "CONTRIBUTING.md.copy")); + ASSERT_TRUE( + boost::filesystem::exists(parentRepoRoot / "CONTRIBUTING.md.copy")); // Edit CONTRIBUTING.md boost::filesystem::ofstream out(parentRepoRoot / "CONTRIBUTING.md"); @@ -53,11 +56,15 @@ protected: } inline void TearDown() { - // Restore original CONTRIBUTING.md - ASSERT_NO_THROW(boost::filesystem::remove(parentRepoRoot / "CONTRIBUTING.md")); - ASSERT_NO_THROW(boost::filesystem::rename(parentRepoRoot / "CONTRIBUTING.md.copy", parentRepoRoot / "CONTRIBUTING.md")); + // Restore original CONTRIBUTING.md + ASSERT_NO_THROW( + boost::filesystem::remove(parentRepoRoot / "CONTRIBUTING.md")); + ASSERT_NO_THROW( + boost::filesystem::rename(parentRepoRoot / "CONTRIBUTING.md.copy", + parentRepoRoot / "CONTRIBUTING.md")); ASSERT_TRUE(boost::filesystem::exists(parentRepoRoot / "CONTRIBUTING.md")); - ASSERT_FALSE(boost::filesystem::exists(parentRepoRoot / "CONTRIBUTING.md.copy")); + ASSERT_FALSE( + boost::filesystem::exists(parentRepoRoot / "CONTRIBUTING.md.copy")); } GitHelper git_; @@ -82,7 +89,7 @@ TEST_F(GitHelperTest, repoShouldInitialiseAsANullPointer) { TEST_F(GitHelperTest, destructorShouldCallLibgit2CleanupFunction) { ASSERT_EQ(2, git_libgit2_init()); - GitHelper * gitPointer = new GitHelper(); + GitHelper* gitPointer = new GitHelper(); ASSERT_EQ(4, git_libgit2_init()); delete gitPointer; @@ -107,20 +114,25 @@ TEST_F(GitHelperTest, isRepositoryShouldReturnFalseForRepositorySubdirectory) { } TEST_F(GitHelperTest, isFileDifferentShouldThrowIfGivenANonRepositoryPath) { - EXPECT_THROW(GitHelper::IsFileDifferent(boost::filesystem::current_path(), "README.md"), GitStateError); + EXPECT_THROW(GitHelper::IsFileDifferent(boost::filesystem::current_path(), + "README.md"), + GitStateError); } TEST_F(GitHelperTest, isFileDifferentShouldReturnFalseForAnUntrackedFile) { - // New files not in the index are not tracked by Git, so aren't considered - // different. - EXPECT_FALSE(GitHelper::IsFileDifferent(parentRepoRoot, "CONTRIBUTING.md.copy")); + // New files not in the index are not tracked by Git, so aren't considered + // different. + EXPECT_FALSE( + GitHelper::IsFileDifferent(parentRepoRoot, "CONTRIBUTING.md.copy")); } -TEST_F(GitHelperTest, isFileDifferentShouldReturnFalseForAnUnchangedTrackedFile) { +TEST_F(GitHelperTest, + isFileDifferentShouldReturnFalseForAnUnchangedTrackedFile) { EXPECT_FALSE(GitHelper::IsFileDifferent(parentRepoRoot, "README.md")); } -TEST_F(GitHelperTest, DISABLED_isFileDifferentShouldReturnTrueForAChangedTrackedFile) { +TEST_F(GitHelperTest, + DISABLED_isFileDifferentShouldReturnTrueForAChangedTrackedFile) { EXPECT_TRUE(GitHelper::IsFileDifferent(parentRepoRoot, "CONTRIBUTING.md")); } } diff --git a/src/tests/api/internals/helpers/version_test.h b/src/tests/api/internals/helpers/version_test.h index 634419b0..d7e6b83e 100644 --- a/src/tests/api/internals/helpers/version_test.h +++ b/src/tests/api/internals/helpers/version_test.h @@ -34,7 +34,7 @@ namespace loot { namespace test { #ifdef _WIN32 TEST(Version, shouldExtractVersionFromApiDll) { - // Use the API DLL built. + // Use the API DLL built. Version version(boost::filesystem::path("loot_api.dll")); std::string expected(LootVersion::string() + ".0"); EXPECT_EQ(expected, version.AsString()); @@ -64,7 +64,8 @@ TEST(Version, shouldExtractASemanticVersion) { EXPECT_EQ("1.0.0-x.7.z.92", version.AsString()); } -TEST(Version, shouldExtractAPseudosemExtendedVersionStoppingAtTheFirstSpaceSeparator) { +TEST(Version, + shouldExtractAPseudosemExtendedVersionStoppingAtTheFirstSpaceSeparator) { Version version(std::string("01.0.0_alpha:1-2 3")); EXPECT_EQ("01.0.0_alpha:1-2", version.AsString()); } @@ -80,84 +81,91 @@ TEST(Version, shouldBeEmptyIfInputStringContainedNoVersion) { } TEST(Version, shouldExtractTimestampWithForwardslashDateSeparators) { - // Found in a Bashed Patch. Though the timestamp isn't useful to - // LOOT, it is semantically a version, and extracting it is far - // easier than trying to skip it and the number of records changed. - Version version(std::string("Updated: 10/09/2016 13:15:18\r\n\r\nRecords Changed: 43")); + // Found in a Bashed Patch. Though the timestamp isn't useful to + // LOOT, it is semantically a version, and extracting it is far + // easier than trying to skip it and the number of records changed. + Version version( + std::string("Updated: 10/09/2016 13:15:18\r\n\r\nRecords Changed: 43")); EXPECT_EQ("10/09/2016 13:15:18", version.AsString()); } TEST(Version, shouldNotExtractTrailingPeriods) { - // Found in . + // Found in . Version version(std::string("Version 0.2.")); EXPECT_EQ("0.2", version.AsString()); } TEST(Version, shouldExtractVersionAfterTextWhenPrecededByVersionColonString) { - // Found in . + // Found in . std::string testText("Legendary Edition\r\n\r\nVersion: 3.0.0"); EXPECT_EQ("3.0.0", Version(testText).AsString()); } TEST(Version, shouldIgnoreNumbersContainingCommas) { - // Found in . + // Found in . std::string testText("fixing over 2,300 bugs so far! Version: 3.5.3"); EXPECT_EQ("3.5.3", Version(testText).AsString()); } TEST(Version, shouldExtractVersionBeforeText) { - // Found in . + // Found in . std::string testText("Version: 2.1 The Unofficial Fallout 3 Patch"); EXPECT_EQ("2.1", Version(testText).AsString()); } TEST(Version, shouldExtractVersionWithPrecedingV) { - // Found in . + // Found in . std::string testText("V2.11\r\n\r\n{{BASH:Invent}}"); EXPECT_EQ("2.11", Version(testText).AsString()); } TEST(Version, shouldExtractVersionWithPrecedingColonPeriodWhitespace) { - // Found in . + // Found in . std::string testText("Version:. 1.09"); EXPECT_EQ("1.09", Version(testText).AsString()); } TEST(Version, shouldExtractVersionWithLettersImmediatelyAfterNumbers) { - // Found in . - std::string testText("comprehensive bugfixing mod for The Elder Scrolls V: Skyrim\r\n\r\nVersion: 2.1.3b\r\n\r\n"); + // Found in . + std::string testText( + "comprehensive bugfixing mod for The Elder Scrolls V: " + "Skyrim\r\n\r\nVersion: 2.1.3b\r\n\r\n"); EXPECT_EQ("2.1.3b", Version(testText).AsString()); } TEST(Version, shouldExtractVersionWithPeriodAndNoPrecedingIdentifier) { - // Found in . + // Found in . std::string testText("SkyUI 5.1"); EXPECT_EQ("5.1", Version(testText).AsString()); } TEST(Version, shouldNotExtractSingleDigitInSentence) { - // Found in . - std::string testText("Adds 8 variants of Triss Merigold's outfit from \"The Witcher 2\""); + // Found in . + std::string testText( + "Adds 8 variants of Triss Merigold's outfit from \"The Witcher 2\""); EXPECT_EQ("", Version(testText).AsString()); } TEST(Version, shouldPreferVersionPrefixedNumbersOverVersionsInSentence) { - // Found in - std::string testText("Requires Skyrim patch 1.9.32.0.8 or greater.\n" - "Requires Unofficial Skyrim Legendary Edition Patch 3.0.0 or greater.\n" - "Version 2.0.0"); + // Found in + std::string testText( + "Requires Skyrim patch 1.9.32.0.8 or greater.\n" + "Requires Unofficial Skyrim Legendary Edition Patch 3.0.0 or greater.\n" + "Version 2.0.0"); EXPECT_EQ("2.0.0", Version(testText).AsString()); } TEST(Version, shouldExtractSingleDigitVersionPrecededByV) { - // Found in + // Found in std::string testText("Immersive Armors v8 Main Plugin"); EXPECT_EQ("8", Version(testText).AsString()); } TEST(Version, shouldPreferVersionPrefixedNumbersOverVPrefixedNumber) { - // Found in - std::string testText("Compatibility patch for AOS v2.5 and True Storms v1.5 (or later),\nPatch Version: 1.0"); + // Found in + std::string testText( + "Compatibility patch for AOS v2.5 and True Storms v1.5 (or " + "later),\nPatch Version: 1.0"); EXPECT_EQ("1.0", Version(testText).AsString()); } diff --git a/src/tests/api/internals/helpers/yaml_set_helpers_test.h b/src/tests/api/internals/helpers/yaml_set_helpers_test.h index 874b1bba..e66f80ec 100644 --- a/src/tests/api/internals/helpers/yaml_set_helpers_test.h +++ b/src/tests/api/internals/helpers/yaml_set_helpers_test.h @@ -79,7 +79,8 @@ protected: return false; } - static bool isSequenceOf(const std::string& sequence, const std::vector& values) { + static bool isSequenceOf(const std::string& sequence, + const std::vector& values) { std::set sortedValues(std::begin(values), std::end(values)); std::set found; @@ -107,17 +108,20 @@ TEST_F(unordered_set, encodingAsYamlShouldStoreAllValuesInUndefinedOrder) { TEST_F(unordered_set, decodingFromAYamlListShouldStoreValuesCorrectly) { YAML::Node node = YAML::Load("[a, b, c]"); - std::unordered_set stringSet = node.as>(); + std::unordered_set stringSet = + node.as>(); EXPECT_EQ(1, stringSet.count("a")); EXPECT_EQ(1, stringSet.count("b")); EXPECT_EQ(1, stringSet.count("c")); } -TEST_F(unordered_set, decodingFromAYamlListThatContainsDuplicateElementsShouldThrow) { +TEST_F(unordered_set, + decodingFromAYamlListThatContainsDuplicateElementsShouldThrow) { YAML::Node node = YAML::Load("[a, b, c, c]"); - EXPECT_THROW(node.as>(), YAML::RepresentationException); + EXPECT_THROW(node.as>(), + YAML::RepresentationException); } TEST_F(unordered_set, emittingAsYamlShouldOutputAYamlListContainingAllValues) { diff --git a/src/tests/api/internals/main.cpp b/src/tests/api/internals/main.cpp index 82b1baa2..11e8d67e 100644 --- a/src/tests/api/internals/main.cpp +++ b/src/tests/api/internals/main.cpp @@ -24,35 +24,35 @@ #include -#include "tests/api/internals/game/game_test.h" #include "tests/api/internals/game/game_cache_test.h" +#include "tests/api/internals/game/game_test.h" #include "tests/api/internals/game/load_order_handler_test.h" #include "tests/api/internals/helpers/crc_test.h" #include "tests/api/internals/helpers/git_helper_test.h" #include "tests/api/internals/helpers/version_test.h" #include "tests/api/internals/helpers/yaml_set_helpers_test.h" +#include "tests/api/internals/masterlist_test.h" #include "tests/api/internals/metadata/condition_evaluator_test.h" #include "tests/api/internals/metadata/condition_grammar_test.h" #include "tests/api/internals/metadata/conditional_metadata_test.h" #include "tests/api/internals/metadata/file_test.h" #include "tests/api/internals/metadata/location_test.h" -#include "tests/api/internals/metadata/message_test.h" #include "tests/api/internals/metadata/message_content_test.h" +#include "tests/api/internals/metadata/message_test.h" #include "tests/api/internals/metadata/plugin_cleaning_data_test.h" #include "tests/api/internals/metadata/plugin_metadata_test.h" #include "tests/api/internals/metadata/priority_test.h" #include "tests/api/internals/metadata/tag_test.h" -#include "tests/api/internals/plugin/plugin_test.h" -#include "tests/api/internals/plugin/plugin_sorter_test.h" -#include "tests/api/internals/masterlist_test.h" #include "tests/api/internals/metadata_list_test.h" +#include "tests/api/internals/plugin/plugin_sorter_test.h" +#include "tests/api/internals/plugin/plugin_test.h" TEST(ModuloOperator, shouldConformToTheCpp11Standard) { - // C++11 defines the modulo operator more strongly - // (only x % 0 is left undefined), whereas C++03 - // only defined the operator for positive first operand. - // Test that the modulo operator has been implemented - // according to C++11. + // C++11 defines the modulo operator more strongly + // (only x % 0 is left undefined), whereas C++03 + // only defined the operator for positive first operand. + // Test that the modulo operator has been implemented + // according to C++11. EXPECT_EQ(0, 20 % 5); EXPECT_EQ(0, 20 % -5); @@ -66,7 +66,7 @@ TEST(ModuloOperator, shouldConformToTheCpp11Standard) { } int main(int argc, char **argv) { - //Set the locale to get encoding conversions working correctly. + // Set the locale to get encoding conversions working correctly. std::locale::global(boost::locale::generator().generate("")); boost::filesystem::path::imbue(std::locale()); diff --git a/src/tests/api/internals/masterlist_test.h b/src/tests/api/internals/masterlist_test.h index 63aa8059..1c20de9b 100644 --- a/src/tests/api/internals/masterlist_test.h +++ b/src/tests/api/internals/masterlist_test.h @@ -34,10 +34,10 @@ namespace test { class MasterlistTest : public CommonGameTestFixture { protected: MasterlistTest() : - repoBranch("master"), - oldBranch("old-branch"), - repoUrl("https://github.com/loot/testing-metadata.git"), - masterlistPath(localPath / "masterlist.yaml") {} + repoBranch("master"), + oldBranch("old-branch"), + repoUrl("https://github.com/loot/testing-metadata.git"), + masterlistPath(localPath / "masterlist.yaml") {} void SetUp() { CommonGameTestFixture::SetUp(); @@ -63,38 +63,39 @@ protected: // but we only have the one so no prefix is necessary. INSTANTIATE_TEST_CASE_P(, MasterlistTest, - ::testing::Values( - GameType::tes4, - GameType::tes5, - GameType::fo3, - GameType::fonv, - GameType::fo4, - GameType::tes5se)); + ::testing::Values(GameType::tes4, + GameType::tes5, + GameType::fo3, + GameType::fonv, + GameType::fo4, + GameType::tes5se)); TEST_P(MasterlistTest, updateShouldThrowIfAnInvalidPathIsGiven) { Masterlist masterlist; - EXPECT_THROW(masterlist.Update(";//\?", repoUrl, repoBranch), boost::filesystem::filesystem_error); + EXPECT_THROW(masterlist.Update(";//\?", repoUrl, repoBranch), + boost::filesystem::filesystem_error); } TEST_P(MasterlistTest, updateShouldThrowIfABlankPathIsGiven) { Masterlist masterlist; - EXPECT_THROW(masterlist.Update("", repoUrl, repoBranch), boost::filesystem::filesystem_error); + EXPECT_THROW(masterlist.Update("", repoUrl, repoBranch), + boost::filesystem::filesystem_error); } TEST_P(MasterlistTest, updateShouldThrowIfABranchThatDoesNotExistIsGiven) { Masterlist masterlist; - EXPECT_THROW(masterlist.Update(masterlistPath, - repoUrl, - "missing-branch"), std::system_error); + EXPECT_THROW(masterlist.Update(masterlistPath, repoUrl, "missing-branch"), + std::system_error); } TEST_P(MasterlistTest, updateShouldThrowIfABlankBranchIsGiven) { Masterlist masterlist; - EXPECT_THROW(masterlist.Update(masterlistPath, repoUrl, ""), std::invalid_argument); + EXPECT_THROW(masterlist.Update(masterlistPath, repoUrl, ""), + std::invalid_argument); } TEST_P(MasterlistTest, updateShouldThrowIfAUrlThatDoesNotExistIsGiven) { @@ -102,34 +103,31 @@ TEST_P(MasterlistTest, updateShouldThrowIfAUrlThatDoesNotExistIsGiven) { EXPECT_THROW(masterlist.Update(masterlistPath, "https://github.com/loot/does-not-exist.git", - repoBranch), std::system_error); + repoBranch), + std::system_error); } TEST_P(MasterlistTest, updateShouldThrowIfABlankUrlIsGiven) { Masterlist masterlist; - EXPECT_THROW(masterlist.Update(masterlistPath, "", repoBranch), std::invalid_argument); + EXPECT_THROW(masterlist.Update(masterlistPath, "", repoBranch), + std::invalid_argument); } TEST_P(MasterlistTest, updateShouldReturnTrueIfNoMasterlistExists) { Masterlist masterlist; - EXPECT_TRUE(masterlist.Update(masterlistPath, - repoUrl, - repoBranch)); + EXPECT_TRUE(masterlist.Update(masterlistPath, repoUrl, repoBranch)); } TEST_P(MasterlistTest, updateShouldReturnFalseIfAnUpToDateMasterlistExists) { Masterlist masterlist; - EXPECT_TRUE(masterlist.Update(masterlistPath, - repoUrl, - repoBranch)); + EXPECT_TRUE(masterlist.Update(masterlistPath, repoUrl, repoBranch)); - EXPECT_FALSE(masterlist.Update(masterlistPath, - repoUrl, - repoBranch)); + EXPECT_FALSE(masterlist.Update(masterlistPath, repoUrl, repoBranch)); } -TEST_P(MasterlistTest, updateShouldDiscardLocalHistoryIfRemoteHistoryIsDifferent) { +TEST_P(MasterlistTest, + updateShouldDiscardLocalHistoryIfRemoteHistoryIsDifferent) { Masterlist masterlist; ASSERT_TRUE(masterlist.Update(masterlistPath, repoUrl, repoBranch)); @@ -146,18 +144,20 @@ TEST_P(MasterlistTest, getInfoShouldThrowIfNoMasterlistExistsAtTheGivenPath) { EXPECT_THROW(masterlist.GetInfo(masterlistPath, false), FileAccessError); } -TEST_P(MasterlistTest, getInfoShouldThrowIfTheGivenPathDoesNotBelongToAGitRepository) { - ASSERT_NO_THROW(boost::filesystem::copy("./testing-metadata/masterlist.yaml", masterlistPath)); +TEST_P(MasterlistTest, + getInfoShouldThrowIfTheGivenPathDoesNotBelongToAGitRepository) { + ASSERT_NO_THROW(boost::filesystem::copy("./testing-metadata/masterlist.yaml", + masterlistPath)); Masterlist masterlist; EXPECT_THROW(masterlist.GetInfo(masterlistPath, false), GitStateError); } -TEST_P(MasterlistTest, getInfoShouldReturnRevisionAndDateStringsOfTheCorrectLengthsWhenRequestingALongId) { +TEST_P( + MasterlistTest, + getInfoShouldReturnRevisionAndDateStringsOfTheCorrectLengthsWhenRequestingALongId) { Masterlist masterlist; - ASSERT_TRUE(masterlist.Update(masterlistPath, - repoUrl, - repoBranch)); + ASSERT_TRUE(masterlist.Update(masterlistPath, repoUrl, repoBranch)); MasterlistInfo info = masterlist.GetInfo(masterlistPath, false); EXPECT_EQ(40, info.revision_id.length()); @@ -165,11 +165,11 @@ TEST_P(MasterlistTest, getInfoShouldReturnRevisionAndDateStringsOfTheCorrectLeng EXPECT_FALSE(info.is_modified); } -TEST_P(MasterlistTest, getInfoShouldReturnRevisionAndDateStringsOfTheCorrectLengthsWhenRequestingAShortId) { +TEST_P( + MasterlistTest, + getInfoShouldReturnRevisionAndDateStringsOfTheCorrectLengthsWhenRequestingAShortId) { Masterlist masterlist; - ASSERT_TRUE(masterlist.Update(masterlistPath, - repoUrl, - repoBranch)); + ASSERT_TRUE(masterlist.Update(masterlistPath, repoUrl, repoBranch)); MasterlistInfo info = masterlist.GetInfo(masterlistPath, true); EXPECT_GE((unsigned)40, info.revision_id.length()); @@ -178,11 +178,11 @@ TEST_P(MasterlistTest, getInfoShouldReturnRevisionAndDateStringsOfTheCorrectLeng EXPECT_FALSE(info.is_modified); } -TEST_P(MasterlistTest, getInfoShouldAppendSuffixesToReturnedStringsIfTheMasterlistHasBeenEdited) { +TEST_P( + MasterlistTest, + getInfoShouldAppendSuffixesToReturnedStringsIfTheMasterlistHasBeenEdited) { Masterlist masterlist; - ASSERT_TRUE(masterlist.Update(masterlistPath, - repoUrl, - repoBranch)); + ASSERT_TRUE(masterlist.Update(masterlistPath, repoUrl, repoBranch)); boost::filesystem::ofstream out(masterlistPath); out.close(); @@ -192,35 +192,35 @@ TEST_P(MasterlistTest, getInfoShouldAppendSuffixesToReturnedStringsIfTheMasterli EXPECT_TRUE(info.is_modified); } -TEST_P(MasterlistTest, isLatestShouldThrowIfTheGivenPathDoesNotBelongToAGitRepository) { - ASSERT_NO_THROW(boost::filesystem::copy("./testing-metadata/masterlist.yaml", masterlistPath)); +TEST_P(MasterlistTest, + isLatestShouldThrowIfTheGivenPathDoesNotBelongToAGitRepository) { + ASSERT_NO_THROW(boost::filesystem::copy("./testing-metadata/masterlist.yaml", + masterlistPath)); EXPECT_THROW(Masterlist::IsLatest(masterlistPath, repoBranch), GitStateError); } TEST_P(MasterlistTest, isLatestShouldThrowIfTheGivenBranchIsAnEmptyString) { Masterlist masterlist; - ASSERT_TRUE(masterlist.Update(masterlistPath, - repoUrl, - repoBranch)); + ASSERT_TRUE(masterlist.Update(masterlistPath, repoUrl, repoBranch)); EXPECT_THROW(Masterlist::IsLatest(masterlistPath, ""), std::invalid_argument); } -TEST_P(MasterlistTest, isLatestShouldReturnFalseIfTheCurrentRevisionIsNotTheLatestRevisionInTheGivenBranch) { +TEST_P( + MasterlistTest, + isLatestShouldReturnFalseIfTheCurrentRevisionIsNotTheLatestRevisionInTheGivenBranch) { Masterlist masterlist; - ASSERT_TRUE(masterlist.Update(masterlistPath, - repoUrl, - oldBranch)); + ASSERT_TRUE(masterlist.Update(masterlistPath, repoUrl, oldBranch)); EXPECT_FALSE(Masterlist::IsLatest(masterlistPath, repoBranch)); } -TEST_P(MasterlistTest, isLatestShouldReturnTrueIfTheCurrentRevisionIsTheLatestRevisioninTheGivenBranch) { +TEST_P( + MasterlistTest, + isLatestShouldReturnTrueIfTheCurrentRevisionIsTheLatestRevisioninTheGivenBranch) { Masterlist masterlist; - ASSERT_TRUE(masterlist.Update(masterlistPath, - repoUrl, - repoBranch)); + ASSERT_TRUE(masterlist.Update(masterlistPath, repoUrl, repoBranch)); EXPECT_TRUE(Masterlist::IsLatest(masterlistPath, repoBranch)); } diff --git a/src/tests/api/internals/metadata/condition_evaluator_test.h b/src/tests/api/internals/metadata/condition_evaluator_test.h index 3201feb4..f42c8571 100644 --- a/src/tests/api/internals/metadata/condition_evaluator_test.h +++ b/src/tests/api/internals/metadata/condition_evaluator_test.h @@ -35,11 +35,14 @@ namespace test { class ConditionEvaluatorTest : public CommonGameTestFixture { protected: ConditionEvaluatorTest() : - info_(std::vector({ - MessageContent("info"), - })), - game_(GetParam(), dataPath.parent_path(), localPath), - evaluator_(game_.Type(), game_.DataPath(), game_.GetCache(), game_.GetLoadOrderHandler()) {} + info_(std::vector({ + MessageContent("info"), + })), + game_(GetParam(), dataPath.parent_path(), localPath), + evaluator_(game_.Type(), + game_.DataPath(), + game_.GetCache(), + game_.GetLoadOrderHandler()) {} const std::vector info_; @@ -51,15 +54,15 @@ protected: // but we only have the one so no prefix is necessary. INSTANTIATE_TEST_CASE_P(, ConditionEvaluatorTest, - ::testing::Values( - GameType::tes4, - GameType::tes5, - GameType::fo3, - GameType::fonv, - GameType::fo4, - GameType::tes5se)); + ::testing::Values(GameType::tes4, + GameType::tes5, + GameType::fo3, + GameType::fonv, + GameType::fo4, + GameType::tes5se)); -TEST_P(ConditionEvaluatorTest, evaluateShouldReturnTrueForAnEmptyConditionString) { +TEST_P(ConditionEvaluatorTest, + evaluateShouldReturnTrueForAnEmptyConditionString) { EXPECT_TRUE(evaluator_.evaluate("")); } @@ -67,27 +70,34 @@ TEST_P(ConditionEvaluatorTest, evaluateShouldThrowForAnInvalidConditionString) { EXPECT_THROW(evaluator_.evaluate("condition"), ConditionSyntaxError); } -TEST_P(ConditionEvaluatorTest, evaluateShouldReturnTrueForAConditionThatIsTrue) { +TEST_P(ConditionEvaluatorTest, + evaluateShouldReturnTrueForAConditionThatIsTrue) { EXPECT_TRUE(evaluator_.evaluate("file(\"" + blankEsm + "\")")); } -TEST_P(ConditionEvaluatorTest, evaluateShouldReturnFalseForAConditionThatIsFalse) { +TEST_P(ConditionEvaluatorTest, + evaluateShouldReturnFalseForAConditionThatIsFalse) { EXPECT_FALSE(evaluator_.evaluate("file(\"" + missingEsp + "\")")); } -TEST_P(ConditionEvaluatorTest, evaluateConditionShouldBeTrueIfTheCrcInThePluginCleaningDataGivenMatchesTheRealPluginCrc) { +TEST_P( + ConditionEvaluatorTest, + evaluateConditionShouldBeTrueIfTheCrcInThePluginCleaningDataGivenMatchesTheRealPluginCrc) { PluginCleaningData dirtyInfo(blankEsmCrc, "cleaner", info_, 2, 10, 30); EXPECT_TRUE(evaluator_.evaluate(dirtyInfo, blankEsm)); } -TEST_P(ConditionEvaluatorTest, evaluateShouldBeFalseIfTheCrcInThePluginCleaningDataGivenDoesNotMatchTheRealPluginCrc) { +TEST_P( + ConditionEvaluatorTest, + evaluateShouldBeFalseIfTheCrcInThePluginCleaningDataGivenDoesNotMatchTheRealPluginCrc) { PluginCleaningData dirtyInfo(0xDEADBEEF, "cleaner", info_, 2, 10, 30); EXPECT_FALSE(evaluator_.evaluate(dirtyInfo, blankEsm)); } -TEST_P(ConditionEvaluatorTest, evaluateShouldBeFalseIfAnEmptyPluginFilenameIsGiven) { +TEST_P(ConditionEvaluatorTest, + evaluateShouldBeFalseIfAnEmptyPluginFilenameIsGiven) { PluginCleaningData dirtyInfo(blankEsmCrc, "cleaner", info_, 2, 10, 30); EXPECT_FALSE(evaluator_.evaluate(dirtyInfo, "")); diff --git a/src/tests/api/internals/metadata/condition_grammar_test.h b/src/tests/api/internals/metadata/condition_grammar_test.h index c75c2ef6..8f9d22ba 100644 --- a/src/tests/api/internals/metadata/condition_grammar_test.h +++ b/src/tests/api/internals/metadata/condition_grammar_test.h @@ -33,14 +33,19 @@ namespace loot { namespace test { class ConditionGrammarTest : public CommonGameTestFixture { protected: - typedef ConditionGrammar Grammar; + typedef ConditionGrammar + Grammar; ConditionGrammarTest() : - resourcePath(dataPath / "resource" / "detail" / "resource.txt"), - game_(GetParam(), dataPath.parent_path(), localPath), - evaluator_(game_.Type(), game_.DataPath(), game_.GetCache(), game_.GetLoadOrderHandler()), - result_(false), - success_(false) {} + resourcePath(dataPath / "resource" / "detail" / "resource.txt"), + game_(GetParam(), dataPath.parent_path(), localPath), + evaluator_(game_.Type(), + game_.DataPath(), + game_.GetCache(), + game_.GetLoadOrderHandler()), + result_(false), + success_(false) {} inline void SetUp() { CommonGameTestFixture::SetUp(); @@ -48,7 +53,8 @@ protected: game_.LoadCurrentLoadOrderState(); // Write out an empty resource file. - ASSERT_NO_THROW(boost::filesystem::create_directories(resourcePath.parent_path())); + ASSERT_NO_THROW( + boost::filesystem::create_directories(resourcePath.parent_path())); boost::filesystem::ofstream out(resourcePath); out.close(); ASSERT_TRUE(boost::filesystem::exists(resourcePath)); @@ -68,17 +74,17 @@ protected: void loadInstalledPlugins(Game& game_, bool headersOnly) { const std::vector plugins({ - masterFile, - blankEsm, - blankDifferentEsm, - blankMasterDependentEsm, - blankDifferentMasterDependentEsm, - blankEsp, - blankDifferentEsp, - blankMasterDependentEsp, - blankDifferentMasterDependentEsp, - blankPluginDependentEsp, - blankDifferentPluginDependentEsp, + masterFile, + blankEsm, + blankDifferentEsm, + blankMasterDependentEsm, + blankDifferentMasterDependentEsm, + blankEsp, + blankDifferentEsp, + blankMasterDependentEsp, + blankDifferentMasterDependentEsp, + blankPluginDependentEsp, + blankDifferentPluginDependentEsp, }); game_.LoadPlugins(plugins, headersOnly); } @@ -96,13 +102,12 @@ protected: // but we only have the one so no prefix is necessary. INSTANTIATE_TEST_CASE_P(, ConditionGrammarTest, - ::testing::Values( - GameType::tes4, - GameType::tes5, - GameType::fo3, - GameType::fonv, - GameType::fo4, - GameType::tes5se)); + ::testing::Values(GameType::tes4, + GameType::tes5, + GameType::fo3, + GameType::fonv, + GameType::fo4, + GameType::tes5se)); TEST_P(ConditionGrammarTest, parsingInvalidSyntaxShouldThrow) { ConditionEvaluator evaluator; @@ -113,7 +118,8 @@ TEST_P(ConditionGrammarTest, parsingInvalidSyntaxShouldThrow) { std::cend(condition), grammar, skipper_, - result_), ConditionSyntaxError); + result_), + ConditionSyntaxError); } TEST_P(ConditionGrammarTest, evaluatingInvalidSyntaxShouldThrow) { @@ -124,7 +130,8 @@ TEST_P(ConditionGrammarTest, evaluatingInvalidSyntaxShouldThrow) { std::cend(condition), grammar, skipper_, - result_), ConditionSyntaxError); + result_), + ConditionSyntaxError); } TEST_P(ConditionGrammarTest, parsingAnEmptyConditionShouldThrow) { @@ -136,7 +143,8 @@ TEST_P(ConditionGrammarTest, parsingAnEmptyConditionShouldThrow) { std::cend(condition), grammar, skipper_, - result_), ConditionSyntaxError); + result_), + ConditionSyntaxError); } TEST_P(ConditionGrammarTest, evaluatingAnEmptyConditionShouldThrow) { @@ -147,36 +155,34 @@ TEST_P(ConditionGrammarTest, evaluatingAnEmptyConditionShouldThrow) { std::cend(condition), grammar, skipper_, - result_), ConditionSyntaxError); + result_), + ConditionSyntaxError); } -TEST_P(ConditionGrammarTest, aFileConditionWithAPluginThatExistsShouldEvaluateToTrue) { +TEST_P(ConditionGrammarTest, + aFileConditionWithAPluginThatExistsShouldEvaluateToTrue) { Grammar grammar(evaluator_); std::string condition("file(\"" + blankEsm + "\")"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_TRUE(result_); } -TEST_P(ConditionGrammarTest, aFileConditionWithAPluginThatDoesNotExistShouldEvaluateToFalse) { +TEST_P(ConditionGrammarTest, + aFileConditionWithAPluginThatDoesNotExistShouldEvaluateToFalse) { Grammar grammar(evaluator_); std::string condition("file(\"" + missingEsp + "\")"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_FALSE(result_); } -TEST_P(ConditionGrammarTest, evaluatingAFileConditionForAnUnsafePathShouldThrow) { +TEST_P(ConditionGrammarTest, + evaluatingAFileConditionForAnUnsafePathShouldThrow) { Grammar grammar(evaluator_); std::string condition("file(\"../../" + blankEsm + "\")"); @@ -184,7 +190,8 @@ TEST_P(ConditionGrammarTest, evaluatingAFileConditionForAnUnsafePathShouldThrow) std::cend(condition), grammar, skipper_, - result_), ConditionSyntaxError); + result_), + ConditionSyntaxError); } TEST_P(ConditionGrammarTest, aFileConditionWithAnInvalidRegexShouldThrow) { @@ -195,554 +202,504 @@ TEST_P(ConditionGrammarTest, aFileConditionWithAnInvalidRegexShouldThrow) { std::cend(condition), grammar, skipper_, - result_), ConditionSyntaxError); + result_), + ConditionSyntaxError); } -TEST_P(ConditionGrammarTest, aFileConditionWithARegexMatchingAPluginThatExistsShouldEvaluateToTrue) { +TEST_P(ConditionGrammarTest, + aFileConditionWithARegexMatchingAPluginThatExistsShouldEvaluateToTrue) { Grammar grammar(evaluator_); std::string condition("file(\"Blank.+\\.esm\")"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_TRUE(result_); } -TEST_P(ConditionGrammarTest, aFileConditionWithARegexMatchingAPluginThatDoesNotExistShouldEvaluateToFalse) { +TEST_P( + ConditionGrammarTest, + aFileConditionWithARegexMatchingAPluginThatDoesNotExistShouldEvaluateToFalse) { Grammar grammar(evaluator_); std::string condition("file(\"Blank\\.m.+\\.esm\")"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_FALSE(result_); } -TEST_P(ConditionGrammarTest, aFileConditionWithARegexMatchingAFileInASubfolderThatExistsShouldEvaluateToTrue) { +TEST_P( + ConditionGrammarTest, + aFileConditionWithARegexMatchingAFileInASubfolderThatExistsShouldEvaluateToTrue) { Grammar grammar(evaluator_); std::string condition("file(\"resource/detail/resource\\.txt\")"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_TRUE(result_); } -TEST_P(ConditionGrammarTest, aManyConditionWithARegexMatchingMoreThanOnePluginShouldEvaluateToTrue) { +TEST_P(ConditionGrammarTest, + aManyConditionWithARegexMatchingMoreThanOnePluginShouldEvaluateToTrue) { Grammar grammar(evaluator_); std::string condition("many(\"Blank.+\\.esm\")"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_TRUE(result_); } -TEST_P(ConditionGrammarTest, aManyConditionWithARegexMatchingOnlyOnePluginShouldEvaluateToFalse) { +TEST_P(ConditionGrammarTest, + aManyConditionWithARegexMatchingOnlyOnePluginShouldEvaluateToFalse) { Grammar grammar(evaluator_); std::string condition("many(\"Blank\\.esm\")"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_FALSE(result_); } -TEST_P(ConditionGrammarTest, aChecksumConditionWithACrcThatMatchesTheActualPluginCrcShouldEvaluateToTrue) { +TEST_P( + ConditionGrammarTest, + aChecksumConditionWithACrcThatMatchesTheActualPluginCrcShouldEvaluateToTrue) { Grammar grammar(evaluator_); - std::string condition("checksum(\"" + blankEsm + "\", " + IntToHexString(blankEsmCrc) + ")"); + std::string condition("checksum(\"" + blankEsm + "\", " + + IntToHexString(blankEsmCrc) + ")"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_TRUE(result_); } -TEST_P(ConditionGrammarTest, aChecksumConditionWithACrcThatMatchesTheActualCachedPluginCrcShouldEvaluateToTrue) { +TEST_P( + ConditionGrammarTest, + aChecksumConditionWithACrcThatMatchesTheActualCachedPluginCrcShouldEvaluateToTrue) { ASSERT_NO_THROW(loadInstalledPlugins(game_, false)); Grammar grammar(evaluator_); - std::string condition("checksum(\"" + blankEsm + "\", " + IntToHexString(blankEsmCrc) + ")"); + std::string condition("checksum(\"" + blankEsm + "\", " + + IntToHexString(blankEsmCrc) + ")"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_TRUE(result_); } -TEST_P(ConditionGrammarTest, aChecksumConditionWithACrcThatDoesNotMatchTheActualPluginCrcShouldEvaluateToFalse) { +TEST_P( + ConditionGrammarTest, + aChecksumConditionWithACrcThatDoesNotMatchTheActualPluginCrcShouldEvaluateToFalse) { Grammar grammar(evaluator_); std::string condition("checksum(\"" + blankEsm + "\", DEADBEEF)"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_FALSE(result_); } -TEST_P(ConditionGrammarTest, aVersionEqualityConditionWithAVersionThatEqualsTheActualPluginVersionShouldEvaluateToTrue) { +TEST_P( + ConditionGrammarTest, + aVersionEqualityConditionWithAVersionThatEqualsTheActualPluginVersionShouldEvaluateToTrue) { ASSERT_NO_THROW(loadInstalledPlugins(game_, true)); Grammar grammar(evaluator_); std::string condition("version(\"" + blankEsm + "\", \"5.0\", ==)"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_TRUE(result_); } -TEST_P(ConditionGrammarTest, aVersionEqualityConditionWithAVersionThatDoesNotEqualTheActualPluginVersionShouldEvaluateToFalse) { +TEST_P( + ConditionGrammarTest, + aVersionEqualityConditionWithAVersionThatDoesNotEqualTheActualPluginVersionShouldEvaluateToFalse) { ASSERT_NO_THROW(loadInstalledPlugins(game_, true)); Grammar grammar(evaluator_); std::string condition("version(\"" + blankEsm + "\", \"6.0\", ==)"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_FALSE(result_); } -TEST_P(ConditionGrammarTest, aVersionEqualityConditionForAPluginWithNoVersionShouldEvaluateToFalse) { +TEST_P(ConditionGrammarTest, + aVersionEqualityConditionForAPluginWithNoVersionShouldEvaluateToFalse) { ASSERT_NO_THROW(loadInstalledPlugins(game_, true)); Grammar grammar(evaluator_); std::string condition("version(\"" + blankEsp + "\", \"6.0\", ==)"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_FALSE(result_); } -TEST_P(ConditionGrammarTest, aVersionInequalityConditionWithAVersionThatDoesNotEqualTheActualPluginVersionShouldEvaluateToTrue) { +TEST_P( + ConditionGrammarTest, + aVersionInequalityConditionWithAVersionThatDoesNotEqualTheActualPluginVersionShouldEvaluateToTrue) { ASSERT_NO_THROW(loadInstalledPlugins(game_, true)); Grammar grammar(evaluator_); std::string condition("version(\"" + blankEsm + "\", \"6.0\", !=)"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_TRUE(result_); } -TEST_P(ConditionGrammarTest, aVersionInequalityConditionWithAVersionThatEqualsTheActualPluginVersionShouldEvaluateToFalse) { +TEST_P( + ConditionGrammarTest, + aVersionInequalityConditionWithAVersionThatEqualsTheActualPluginVersionShouldEvaluateToFalse) { ASSERT_NO_THROW(loadInstalledPlugins(game_, true)); Grammar grammar(evaluator_); std::string condition("version(\"" + blankEsm + "\", \"5.0\", !=)"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_FALSE(result_); } -TEST_P(ConditionGrammarTest, aVersionInequalityConditionForAPluginWithNoVersionShouldEvaluateToTrue) { +TEST_P(ConditionGrammarTest, + aVersionInequalityConditionForAPluginWithNoVersionShouldEvaluateToTrue) { ASSERT_NO_THROW(loadInstalledPlugins(game_, true)); Grammar grammar(evaluator_); std::string condition("version(\"" + blankEsp + "\", \"6.0\", !=)"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_TRUE(result_); } -TEST_P(ConditionGrammarTest, aVersionLessThanConditionWithAnActualPluginVersionLessThanTheGivenVersionShouldEvaluateToTrue) { +TEST_P( + ConditionGrammarTest, + aVersionLessThanConditionWithAnActualPluginVersionLessThanTheGivenVersionShouldEvaluateToTrue) { ASSERT_NO_THROW(loadInstalledPlugins(game_, true)); Grammar grammar(evaluator_); std::string condition("version(\"" + blankEsm + "\", \"6.0\", <)"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_TRUE(result_); } -TEST_P(ConditionGrammarTest, aVersionLessThanConditionWithAnActualPluginVersionEqualToTheGivenVersionShouldEvaluateToFalse) { +TEST_P( + ConditionGrammarTest, + aVersionLessThanConditionWithAnActualPluginVersionEqualToTheGivenVersionShouldEvaluateToFalse) { ASSERT_NO_THROW(loadInstalledPlugins(game_, true)); Grammar grammar(evaluator_); std::string condition("version(\"" + blankEsm + "\", \"5.0\", <)"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_FALSE(result_); } -TEST_P(ConditionGrammarTest, aVersionLessThanConditionForAPluginWithNoVersionShouldEvaluateToTrue) { +TEST_P(ConditionGrammarTest, + aVersionLessThanConditionForAPluginWithNoVersionShouldEvaluateToTrue) { ASSERT_NO_THROW(loadInstalledPlugins(game_, true)); Grammar grammar(evaluator_); std::string condition("version(\"" + blankEsp + "\", \"5.0\", <)"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_TRUE(result_); } -TEST_P(ConditionGrammarTest, aVersionGreaterThanConditionWithAnActualPluginVersionGreaterThanTheGivenVersionShouldEvaluateToTrue) { +TEST_P( + ConditionGrammarTest, + aVersionGreaterThanConditionWithAnActualPluginVersionGreaterThanTheGivenVersionShouldEvaluateToTrue) { ASSERT_NO_THROW(loadInstalledPlugins(game_, true)); Grammar grammar(evaluator_); std::string condition("version(\"" + blankEsm + "\", \"4.0\", >)"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_TRUE(result_); } -TEST_P(ConditionGrammarTest, aVersionGreaterThanConditionWithAnActualPluginVersionEqualToTheGivenVersionShouldEvaluateToFalse) { +TEST_P( + ConditionGrammarTest, + aVersionGreaterThanConditionWithAnActualPluginVersionEqualToTheGivenVersionShouldEvaluateToFalse) { ASSERT_NO_THROW(loadInstalledPlugins(game_, true)); Grammar grammar(evaluator_); std::string condition("version(\"" + blankEsm + "\", \"5.0\", >)"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_FALSE(result_); } -TEST_P(ConditionGrammarTest, aVersionGreaterThanConditionForAPluginWithNoVersionShouldEvaluateToFalse) { +TEST_P( + ConditionGrammarTest, + aVersionGreaterThanConditionForAPluginWithNoVersionShouldEvaluateToFalse) { ASSERT_NO_THROW(loadInstalledPlugins(game_, true)); Grammar grammar(evaluator_); std::string condition("version(\"" + blankEsp + "\", \"5.0\", >)"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_FALSE(result_); } -TEST_P(ConditionGrammarTest, aVersionLessThanOrEqualToConditionWithAnActualPluginVersionEqualToTheGivenVersionShouldEvaluateToTrue) { +TEST_P( + ConditionGrammarTest, + aVersionLessThanOrEqualToConditionWithAnActualPluginVersionEqualToTheGivenVersionShouldEvaluateToTrue) { ASSERT_NO_THROW(loadInstalledPlugins(game_, true)); Grammar grammar(evaluator_); std::string condition("version(\"" + blankEsm + "\", \"5.0\", <=)"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_TRUE(result_); } -TEST_P(ConditionGrammarTest, aVersionLessThanOrEqualToConditionWithAnActualPluginVersionGreaterThanTheGivenVersionShouldEvaluateToFalse) { +TEST_P( + ConditionGrammarTest, + aVersionLessThanOrEqualToConditionWithAnActualPluginVersionGreaterThanTheGivenVersionShouldEvaluateToFalse) { ASSERT_NO_THROW(loadInstalledPlugins(game_, true)); Grammar grammar(evaluator_); std::string condition("version(\"" + blankEsm + "\", \"4.0\", <=)"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_FALSE(result_); } -TEST_P(ConditionGrammarTest, aVersionLessThanOrEqualToConditionForAPluginWithNoVersionShouldEvaluateToTrue) { +TEST_P( + ConditionGrammarTest, + aVersionLessThanOrEqualToConditionForAPluginWithNoVersionShouldEvaluateToTrue) { ASSERT_NO_THROW(loadInstalledPlugins(game_, true)); Grammar grammar(evaluator_); std::string condition("version(\"" + blankEsp + "\", \"5.0\", <=)"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_TRUE(result_); } -TEST_P(ConditionGrammarTest, aVersionGreaterThanOrEqualToConditionWithAnActualPluginVersionEqualToTheGivenVersionShouldEvaluateToTrue) { +TEST_P( + ConditionGrammarTest, + aVersionGreaterThanOrEqualToConditionWithAnActualPluginVersionEqualToTheGivenVersionShouldEvaluateToTrue) { ASSERT_NO_THROW(loadInstalledPlugins(game_, true)); Grammar grammar(evaluator_); std::string condition("version(\"" + blankEsm + "\", \"5.0\", >=)"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_TRUE(result_); } -TEST_P(ConditionGrammarTest, aVersionGreaterThanOrEqualToConditionWithAnActualPluginVersionLessThanTheGivenVersionShouldEvaluateToFalse) { +TEST_P( + ConditionGrammarTest, + aVersionGreaterThanOrEqualToConditionWithAnActualPluginVersionLessThanTheGivenVersionShouldEvaluateToFalse) { ASSERT_NO_THROW(loadInstalledPlugins(game_, true)); Grammar grammar(evaluator_); std::string condition("version(\"" + blankEsm + "\", \"6.0\", >=)"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_FALSE(result_); } -TEST_P(ConditionGrammarTest, aVersionGreaterThanOrEqualToConditionForAPluginWithNoVersionShouldEvaluateToFalse) { +TEST_P( + ConditionGrammarTest, + aVersionGreaterThanOrEqualToConditionForAPluginWithNoVersionShouldEvaluateToFalse) { ASSERT_NO_THROW(loadInstalledPlugins(game_, true)); Grammar grammar(evaluator_); std::string condition("version(\"" + blankEsp + "\", \"5.0\", >=)"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_FALSE(result_); } -TEST_P(ConditionGrammarTest, anActiveConditionWithAPluginThatIsActiveShouldEvaluateToTrue) { +TEST_P(ConditionGrammarTest, + anActiveConditionWithAPluginThatIsActiveShouldEvaluateToTrue) { Grammar grammar(evaluator_); std::string condition("active(\"" + blankEsm + "\")"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_TRUE(result_); } -TEST_P(ConditionGrammarTest, anActiveConditionWithAPluginThatIsNotActiveShouldEvaluateToFalse) { +TEST_P(ConditionGrammarTest, + anActiveConditionWithAPluginThatIsNotActiveShouldEvaluateToFalse) { Grammar grammar(evaluator_); std::string condition("active(\"" + blankEsp + "\")"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_FALSE(result_); } -TEST_P(ConditionGrammarTest, anActiveConditionWithARegexMatchingAnActivePluginShouldEvaluateToTrue) { +TEST_P(ConditionGrammarTest, + anActiveConditionWithARegexMatchingAnActivePluginShouldEvaluateToTrue) { Grammar grammar(evaluator_); std::string condition("active(\"Blank\\.esm\")"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_TRUE(result_); } -TEST_P(ConditionGrammarTest, anActiveConditionWithARegexMatchingNoActivePluginsShouldEvaluateToFalse) { +TEST_P( + ConditionGrammarTest, + anActiveConditionWithARegexMatchingNoActivePluginsShouldEvaluateToFalse) { Grammar grammar(evaluator_); std::string condition("active(\"Blank\\.esp\")"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_FALSE(result_); } -TEST_P(ConditionGrammarTest, aManyActiveConditionWithARegexMatchingMoreThanOnePluginThatIsActiveShouldEvaluateToTrue) { +TEST_P( + ConditionGrammarTest, + aManyActiveConditionWithARegexMatchingMoreThanOnePluginThatIsActiveShouldEvaluateToTrue) { Grammar grammar(evaluator_); - std::string condition("many_active(\"Blank( - Different Master Dependent)?\\.es(m|p)\")"); + std::string condition( + "many_active(\"Blank( - Different Master Dependent)?\\.es(m|p)\")"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_TRUE(result_); } -TEST_P(ConditionGrammarTest, aManyActiveConditionWithARegexMatchingOnlyOnePluginThatIsActiveShouldEvaluateToFalse) { +TEST_P( + ConditionGrammarTest, + aManyActiveConditionWithARegexMatchingOnlyOnePluginThatIsActiveShouldEvaluateToFalse) { Grammar grammar(evaluator_); std::string condition("many_active(\"Blank\\.esm\")"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_FALSE(result_); } -TEST_P(ConditionGrammarTest, aManyActiveConditionWithARegexMatchingNoPluginsThatAreActiveShouldEvaluateToFalse) { +TEST_P( + ConditionGrammarTest, + aManyActiveConditionWithARegexMatchingNoPluginsThatAreActiveShouldEvaluateToFalse) { Grammar grammar(evaluator_); std::string condition("many_active(\"Blank\\.esp\")"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_FALSE(result_); } -TEST_P(ConditionGrammarTest, aFalseConditionPrecededByANegatorShouldEvaluateToTrue) { +TEST_P(ConditionGrammarTest, + aFalseConditionPrecededByANegatorShouldEvaluateToTrue) { Grammar grammar(evaluator_); std::string condition("not file(\"" + missingEsp + "\")"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_TRUE(result_); } -TEST_P(ConditionGrammarTest, aTrueConditionPrecededByANegatorShouldEvaluateToFalse) { +TEST_P(ConditionGrammarTest, + aTrueConditionPrecededByANegatorShouldEvaluateToFalse) { Grammar grammar(evaluator_); std::string condition("not file(\"" + blankEsm + "\")"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(condition), - std::cend(condition), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(condition), std::cend(condition), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_FALSE(result_); } -TEST_P(ConditionGrammarTest, twoTrueConditionsJoinedByAnAndShouldEvaluateToTrue) { +TEST_P(ConditionGrammarTest, + twoTrueConditionsJoinedByAnAndShouldEvaluateToTrue) { Grammar grammar(evaluator_); std::string condition("file(\"" + blankEsm + "\")"); std::string compound(condition + " and " + condition); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(compound), - std::cend(compound), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(compound), std::cend(compound), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_TRUE(result_); } -TEST_P(ConditionGrammarTest, aTrueAndAFalseConditionJoinedByAnAndShouldEvaluateToFalse) { +TEST_P(ConditionGrammarTest, + aTrueAndAFalseConditionJoinedByAnAndShouldEvaluateToFalse) { Grammar grammar(evaluator_); std::string condition("file(\"" + blankEsm + "\")"); std::string compound(condition + " and not " + condition); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(compound), - std::cend(compound), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(compound), std::cend(compound), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_FALSE(result_); } -TEST_P(ConditionGrammarTest, aFalseAndATrueConditionJoinedByAnOrShouldEvaluateToTrue) { +TEST_P(ConditionGrammarTest, + aFalseAndATrueConditionJoinedByAnOrShouldEvaluateToTrue) { Grammar grammar(evaluator_); std::string condition("file(\"" + blankEsm + "\")"); std::string compound("not " + condition + " or " + condition); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(compound), - std::cend(compound), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(compound), std::cend(compound), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_TRUE(result_); } -TEST_P(ConditionGrammarTest, twoFalseConditionsJoinedByAnOrShouldEvaluateToFalse) { +TEST_P(ConditionGrammarTest, + twoFalseConditionsJoinedByAnOrShouldEvaluateToFalse) { Grammar grammar(evaluator_); std::string condition("file(\"" + blankEsm + "\")"); std::string compound("not " + condition + " or not " + condition); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(compound), - std::cend(compound), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(compound), std::cend(compound), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_FALSE(result_); } @@ -750,13 +707,11 @@ TEST_P(ConditionGrammarTest, twoFalseConditionsJoinedByAnOrShouldEvaluateToFalse TEST_P(ConditionGrammarTest, andOperatorsShouldTakePrecedenceOverOrOperators) { Grammar grammar(evaluator_); std::string condition("file(\"" + blankEsm + "\")"); - std::string compound("not " + condition + " and " + condition + " or " + condition); + std::string compound("not " + condition + " and " + condition + " or " + + condition); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(compound), - std::cend(compound), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(compound), std::cend(compound), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_TRUE(result_); } @@ -764,13 +719,11 @@ TEST_P(ConditionGrammarTest, andOperatorsShouldTakePrecedenceOverOrOperators) { TEST_P(ConditionGrammarTest, parenthesesShouldTakePrecedenceOverAndOperators) { Grammar grammar(evaluator_); std::string condition("file(\"" + blankEsm + "\")"); - std::string compound("not " + condition + " and ( " + condition + " or " + condition + " )"); + std::string compound("not " + condition + " and ( " + condition + " or " + + condition + " )"); - success_ = boost::spirit::qi::phrase_parse(std::cbegin(compound), - std::cend(compound), - grammar, - skipper_, - result_); + success_ = boost::spirit::qi::phrase_parse( + std::cbegin(compound), std::cend(compound), grammar, skipper_, result_); EXPECT_TRUE(success_); EXPECT_FALSE(result_); } diff --git a/src/tests/api/internals/metadata/conditional_metadata_test.h b/src/tests/api/internals/metadata/conditional_metadata_test.h index e709ad80..43062d48 100644 --- a/src/tests/api/internals/metadata/conditional_metadata_test.h +++ b/src/tests/api/internals/metadata/conditional_metadata_test.h @@ -40,39 +40,44 @@ protected: // but we only have the one so no prefix is necessary. INSTANTIATE_TEST_CASE_P(, ConditionalMetadataTest, - ::testing::Values( - GameType::tes4, - GameType::tes5, - GameType::fo3, - GameType::fonv, - GameType::fo4, - GameType::tes5se)); + ::testing::Values(GameType::tes4, + GameType::tes5, + GameType::fo3, + GameType::fonv, + GameType::fo4, + GameType::tes5se)); -TEST_P(ConditionalMetadataTest, defaultConstructorShouldSetEmptyConditionString) { +TEST_P(ConditionalMetadataTest, + defaultConstructorShouldSetEmptyConditionString) { EXPECT_TRUE(conditionalMetadata_.GetCondition().empty()); } -TEST_P(ConditionalMetadataTest, stringConstructorShouldSetConditionToGivenString) { +TEST_P(ConditionalMetadataTest, + stringConstructorShouldSetConditionToGivenString) { std::string condition("condition"); conditionalMetadata_ = ConditionalMetadata(condition); EXPECT_EQ(condition, conditionalMetadata_.GetCondition()); } -TEST_P(ConditionalMetadataTest, isConditionalShouldBeFalseForAnEmptyConditionString) { +TEST_P(ConditionalMetadataTest, + isConditionalShouldBeFalseForAnEmptyConditionString) { EXPECT_FALSE(conditionalMetadata_.IsConditional()); } -TEST_P(ConditionalMetadataTest, isConditionalShouldBeTrueForANonEmptyConditionString) { +TEST_P(ConditionalMetadataTest, + isConditionalShouldBeTrueForANonEmptyConditionString) { conditionalMetadata_ = ConditionalMetadata("condition"); EXPECT_TRUE(conditionalMetadata_.IsConditional()); } -TEST_P(ConditionalMetadataTest, parseConditionShouldNotThrowForAnEmptyCondition) { +TEST_P(ConditionalMetadataTest, + parseConditionShouldNotThrowForAnEmptyCondition) { EXPECT_NO_THROW(conditionalMetadata_.ParseCondition()); } -TEST_P(ConditionalMetadataTest, parseConditionShouldThrowForAnInvalidCondition) { +TEST_P(ConditionalMetadataTest, + parseConditionShouldThrowForAnInvalidCondition) { conditionalMetadata_ = ConditionalMetadata("condition"); EXPECT_THROW(conditionalMetadata_.ParseCondition(), ConditionSyntaxError); } @@ -82,7 +87,8 @@ TEST_P(ConditionalMetadataTest, parseConditionShouldNotThrowForATrueCondition) { EXPECT_NO_THROW(conditionalMetadata_.ParseCondition()); } -TEST_P(ConditionalMetadataTest, parseConditionShouldNotThrowForAFalseCondition) { +TEST_P(ConditionalMetadataTest, + parseConditionShouldNotThrowForAFalseCondition) { conditionalMetadata_ = ConditionalMetadata("file(\"" + missingEsp + "\")"); EXPECT_NO_THROW(conditionalMetadata_.ParseCondition()); } diff --git a/src/tests/api/internals/metadata/file_test.h b/src/tests/api/internals/metadata/file_test.h index e15fc66a..ccc102a5 100644 --- a/src/tests/api/internals/metadata/file_test.h +++ b/src/tests/api/internals/metadata/file_test.h @@ -63,7 +63,8 @@ TEST(File, filesWithDifferentNamesShouldBeUnequal) { EXPECT_FALSE(file1 == file2); } -TEST(File, lessThanOperatorShouldUseCaseInsensitiveLexicographicalNameComparison) { +TEST(File, + lessThanOperatorShouldUseCaseInsensitiveLexicographicalNameComparison) { File file1("name", "display1", "condition1"); File file2("Name", "display2", "condition2"); @@ -81,9 +82,9 @@ TEST(File, emittingAsYamlShouldSingleQuoteValues) { File file("name1", "display1", "condition1"); YAML::Emitter emitter; emitter << file; - std::string expected = "name: '" + file.GetName() + - "'\ncondition: '" + file.GetCondition() + - "'\ndisplay: '" + file.GetDisplayName() + "'"; + std::string expected = "name: '" + file.GetName() + "'\ncondition: '" + + file.GetCondition() + "'\ndisplay: '" + + file.GetDisplayName() + "'"; EXPECT_EQ(expected, emitter.c_str()); } @@ -108,8 +109,8 @@ TEST(File, emittingAsYamlShouldOmitAnEmptyConditionString) { File file("name1", "display1"); YAML::Emitter emitter; emitter << file; - std::string expected = "name: '" + file.GetName() + - "'\ndisplay: '" + file.GetDisplayName() + "'"; + std::string expected = "name: '" + file.GetName() + "'\ndisplay: '" + + file.GetDisplayName() + "'"; EXPECT_EQ(expected, emitter.c_str()); } @@ -145,7 +146,8 @@ TEST(File, encodingAsYamlShouldOmitDisplayFieldIfItMatchesTheNameField) { } TEST(File, decodingFromYamlShouldSetDataCorrectly) { - YAML::Node node = YAML::Load("{name: name1, display: display1, condition: 'file(\"Foo.esp\")'}"); + YAML::Node node = YAML::Load( + "{name: name1, display: display1, condition: 'file(\"Foo.esp\")'}"); File file = node.as(); EXPECT_EQ(node["name"].as(), file.GetName()); @@ -153,7 +155,8 @@ TEST(File, decodingFromYamlShouldSetDataCorrectly) { EXPECT_EQ(node["condition"].as(), file.GetCondition()); } -TEST(File, decodingFromYamlWithMissingConditionFieldShouldLeaveConditionStringEmpty) { +TEST(File, + decodingFromYamlWithMissingConditionFieldShouldLeaveConditionStringEmpty) { YAML::Node node = YAML::Load("{name: name1, display: display1}"); File file = node.as(); @@ -162,7 +165,9 @@ TEST(File, decodingFromYamlWithMissingConditionFieldShouldLeaveConditionStringEm EXPECT_TRUE(file.GetCondition().empty()); } -TEST(File, decodingFromYamlScalarShouldUseNameValueForDisplayNameAndLeaveConditionEmpty) { +TEST( + File, + decodingFromYamlScalarShouldUseNameValueForDisplayNameAndLeaveConditionEmpty) { YAML::Node node = YAML::Load("name1"); File file = node.as(); diff --git a/src/tests/api/internals/metadata/location_test.h b/src/tests/api/internals/metadata/location_test.h index 241c1cc3..6add8f00 100644 --- a/src/tests/api/internals/metadata/location_test.h +++ b/src/tests/api/internals/metadata/location_test.h @@ -61,7 +61,8 @@ TEST(Location, locationsWithDifferentUrlsShouldBeUnequal) { EXPECT_FALSE(location1 == location2); } -TEST(Location, lessThanOperatorShouldUseCaseInsensitiveLexicographicalUrlComparison) { +TEST(Location, + lessThanOperatorShouldUseCaseInsensitiveLexicographicalUrlComparison) { Location location1("http://www.example.com", "example1"); Location location2("HTTP://WWW.EXAMPLE.COM", "example2"); @@ -88,7 +89,9 @@ TEST(Location, emittingAsYamlShouldOutputAMapIfTheNameStringIsNotEmpty) { YAML::Emitter emitter; emitter << location; - EXPECT_EQ("link: '" + location.GetURL() + "'\nname: '" + location.GetName() + "'", emitter.c_str()); + EXPECT_EQ( + "link: '" + location.GetURL() + "'\nname: '" + location.GetName() + "'", + emitter.c_str()); } TEST(Location, encodingAsYamlShouldStoreDataCorrectly) { @@ -117,7 +120,8 @@ TEST(Location, decodingFromYamlShouldSetDataCorrectly) { EXPECT_EQ(node["name"].as(), location.GetName()); } -TEST(Location, decodingFromYamlScalarShouldSetUrlToScalarValueAndLeaveNameEmpty) { +TEST(Location, + decodingFromYamlScalarShouldSetUrlToScalarValueAndLeaveNameEmpty) { YAML::Node node = YAML::Load("http://www.example.com"); Location location = node.as(); diff --git a/src/tests/api/internals/metadata/message_content_test.h b/src/tests/api/internals/metadata/message_content_test.h index 9e78caa1..a2ef0cf8 100644 --- a/src/tests/api/internals/metadata/message_content_test.h +++ b/src/tests/api/internals/metadata/message_content_test.h @@ -56,14 +56,16 @@ TEST(MessageContent, contentShouldBeEqualIfStringsAreCaseInsensitivelyEqual) { EXPECT_TRUE(content1 == content2); } -TEST(MessageContent, contentShouldBeUnequalIfStringsAreNotCaseInsensitivelyEqual) { +TEST(MessageContent, + contentShouldBeUnequalIfStringsAreNotCaseInsensitivelyEqual) { MessageContent content1("content1", french); MessageContent content2("content2", french); EXPECT_FALSE(content1 == content2); } -TEST(MessageContent, LessThanOperatorShouldUseCaseInsensitiveLexicographicalComparison) { +TEST(MessageContent, + LessThanOperatorShouldUseCaseInsensitiveLexicographicalComparison) { MessageContent content1("content"); MessageContent content2("Content", french); @@ -82,8 +84,8 @@ TEST(MessageContent, emittingAsYamlShouldOutputDataCorrectly) { YAML::Emitter emitter; emitter << content; - EXPECT_EQ("lang: " + french + - "\ntext: '" + content.GetText() + "'", emitter.c_str()); + EXPECT_EQ("lang: " + french + "\ntext: '" + content.GetText() + "'", + emitter.c_str()); } TEST(MessageContent, encodingAsYamlShouldOutputDataCorrectly) { diff --git a/src/tests/api/internals/metadata/message_test.h b/src/tests/api/internals/metadata/message_test.h index 60b1856d..79d70571 100644 --- a/src/tests/api/internals/metadata/message_test.h +++ b/src/tests/api/internals/metadata/message_test.h @@ -40,10 +40,7 @@ protected: // Pass an empty first argument, as it's a prefix for the test instantation, // but we only have the one so no prefix is necessary. -INSTANTIATE_TEST_CASE_P(, - MessageTest, - ::testing::Values( - GameType::tes4)); +INSTANTIATE_TEST_CASE_P(, MessageTest, ::testing::Values(GameType::tes4)); TEST_P(MessageTest, defaultConstructorShouldCreateNoteWithNoContent) { Message message; @@ -51,7 +48,8 @@ TEST_P(MessageTest, defaultConstructorShouldCreateNoteWithNoContent) { EXPECT_EQ(MessageContents(), message.GetContent()); } -TEST_P(MessageTest, scalarContentConstructorShouldCreateAMessageWithASingleContentString) { +TEST_P(MessageTest, + scalarContentConstructorShouldCreateAMessageWithASingleContentString) { MessageContent content = MessageContent("content1"); Message message(MessageType::warn, content.GetText(), "condition1"); @@ -60,10 +58,10 @@ TEST_P(MessageTest, scalarContentConstructorShouldCreateAMessageWithASingleConte EXPECT_EQ("condition1", message.GetCondition()); } -TEST_P(MessageTest, vectorContentConstructorShouldCreateAMessageWithGivenContentStrings) { +TEST_P(MessageTest, + vectorContentConstructorShouldCreateAMessageWithGivenContentStrings) { MessageContents contents({ - MessageContent("content1"), - MessageContent("content2", french), + MessageContent("content1"), MessageContent("content2", french), }); Message message(MessageType::error, contents, "condition1"); @@ -72,12 +70,14 @@ TEST_P(MessageTest, vectorContentConstructorShouldCreateAMessageWithGivenContent EXPECT_EQ("condition1", message.GetCondition()); } -TEST_P(MessageTest, vectorContentConstructorShouldThrowIfMultipleContentStringsAreGivenAndNoneAreEnglish) { +TEST_P( + MessageTest, + vectorContentConstructorShouldThrowIfMultipleContentStringsAreGivenAndNoneAreEnglish) { MessageContents contents({ - MessageContent("content1", german), - MessageContent("content2", french), + MessageContent("content1", german), MessageContent("content2", french), }); - EXPECT_THROW(Message(MessageType::error, contents, "condition1"), std::invalid_argument); + EXPECT_THROW(Message(MessageType::error, contents, "condition1"), + std::invalid_argument); } TEST_P(MessageTest, messagesWithDifferentContentStringsShouldBeUnequal) { @@ -88,15 +88,25 @@ TEST_P(MessageTest, messagesWithDifferentContentStringsShouldBeUnequal) { } TEST_P(MessageTest, messagesWithEqualContentStringsShouldBeEqual) { - Message message1(MessageType::say, MessageContents({MessageContent("content1")}), "condition1"); - Message message2(MessageType::warn, MessageContents({MessageContent("content1", french)}), "condition2"); + Message message1(MessageType::say, + MessageContents({MessageContent("content1")}), + "condition1"); + Message message2(MessageType::warn, + MessageContents({MessageContent("content1", french)}), + "condition2"); EXPECT_TRUE(message1 == message2); } -TEST_P(MessageTest, lessThanOperatorShouldUseCaseInsensitiveLexicographicalContentStringComparison) { - Message message1(MessageType::say, MessageContents({MessageContent("content1")}), "condition1"); - Message message2(MessageType::warn, MessageContents({MessageContent("content1", french)}), "condition2"); +TEST_P( + MessageTest, + lessThanOperatorShouldUseCaseInsensitiveLexicographicalContentStringComparison) { + Message message1(MessageType::say, + MessageContents({MessageContent("content1")}), + "condition1"); + Message message2(MessageType::warn, + MessageContents({MessageContent("content1", french)}), + "condition2"); EXPECT_FALSE(message1 < message2); EXPECT_FALSE(message2 < message1); @@ -108,42 +118,51 @@ TEST_P(MessageTest, lessThanOperatorShouldUseCaseInsensitiveLexicographicalConte TEST_P(MessageTest, getContentShouldReturnADefaultContentObjectIfNoneExists) { Message message; - EXPECT_EQ(MessageContent(), message.GetContent(MessageContent::defaultLanguage)); + EXPECT_EQ(MessageContent(), + message.GetContent(MessageContent::defaultLanguage)); } -TEST_P(MessageTest, getContentShouldSelectTheEnglishStringIfThereIsNoStringForTheGivenLanguage) { - Message message(MessageType::say, MessageContents({ - MessageContent("content1", german), - MessageContent("content2"), - })); +TEST_P( + MessageTest, + getContentShouldSelectTheEnglishStringIfThereIsNoStringForTheGivenLanguage) { + Message message( + MessageType::say, + MessageContents({ + MessageContent("content1", german), MessageContent("content2"), + })); EXPECT_EQ("content2", message.GetContent(french).GetText()); } TEST_P(MessageTest, getContentShouldSelectTheGivenLanguageStringIfItExists) { - Message message(MessageType::say, MessageContents({ - MessageContent("content1", german), - MessageContent("content2"), - MessageContent("content3", french), - })); + Message message(MessageType::say, + MessageContents({ + MessageContent("content1", german), + MessageContent("content2"), + MessageContent("content3", french), + })); EXPECT_EQ("content3", message.GetContent(french).GetText()); } TEST_P(MessageTest, getContentShouldSelectTheContentStringIfOnlyOneExists) { - Message message(MessageType::say, MessageContents({ - MessageContent("content1", french), - })); + Message message(MessageType::say, + MessageContents({ + MessageContent("content1", french), + })); - EXPECT_EQ("content1", message.GetContent(MessageContent::defaultLanguage).GetText()); + EXPECT_EQ("content1", + message.GetContent(MessageContent::defaultLanguage).GetText()); } TEST_P(MessageTest, toSimpleMessageShouldSelectTextAndLanguageUsingGetContent) { - Message message(MessageType::warn, MessageContents({ - MessageContent("content1", german), - MessageContent("content2"), - MessageContent("content3", french), - }), "condition1"); + Message message(MessageType::warn, + MessageContents({ + MessageContent("content1", german), + MessageContent("content2"), + MessageContent("content3", french), + }), + "condition1"); SimpleMessage simpleMessage = message.ToSimpleMessage(french); @@ -158,8 +177,10 @@ TEST_P(MessageTest, emittingAsYamlShouldOutputNoteMessageTypeCorrectly) { YAML::Emitter emitter; emitter << message; - EXPECT_STREQ("type: say\n" - "content: 'content1'", emitter.c_str()); + EXPECT_STREQ( + "type: say\n" + "content: 'content1'", + emitter.c_str()); } TEST_P(MessageTest, emittingAsYamlShouldOutputWarnMessageTypeCorrectly) { @@ -167,8 +188,10 @@ TEST_P(MessageTest, emittingAsYamlShouldOutputWarnMessageTypeCorrectly) { YAML::Emitter emitter; emitter << message; - EXPECT_STREQ("type: warn\n" - "content: 'content1'", emitter.c_str()); + EXPECT_STREQ( + "type: warn\n" + "content: 'content1'", + emitter.c_str()); } TEST_P(MessageTest, emittingAsYamlShouldOutputErrorMessageTypeCorrectly) { @@ -176,8 +199,10 @@ TEST_P(MessageTest, emittingAsYamlShouldOutputErrorMessageTypeCorrectly) { YAML::Emitter emitter; emitter << message; - EXPECT_STREQ("type: error\n" - "content: 'content1'", emitter.c_str()); + EXPECT_STREQ( + "type: error\n" + "content: 'content1'", + emitter.c_str()); } TEST_P(MessageTest, emittingAsYamlShouldOutputConditionIfItIsNotEmpty) { @@ -185,25 +210,28 @@ TEST_P(MessageTest, emittingAsYamlShouldOutputConditionIfItIsNotEmpty) { YAML::Emitter emitter; emitter << message; - EXPECT_STREQ("type: say\n" - "content: 'content1'\n" - "condition: 'condition1'", emitter.c_str()); + EXPECT_STREQ( + "type: say\n" + "content: 'content1'\n" + "condition: 'condition1'", + emitter.c_str()); } TEST_P(MessageTest, emittingAsYamlShouldOutputMultipleContentStringsAsAList) { - Message message(MessageType::say, MessageContents({ - MessageContent("content1"), - MessageContent("content2", french) - })); + Message message(MessageType::say, + MessageContents({MessageContent("content1"), + MessageContent("content2", french)})); YAML::Emitter emitter; emitter << message; - EXPECT_STREQ("type: say\n" - "content:\n" - " - lang: en\n" - " text: 'content1'\n" - " - lang: fr\n" - " text: 'content2'", emitter.c_str()); + EXPECT_STREQ( + "type: say\n" + "content:\n" + " - lang: en\n" + " text: 'content1'\n" + " - lang: fr\n" + " text: 'content2'", + emitter.c_str()); } TEST_P(MessageTest, encodingAsYamlShouldStoreNoteMessageTypeCorrectly) { @@ -256,8 +284,7 @@ TEST_P(MessageTest, encodingAsYamlShouldStoreASingleContentStringInAVector) { TEST_P(MessageTest, encodingAsYamlShouldMultipleContentStringsInAVector) { MessageContents contents({ - MessageContent("content1"), - MessageContent("content2", french), + MessageContent("content1"), MessageContent("content2", french), }); Message message(MessageType::say, contents); YAML::Node node; @@ -267,57 +294,65 @@ TEST_P(MessageTest, encodingAsYamlShouldMultipleContentStringsInAVector) { } TEST_P(MessageTest, decodingFromYamlShouldSetNoteTypeCorrectly) { - YAML::Node node = YAML::Load("type: say\n" - "content: content1"); + YAML::Node node = YAML::Load( + "type: say\n" + "content: content1"); Message message = node.as(); EXPECT_EQ(MessageType::say, message.GetType()); } TEST_P(MessageTest, decodingFromYamlShouldSetWarningTypeCorrectly) { - YAML::Node node = YAML::Load("type: warn\n" - "content: content1"); + YAML::Node node = YAML::Load( + "type: warn\n" + "content: content1"); Message message = node.as(); EXPECT_EQ(MessageType::warn, message.GetType()); } TEST_P(MessageTest, decodingFromYamlShouldSetErrorTypeCorrectly) { - YAML::Node node = YAML::Load("type: error\n" - "content: content1"); + YAML::Node node = YAML::Load( + "type: error\n" + "content: content1"); Message message = node.as(); EXPECT_EQ(MessageType::error, message.GetType()); } TEST_P(MessageTest, decodingFromYamlShouldHandleAnUnrecognisedTypeAsANote) { - YAML::Node node = YAML::Load("type: invalid\n" - "content: content1"); + YAML::Node node = YAML::Load( + "type: invalid\n" + "content: content1"); Message message = node.as(); EXPECT_EQ(MessageType::say, message.GetType()); } -TEST_P(MessageTest, decodingFromYamlShouldLeaveTheConditionEmptyIfNoneIsPresent) { - YAML::Node node = YAML::Load("type: say\n" - "content: content1"); +TEST_P(MessageTest, + decodingFromYamlShouldLeaveTheConditionEmptyIfNoneIsPresent) { + YAML::Node node = YAML::Load( + "type: say\n" + "content: content1"); Message message = node.as(); EXPECT_TRUE(message.GetCondition().empty()); } TEST_P(MessageTest, decodingFromYamlShouldStoreANonEmptyConditionField) { - YAML::Node node = YAML::Load("type: say\n" - "content: content1\n" - "condition: 'file(\"Foo.esp\")'"); + YAML::Node node = YAML::Load( + "type: say\n" + "content: content1\n" + "condition: 'file(\"Foo.esp\")'"); Message message = node.as(); EXPECT_EQ("file(\"Foo.esp\")", message.GetCondition()); } TEST_P(MessageTest, decodingFromYamlShouldStoreAScalarContentValueCorrectly) { - YAML::Node node = YAML::Load("type: say\n" - "content: content1\n"); + YAML::Node node = YAML::Load( + "type: say\n" + "content: content1\n"); Message message = node.as(); MessageContents expectedContent({MessageContent("content1")}); @@ -325,89 +360,110 @@ TEST_P(MessageTest, decodingFromYamlShouldStoreAScalarContentValueCorrectly) { } TEST_P(MessageTest, decodingFromYamlShouldStoreAListOfContentStringsCorrectly) { - YAML::Node node = YAML::Load("type: say\n" - "content:\n" - " - lang: en\n" - " text: content1\n" - " - lang: fr\n" - " text: content2"); + YAML::Node node = YAML::Load( + "type: say\n" + "content:\n" + " - lang: en\n" + " text: content1\n" + " - lang: fr\n" + " text: content2"); Message message = node.as(); EXPECT_EQ(MessageContents({ - MessageContent("content1"), - MessageContent("content2", french), - }), message.GetContent()); + MessageContent("content1"), MessageContent("content2", french), + }), + message.GetContent()); } -TEST_P(MessageTest, decodingFromYamlShouldNotThrowIfTheOnlyContentStringIsNotEnglish) { - YAML::Node node = YAML::Load("type: say\n" - "content:\n" - " - lang: fr\n" - " text: content1"); +TEST_P(MessageTest, + decodingFromYamlShouldNotThrowIfTheOnlyContentStringIsNotEnglish) { + YAML::Node node = YAML::Load( + "type: say\n" + "content:\n" + " - lang: fr\n" + " text: content1"); EXPECT_NO_THROW(Message message = node.as()); } -TEST_P(MessageTest, decodingFromYamlShouldThrowIfMultipleContentStringsAreGivenAndNoneAreEnglish) { - YAML::Node node = YAML::Load("type: say\n" - "content:\n" - " - lang: de\n" - " text: content1\n" - " - lang: fr\n" - " text: content2"); +TEST_P( + MessageTest, + decodingFromYamlShouldThrowIfMultipleContentStringsAreGivenAndNoneAreEnglish) { + YAML::Node node = YAML::Load( + "type: say\n" + "content:\n" + " - lang: de\n" + " text: content1\n" + " - lang: fr\n" + " text: content2"); EXPECT_THROW(node.as(), YAML::RepresentationException); } -TEST_P(MessageTest, decodingFromYamlShouldApplySubstitutionsWhenThereIsOnlyOneContentString) { - YAML::Node node = YAML::Load("type: say\n" - "content: con%1%tent1\n" - "subs:\n" - " - sub1"); +TEST_P( + MessageTest, + decodingFromYamlShouldApplySubstitutionsWhenThereIsOnlyOneContentString) { + YAML::Node node = YAML::Load( + "type: say\n" + "content: con%1%tent1\n" + "subs:\n" + " - sub1"); Message message = node.as(); - EXPECT_EQ(MessageContents({MessageContent("consub1tent1")}), message.GetContent()); + EXPECT_EQ(MessageContents({MessageContent("consub1tent1")}), + message.GetContent()); } -TEST_P(MessageTest, decodingFromYamlShouldApplySubstitutionsToAllContentStrings) { - YAML::Node node = YAML::Load("type: say\n" - "content:\n" - " - lang: en\n" - " text: content1 %1%\n" - " - lang: fr\n" - " text: content2 %1%\n" - "subs:\n" - " - sub"); +TEST_P(MessageTest, + decodingFromYamlShouldApplySubstitutionsToAllContentStrings) { + YAML::Node node = YAML::Load( + "type: say\n" + "content:\n" + " - lang: en\n" + " text: content1 %1%\n" + " - lang: fr\n" + " text: content2 %1%\n" + "subs:\n" + " - sub"); Message message = node.as(); EXPECT_EQ(MessageContents({ - MessageContent("content1 sub"), - MessageContent("content2 sub", french), - }), message.GetContent()); + MessageContent("content1 sub"), + MessageContent("content2 sub", french), + }), + message.GetContent()); } -TEST_P(MessageTest, decodingFromYamlShouldThrowIfTheContentStringExpectsMoreSubstitutionsThanExist) { - YAML::Node node = YAML::Load("type: say\n" - "content: '%1% %2%'\n" - "subs:\n" - " - sub1"); +TEST_P( + MessageTest, + decodingFromYamlShouldThrowIfTheContentStringExpectsMoreSubstitutionsThanExist) { + YAML::Node node = YAML::Load( + "type: say\n" + "content: '%1% %2%'\n" + "subs:\n" + " - sub1"); EXPECT_THROW(node.as(), YAML::RepresentationException); } -// Don't throw because no subs are given, so none are expected in the content string. -TEST_P(MessageTest, decodingFromYamlShouldIgnoreSubstitutionSyntaxIfNoSubstitutionsExist) { - YAML::Node node = YAML::Load("type: say\n" - "content: con%1%tent1\n"); +// Don't throw because no subs are given, so none are expected in the content +// string. +TEST_P(MessageTest, + decodingFromYamlShouldIgnoreSubstitutionSyntaxIfNoSubstitutionsExist) { + YAML::Node node = YAML::Load( + "type: say\n" + "content: con%1%tent1\n"); Message message = node.as(); - EXPECT_EQ(MessageContents({MessageContent("con%1%tent1")}), message.GetContent()); + EXPECT_EQ(MessageContents({MessageContent("con%1%tent1")}), + message.GetContent()); } TEST_P(MessageTest, decodingFromYamlShouldThrowIfAnInvalidConditionIsGiven) { - YAML::Node node = YAML::Load("type: say\n" - "content: content1\n" - "condition: invalid"); + YAML::Node node = YAML::Load( + "type: say\n" + "content: content1\n" + "condition: invalid"); EXPECT_THROW(node.as(), YAML::RepresentationException); } diff --git a/src/tests/api/internals/metadata/plugin_cleaning_data_test.h b/src/tests/api/internals/metadata/plugin_cleaning_data_test.h index d7fcbf0c..3c0eb1f0 100644 --- a/src/tests/api/internals/metadata/plugin_cleaning_data_test.h +++ b/src/tests/api/internals/metadata/plugin_cleaning_data_test.h @@ -35,9 +35,10 @@ namespace loot { namespace test { class PluginCleaningDataTest : public CommonGameTestFixture { protected: - PluginCleaningDataTest() : info_(std::vector({ - MessageContent("info"), - })) {} + PluginCleaningDataTest() : + info_(std::vector({ + MessageContent("info"), + })) {} const std::vector info_; }; @@ -46,10 +47,10 @@ protected: // but we only have the one so no prefix is necessary. INSTANTIATE_TEST_CASE_P(, PluginCleaningDataTest, - ::testing::Values( - GameType::tes4)); + ::testing::Values(GameType::tes4)); -TEST_P(PluginCleaningDataTest, defaultConstructorShouldLeaveAllCountsAtZeroAndTheUtilityStringEmpty) { +TEST_P(PluginCleaningDataTest, + defaultConstructorShouldLeaveAllCountsAtZeroAndTheUtilityStringEmpty) { PluginCleaningData info; EXPECT_EQ(0, info.GetCRC()); EXPECT_EQ(0, info.GetITMCount()); @@ -91,35 +92,41 @@ TEST_P(PluginCleaningDataTest, LessThanOperatorShouldCompareCrcValues) { EXPECT_FALSE(info2 < info1); } -TEST_P(PluginCleaningDataTest, chooseInfoShouldCreateADefaultContentObjectIfNoneExists) { - PluginCleaningData dirtyInfo(0xDEADBEEF, "cleaner", std::vector(), 2, 10, 30); - EXPECT_EQ(MessageContent(), dirtyInfo.ChooseInfo(MessageContent::defaultLanguage)); +TEST_P(PluginCleaningDataTest, + chooseInfoShouldCreateADefaultContentObjectIfNoneExists) { + PluginCleaningData dirtyInfo( + 0xDEADBEEF, "cleaner", std::vector(), 2, 10, 30); + EXPECT_EQ(MessageContent(), + dirtyInfo.ChooseInfo(MessageContent::defaultLanguage)); } -TEST_P(PluginCleaningDataTest, chooseInfoShouldLeaveTheContentUnchangedIfOnlyOneStringExists) { +TEST_P(PluginCleaningDataTest, + chooseInfoShouldLeaveTheContentUnchangedIfOnlyOneStringExists) { PluginCleaningData dirtyInfo(0xDEADBEEF, "cleaner", info_, 2, 10, 30); EXPECT_EQ(info_[0], dirtyInfo.ChooseInfo(french)); EXPECT_EQ(info_[0], dirtyInfo.ChooseInfo(MessageContent::defaultLanguage)); } -TEST_P(PluginCleaningDataTest, chooseInfoShouldSelectTheEnglishStringIfNoStringExistsForTheGivenLanguage) { +TEST_P( + PluginCleaningDataTest, + chooseInfoShouldSelectTheEnglishStringIfNoStringExistsForTheGivenLanguage) { MessageContent content("content1", MessageContent::defaultLanguage); std::vector info({ - content, - MessageContent("content1", german), + content, MessageContent("content1", german), }); PluginCleaningData dirtyInfo(0xDEADBEEF, "cleaner", info, 2, 10, 30); EXPECT_EQ(content, dirtyInfo.ChooseInfo(french)); } -TEST_P(PluginCleaningDataTest, chooseInfoShouldSelectTheStringForTheGivenLanguageIfOneExists) { +TEST_P(PluginCleaningDataTest, + chooseInfoShouldSelectTheStringForTheGivenLanguageIfOneExists) { MessageContent frenchContent("content3", french); std::vector info({ - MessageContent("content1", german), - MessageContent("content2", MessageContent::defaultLanguage), - frenchContent, + MessageContent("content1", german), + MessageContent("content2", MessageContent::defaultLanguage), + frenchContent, }); PluginCleaningData dirtyInfo(0xDEADBEEF, "cleaner", info, 2, 10, 30); @@ -131,7 +138,10 @@ TEST_P(PluginCleaningDataTest, emittingAsYamlShouldOutputAllNonZeroCounts) { YAML::Emitter emitter; emitter << info; - EXPECT_STREQ("crc: 0x12345678\nutil: 'cleaner'\ninfo: 'info'\nitm: 2\nudr: 10\nnav: 30", emitter.c_str()); + EXPECT_STREQ( + "crc: 0x12345678\nutil: 'cleaner'\ninfo: 'info'\nitm: 2\nudr: 10\nnav: " + "30", + emitter.c_str()); } TEST_P(PluginCleaningDataTest, emittingAsYamlShouldOmitAllZeroCounts) { @@ -139,7 +149,8 @@ TEST_P(PluginCleaningDataTest, emittingAsYamlShouldOmitAllZeroCounts) { YAML::Emitter emitter; emitter << info; - EXPECT_STREQ("crc: 0x12345678\nutil: 'cleaner'\ninfo: 'info'", emitter.c_str()); + EXPECT_STREQ("crc: 0x12345678\nutil: 'cleaner'\ninfo: 'info'", + emitter.c_str()); } TEST_P(PluginCleaningDataTest, encodingAsYamlShouldOmitAllZeroCountFields) { @@ -155,7 +166,8 @@ TEST_P(PluginCleaningDataTest, encodingAsYamlShouldOmitAllZeroCountFields) { EXPECT_FALSE(node["nav"]); } -TEST_P(PluginCleaningDataTest, encodingAsYamlShouldOutputAllNonZeroCountFields) { +TEST_P(PluginCleaningDataTest, + encodingAsYamlShouldOutputAllNonZeroCountFields) { PluginCleaningData info(0x12345678, "cleaner", info_, 2, 10, 30); YAML::Node node; node = info; @@ -168,7 +180,8 @@ TEST_P(PluginCleaningDataTest, encodingAsYamlShouldOutputAllNonZeroCountFields) EXPECT_EQ(30, node["nav"].as()); } -TEST_P(PluginCleaningDataTest, decodingFromYamlShouldLeaveMissingFieldsWithZeroValues) { +TEST_P(PluginCleaningDataTest, + decodingFromYamlShouldLeaveMissingFieldsWithZeroValues) { YAML::Node node = YAML::Load("{crc: 0x12345678, util: cleaner}"); PluginCleaningData info = node.as(); @@ -181,7 +194,8 @@ TEST_P(PluginCleaningDataTest, decodingFromYamlShouldLeaveMissingFieldsWithZeroV } TEST_P(PluginCleaningDataTest, decodingFromYamlShouldStoreAllNonZeroCounts) { - YAML::Node node = YAML::Load("{crc: 0x12345678, util: cleaner, info: info, itm: 2, udr: 10, nav: 30}"); + YAML::Node node = YAML::Load( + "{crc: 0x12345678, util: cleaner, info: info, itm: 2, udr: 10, nav: 30}"); PluginCleaningData info = node.as(); EXPECT_EQ(0x12345678, info.GetCRC()); diff --git a/src/tests/api/internals/metadata/plugin_metadata_test.h b/src/tests/api/internals/metadata/plugin_metadata_test.h index 44f904b0..f9ef07d7 100644 --- a/src/tests/api/internals/metadata/plugin_metadata_test.h +++ b/src/tests/api/internals/metadata/plugin_metadata_test.h @@ -35,9 +35,10 @@ namespace loot { namespace test { class PluginMetadataTest : public CommonGameTestFixture { protected: - PluginMetadataTest() : info_(std::vector({ - MessageContent("info"), - })) {} + PluginMetadataTest() : + info_(std::vector({ + MessageContent("info"), + })) {} const std::vector info_; }; @@ -46,24 +47,28 @@ protected: // but we only have the one so no prefix is necessary. INSTANTIATE_TEST_CASE_P(, PluginMetadataTest, - ::testing::Values( - GameType::tes5)); + ::testing::Values(GameType::tes5)); -TEST_P(PluginMetadataTest, defaultConstructorShouldLeaveNameEmptyAndEnableMetadataAndLeaveAllOtherFieldsAtTheirDefaults) { +TEST_P( + PluginMetadataTest, + defaultConstructorShouldLeaveNameEmptyAndEnableMetadataAndLeaveAllOtherFieldsAtTheirDefaults) { PluginMetadata plugin; EXPECT_TRUE(plugin.GetName().empty()); EXPECT_TRUE(plugin.IsEnabled()); } -TEST_P(PluginMetadataTest, stringConstructorShouldSetNameToGivenStringAndEnableMetadataAndLeaveAllOtherFieldsAtTheirDefaults) { +TEST_P( + PluginMetadataTest, + stringConstructorShouldSetNameToGivenStringAndEnableMetadataAndLeaveAllOtherFieldsAtTheirDefaults) { PluginMetadata plugin(blankEsm); EXPECT_EQ(blankEsm, plugin.GetName()); EXPECT_TRUE(plugin.IsEnabled()); } -TEST_P(PluginMetadataTest, equalityOperatorShouldUseCaseInsensitiveNameComparisonForNonRegexNames) { +TEST_P(PluginMetadataTest, + equalityOperatorShouldUseCaseInsensitiveNameComparisonForNonRegexNames) { PluginMetadata plugin1(blankEsm); PluginMetadata plugin2(boost::to_lower_copy(blankEsm)); EXPECT_TRUE(plugin1 == plugin2); @@ -73,7 +78,8 @@ TEST_P(PluginMetadataTest, equalityOperatorShouldUseCaseInsensitiveNameCompariso EXPECT_FALSE(plugin1 == plugin2); } -TEST_P(PluginMetadataTest, equalityOperatorShouldUseCaseInsensitiveNameComparisonForTwoRegexNames) { +TEST_P(PluginMetadataTest, + equalityOperatorShouldUseCaseInsensitiveNameComparisonForTwoRegexNames) { PluginMetadata plugin1("Blan.\\.esm"); PluginMetadata plugin2("blan.\\.esm"); EXPECT_TRUE(plugin1 == plugin2); @@ -85,7 +91,8 @@ TEST_P(PluginMetadataTest, equalityOperatorShouldUseCaseInsensitiveNameCompariso EXPECT_FALSE(plugin2 == plugin1); } -TEST_P(PluginMetadataTest, equalityOperatorShouldUseRegexMatchingForARegexNameAndANonRegexName) { +TEST_P(PluginMetadataTest, + equalityOperatorShouldUseRegexMatchingForARegexNameAndANonRegexName) { PluginMetadata plugin1("Blank.esm"); PluginMetadata plugin2("Blan.\\.esm"); EXPECT_TRUE(plugin1 == plugin2); @@ -106,7 +113,8 @@ TEST_P(PluginMetadataTest, mergeMetadataShouldNotChangeName) { EXPECT_EQ(blankEsm, plugin1.GetName()); } -TEST_P(PluginMetadataTest, mergeMetadataShouldNotUseMergedEnabledStateIfMergedMetadataIsEmpty) { +TEST_P(PluginMetadataTest, + mergeMetadataShouldNotUseMergedEnabledStateIfMergedMetadataIsEmpty) { PluginMetadata plugin1; PluginMetadata plugin2; @@ -117,7 +125,8 @@ TEST_P(PluginMetadataTest, mergeMetadataShouldNotUseMergedEnabledStateIfMergedMe EXPECT_TRUE(plugin1.IsEnabled()); } -TEST_P(PluginMetadataTest, mergeMetadataShouldUseMergedEnabledStateIfMergedMetadataIsNotEmpty) { +TEST_P(PluginMetadataTest, + mergeMetadataShouldUseMergedEnabledStateIfMergedMetadataIsNotEmpty) { PluginMetadata plugin1; PluginMetadata plugin2; @@ -129,7 +138,8 @@ TEST_P(PluginMetadataTest, mergeMetadataShouldUseMergedEnabledStateIfMergedMetad EXPECT_FALSE(plugin1.IsEnabled()); } -TEST_P(PluginMetadataTest, mergeMetadataShouldUseMergedNonZeroLocalPriorityValue) { +TEST_P(PluginMetadataTest, + mergeMetadataShouldUseMergedNonZeroLocalPriorityValue) { PluginMetadata plugin1; PluginMetadata plugin2; @@ -140,7 +150,8 @@ TEST_P(PluginMetadataTest, mergeMetadataShouldUseMergedNonZeroLocalPriorityValue EXPECT_EQ(3, plugin1.GetLocalPriority().GetValue()); } -TEST_P(PluginMetadataTest, mergeMetadataShouldUseMergedNonZeroGlobalPriorityValue) { +TEST_P(PluginMetadataTest, + mergeMetadataShouldUseMergedNonZeroGlobalPriorityValue) { PluginMetadata plugin1; PluginMetadata plugin2; @@ -151,7 +162,8 @@ TEST_P(PluginMetadataTest, mergeMetadataShouldUseMergedNonZeroGlobalPriorityValu EXPECT_EQ(3, plugin1.GetGlobalPriority().GetValue()); } -TEST_P(PluginMetadataTest, mergeMetadataShouldNotUseImplicitZeroLocalPriorityValue) { +TEST_P(PluginMetadataTest, + mergeMetadataShouldNotUseImplicitZeroLocalPriorityValue) { PluginMetadata plugin1; PluginMetadata plugin2; @@ -161,7 +173,8 @@ TEST_P(PluginMetadataTest, mergeMetadataShouldNotUseImplicitZeroLocalPriorityVal EXPECT_EQ(5, plugin1.GetLocalPriority().GetValue()); } -TEST_P(PluginMetadataTest, mergeMetadataShouldNotUseImplicitZeroGlobalPriorityValue) { +TEST_P(PluginMetadataTest, + mergeMetadataShouldNotUseImplicitZeroGlobalPriorityValue) { PluginMetadata plugin1; PluginMetadata plugin2; @@ -171,7 +184,8 @@ TEST_P(PluginMetadataTest, mergeMetadataShouldNotUseImplicitZeroGlobalPriorityVa EXPECT_EQ(5, plugin1.GetGlobalPriority().GetValue()); } -TEST_P(PluginMetadataTest, mergeMetadataShouldMergeAnExplicitLocalPriorityValueOfZero) { +TEST_P(PluginMetadataTest, + mergeMetadataShouldMergeAnExplicitLocalPriorityValueOfZero) { PluginMetadata plugin1; PluginMetadata plugin2; @@ -183,7 +197,8 @@ TEST_P(PluginMetadataTest, mergeMetadataShouldMergeAnExplicitLocalPriorityValueO EXPECT_TRUE(plugin1.GetLocalPriority().IsExplicit()); } -TEST_P(PluginMetadataTest, mergeMetadataShouldMergeAnExplicitGlobalPriorityValueOfZero) { +TEST_P(PluginMetadataTest, + mergeMetadataShouldMergeAnExplicitGlobalPriorityValueOfZero) { PluginMetadata plugin1; PluginMetadata plugin2; @@ -270,7 +285,8 @@ TEST_P(PluginMetadataTest, mergeMetadataShouldMergeDirtyInfoData) { plugin2.SetDirtyInfo({info1, info2}); plugin1.MergeMetadata(plugin2); - EXPECT_EQ(std::set({info1, info2}), plugin1.GetDirtyInfo()); + EXPECT_EQ(std::set({info1, info2}), + plugin1.GetDirtyInfo()); } TEST_P(PluginMetadataTest, mergeMetadataShouldMergeCleanInfoData) { PluginMetadata plugin1; @@ -282,7 +298,8 @@ TEST_P(PluginMetadataTest, mergeMetadataShouldMergeCleanInfoData) { plugin2.SetCleanInfo({info1, info2}); plugin1.MergeMetadata(plugin2); - EXPECT_EQ(std::set({info1, info2}), plugin1.GetCleanInfo()); + EXPECT_EQ(std::set({info1, info2}), + plugin1.GetCleanInfo()); } TEST_P(PluginMetadataTest, mergeMetadataShouldMergeLocationData) { @@ -342,7 +359,8 @@ TEST_P(PluginMetadataTest, newMetadataShouldUseSourcePluginGlobalPriority) { EXPECT_EQ(5, newMetadata.GetGlobalPriority().GetValue()); } -TEST_P(PluginMetadataTest, newMetadataShouldOutputLoadAfterDataThatAreNotCommonToBothInputPlugins) { +TEST_P(PluginMetadataTest, + newMetadataShouldOutputLoadAfterDataThatAreNotCommonToBothInputPlugins) { PluginMetadata plugin1; PluginMetadata plugin2; File file1(blankEsm); @@ -356,7 +374,9 @@ TEST_P(PluginMetadataTest, newMetadataShouldOutputLoadAfterDataThatAreNotCommonT EXPECT_EQ(std::set({file2}), newMetadata.GetLoadAfterFiles()); } -TEST_P(PluginMetadataTest, newMetadataShouldOutputRequirementsDataThatAreNotCommonToBothInputPlugins) { +TEST_P( + PluginMetadataTest, + newMetadataShouldOutputRequirementsDataThatAreNotCommonToBothInputPlugins) { PluginMetadata plugin1; PluginMetadata plugin2; File file1(blankEsm); @@ -370,7 +390,9 @@ TEST_P(PluginMetadataTest, newMetadataShouldOutputRequirementsDataThatAreNotComm EXPECT_EQ(std::set({file2}), newMetadata.GetRequirements()); } -TEST_P(PluginMetadataTest, newMetadataShouldOutputIncompatibilityDataThatAreNotCommonToBothInputPlugins) { +TEST_P( + PluginMetadataTest, + newMetadataShouldOutputIncompatibilityDataThatAreNotCommonToBothInputPlugins) { PluginMetadata plugin1; PluginMetadata plugin2; File file1(blankEsm); @@ -384,7 +406,8 @@ TEST_P(PluginMetadataTest, newMetadataShouldOutputIncompatibilityDataThatAreNotC EXPECT_EQ(std::set({file2}), newMetadata.GetIncompatibilities()); } -TEST_P(PluginMetadataTest, newMetadataShouldOutputMessagesThatAreNotCommonToBothInputPlugins) { +TEST_P(PluginMetadataTest, + newMetadataShouldOutputMessagesThatAreNotCommonToBothInputPlugins) { PluginMetadata plugin1; PluginMetadata plugin2; Message message1(MessageType::say, "content1"); @@ -398,7 +421,8 @@ TEST_P(PluginMetadataTest, newMetadataShouldOutputMessagesThatAreNotCommonToBoth EXPECT_EQ(std::vector({message2}), newMetadata.GetMessages()); } -TEST_P(PluginMetadataTest, newMetadataShouldOutputTagsThatAreNotCommonToBothInputPlugins) { +TEST_P(PluginMetadataTest, + newMetadataShouldOutputTagsThatAreNotCommonToBothInputPlugins) { PluginMetadata plugin1; PluginMetadata plugin2; Tag tag1("Relev"); @@ -412,7 +436,9 @@ TEST_P(PluginMetadataTest, newMetadataShouldOutputTagsThatAreNotCommonToBothInpu EXPECT_EQ(std::set({tag2}), newMetadata.GetTags()); } -TEST_P(PluginMetadataTest, newMetadataShouldOutputDirtyInfoObjectsThatAreNotCommonToBothInputPlugins) { +TEST_P( + PluginMetadataTest, + newMetadataShouldOutputDirtyInfoObjectsThatAreNotCommonToBothInputPlugins) { PluginMetadata plugin1; PluginMetadata plugin2; PluginCleaningData info1(0x5, "utility", info_, 1, 2, 3); @@ -426,7 +452,9 @@ TEST_P(PluginMetadataTest, newMetadataShouldOutputDirtyInfoObjectsThatAreNotComm EXPECT_EQ(std::set({info2}), newMetadata.GetDirtyInfo()); } -TEST_P(PluginMetadataTest, newMetadataShouldOutputCleanInfoObjectsThatAreNotCommonToBothInputPlugins) { +TEST_P( + PluginMetadataTest, + newMetadataShouldOutputCleanInfoObjectsThatAreNotCommonToBothInputPlugins) { PluginMetadata plugin1; PluginMetadata plugin2; PluginCleaningData info1(0x5, "utility"); @@ -440,7 +468,8 @@ TEST_P(PluginMetadataTest, newMetadataShouldOutputCleanInfoObjectsThatAreNotComm EXPECT_EQ(std::set({info2}), newMetadata.GetCleanInfo()); } -TEST_P(PluginMetadataTest, newMetadataShouldOutputLocationsThatAreNotCommonToBothInputPlugins) { +TEST_P(PluginMetadataTest, + newMetadataShouldOutputLocationsThatAreNotCommonToBothInputPlugins) { PluginMetadata plugin1; PluginMetadata plugin2; Location location1("http://www.example.com/1"); @@ -457,9 +486,11 @@ TEST_P(PluginMetadataTest, newMetadataShouldOutputLocationsThatAreNotCommonToBot TEST_P(PluginMetadataTest, simpleMessagesShouldReturnMessagesAsSimpleMessages) { PluginMetadata plugin; plugin.SetMessages({ - Message(MessageType::say, "content1"), - Message(MessageType::warn, {{"content2",french}, {"other content2", MessageContent::defaultLanguage}}), - Message(MessageType::error, "content3"), + Message(MessageType::say, "content1"), + Message(MessageType::warn, + {{"content2", french}, + {"other content2", MessageContent::defaultLanguage}}), + Message(MessageType::error, "content3"), }); auto simpleMessages = plugin.GetSimpleMessages(french); @@ -476,33 +507,38 @@ TEST_P(PluginMetadataTest, simpleMessagesShouldReturnMessagesAsSimpleMessages) { EXPECT_EQ("content3", simpleMessages.back().text); } -TEST_P(PluginMetadataTest, hasNameOnlyShouldBeTrueForADefaultConstructedPluginMetadataObject) { +TEST_P(PluginMetadataTest, + hasNameOnlyShouldBeTrueForADefaultConstructedPluginMetadataObject) { PluginMetadata plugin; EXPECT_TRUE(plugin.HasNameOnly()); } -TEST_P(PluginMetadataTest, hasNameOnlyShouldBeTrueForAPluginMetadataObjectConstructedWithAName) { +TEST_P(PluginMetadataTest, + hasNameOnlyShouldBeTrueForAPluginMetadataObjectConstructedWithAName) { PluginMetadata plugin(blankEsp); EXPECT_TRUE(plugin.HasNameOnly()); } -TEST_P(PluginMetadataTest, hasNameOnlyShouldBeTrueIfThePluginMetadataIsDisabled) { +TEST_P(PluginMetadataTest, + hasNameOnlyShouldBeTrueIfThePluginMetadataIsDisabled) { PluginMetadata plugin(blankEsp); plugin.SetEnabled(false); EXPECT_TRUE(plugin.HasNameOnly()); } -TEST_P(PluginMetadataTest, hasNameOnlyShouldBeFalseIfTheLocalPriorityIsExplicit) { +TEST_P(PluginMetadataTest, + hasNameOnlyShouldBeFalseIfTheLocalPriorityIsExplicit) { PluginMetadata plugin(blankEsp); plugin.SetLocalPriority(Priority(0)); EXPECT_FALSE(plugin.HasNameOnly()); } -TEST_P(PluginMetadataTest, hasNameOnlyShouldBeFalseIfTheGlobalPriorityIsExplicit) { +TEST_P(PluginMetadataTest, + hasNameOnlyShouldBeFalseIfTheGlobalPriorityIsExplicit) { PluginMetadata plugin(blankEsp); plugin.SetGlobalPriority(Priority(0)); @@ -516,14 +552,16 @@ TEST_P(PluginMetadataTest, hasNameOnlyShouldBeFalseIfLoadAfterMetadataExists) { EXPECT_FALSE(plugin.HasNameOnly()); } -TEST_P(PluginMetadataTest, hasNameOnlyShouldBeFalseIfRequirementMetadataExists) { +TEST_P(PluginMetadataTest, + hasNameOnlyShouldBeFalseIfRequirementMetadataExists) { PluginMetadata plugin(blankEsp); plugin.SetRequirements({File(blankEsm)}); EXPECT_FALSE(plugin.HasNameOnly()); } -TEST_P(PluginMetadataTest, hasNameOnlyShouldBeFalseIfIncompatibilityMetadataExists) { +TEST_P(PluginMetadataTest, + hasNameOnlyShouldBeFalseIfIncompatibilityMetadataExists) { PluginMetadata plugin(blankEsp); plugin.SetIncompatibilities({File(blankEsm)}); @@ -577,37 +615,43 @@ TEST_P(PluginMetadataTest, isRegexPluginShouldBeFalseForAnExactPluginFilename) { EXPECT_FALSE(plugin.IsRegexPlugin()); } -TEST_P(PluginMetadataTest, isRegexPluginShouldBeTrueIfThePluginNameContainsAColon) { +TEST_P(PluginMetadataTest, + isRegexPluginShouldBeTrueIfThePluginNameContainsAColon) { PluginMetadata plugin("Blank:.esm"); EXPECT_TRUE(plugin.IsRegexPlugin()); } -TEST_P(PluginMetadataTest, isRegexPluginShouldBeTrueIfThePluginNameContainsABackslash) { +TEST_P(PluginMetadataTest, + isRegexPluginShouldBeTrueIfThePluginNameContainsABackslash) { PluginMetadata plugin("Blank\\.esm"); EXPECT_TRUE(plugin.IsRegexPlugin()); } -TEST_P(PluginMetadataTest, isRegexPluginShouldBeTrueIfThePluginNameContainsAnAsterisk) { +TEST_P(PluginMetadataTest, + isRegexPluginShouldBeTrueIfThePluginNameContainsAnAsterisk) { PluginMetadata plugin("Blank*.esm"); EXPECT_TRUE(plugin.IsRegexPlugin()); } -TEST_P(PluginMetadataTest, isRegexPluginShouldBeTrueIfThePluginNameContainsAQuestionMark) { +TEST_P(PluginMetadataTest, + isRegexPluginShouldBeTrueIfThePluginNameContainsAQuestionMark) { PluginMetadata plugin("Blank?.esm"); EXPECT_TRUE(plugin.IsRegexPlugin()); } -TEST_P(PluginMetadataTest, isRegexPluginShouldBeTrueIfThePluginNameContainsAVerticalBar) { +TEST_P(PluginMetadataTest, + isRegexPluginShouldBeTrueIfThePluginNameContainsAVerticalBar) { PluginMetadata plugin("Blank|.esm"); EXPECT_TRUE(plugin.IsRegexPlugin()); } -TEST_P(PluginMetadataTest, emittingAsYamlShouldOutputAPluginWithNoMetadataAsABlankString) { +TEST_P(PluginMetadataTest, + emittingAsYamlShouldOutputAPluginWithNoMetadataAsABlankString) { PluginMetadata plugin(blankEsm); YAML::Emitter emitter; emitter << plugin; @@ -615,29 +659,37 @@ TEST_P(PluginMetadataTest, emittingAsYamlShouldOutputAPluginWithNoMetadataAsABla EXPECT_STREQ("", emitter.c_str()); } -TEST_P(PluginMetadataTest, emittingAsYamlShouldOutputAPluginWithAnExplicitLocalPriorityCorrectly) { +TEST_P(PluginMetadataTest, + emittingAsYamlShouldOutputAPluginWithAnExplicitLocalPriorityCorrectly) { PluginMetadata plugin(blankEsm); plugin.SetLocalPriority(Priority(0)); YAML::Emitter emitter; emitter << plugin; - EXPECT_STREQ("name: 'Blank.esm'\n" - "priority: 0", emitter.c_str()); + EXPECT_STREQ( + "name: 'Blank.esm'\n" + "priority: 0", + emitter.c_str()); } -TEST_P(PluginMetadataTest, emittingAsYamlShouldOutputAPluginWithAnExplicitGlobalPriorityCorrectly) { +TEST_P(PluginMetadataTest, + emittingAsYamlShouldOutputAPluginWithAnExplicitGlobalPriorityCorrectly) { PluginMetadata plugin(blankEsm); plugin.SetGlobalPriority(Priority(0)); YAML::Emitter emitter; emitter << plugin; - EXPECT_STREQ("name: 'Blank.esm'\n" - "global_priority: 0", emitter.c_str()); + EXPECT_STREQ( + "name: 'Blank.esm'\n" + "global_priority: 0", + emitter.c_str()); } -TEST_P(PluginMetadataTest, emittingAsYamlShouldOutputAPluginThatIsDisabledAndIsNotNameOnlyCorrectly) { +TEST_P( + PluginMetadataTest, + emittingAsYamlShouldOutputAPluginThatIsDisabledAndIsNotNameOnlyCorrectly) { PluginMetadata plugin(blankEsm); plugin.SetGlobalPriority(Priority(0)); plugin.SetEnabled(false); @@ -645,12 +697,16 @@ TEST_P(PluginMetadataTest, emittingAsYamlShouldOutputAPluginThatIsDisabledAndIsN YAML::Emitter emitter; emitter << plugin; - EXPECT_STREQ("name: 'Blank.esm'\n" - "enabled: false\n" - "global_priority: 0", emitter.c_str()); + EXPECT_STREQ( + "name: 'Blank.esm'\n" + "enabled: false\n" + "global_priority: 0", + emitter.c_str()); } -TEST_P(PluginMetadataTest, emittingAsYamlShouldOutputAPluginThatIsDisabledAndIsNameOnlyAsAnEmptyString) { +TEST_P( + PluginMetadataTest, + emittingAsYamlShouldOutputAPluginThatIsDisabledAndIsNameOnlyAsAnEmptyString) { PluginMetadata plugin(blankEsm); plugin.SetEnabled(false); @@ -660,53 +716,65 @@ TEST_P(PluginMetadataTest, emittingAsYamlShouldOutputAPluginThatIsDisabledAndIsN EXPECT_STREQ("", emitter.c_str()); } -TEST_P(PluginMetadataTest, emittingAsYamlShouldOutputAPluginWithLoadAfterMetadataCorrectly) { +TEST_P(PluginMetadataTest, + emittingAsYamlShouldOutputAPluginWithLoadAfterMetadataCorrectly) { PluginMetadata plugin(blankEsp); plugin.SetLoadAfterFiles({File(blankEsm)}); YAML::Emitter emitter; emitter << plugin; - EXPECT_STREQ("name: 'Blank.esp'\n" - "after:\n" - " - 'Blank.esm'", emitter.c_str()); + EXPECT_STREQ( + "name: 'Blank.esp'\n" + "after:\n" + " - 'Blank.esm'", + emitter.c_str()); } -TEST_P(PluginMetadataTest, emittingAsYamlShouldOutputAPluginWithRequirementsCorrectly) { +TEST_P(PluginMetadataTest, + emittingAsYamlShouldOutputAPluginWithRequirementsCorrectly) { PluginMetadata plugin(blankEsp); plugin.SetRequirements({File(blankEsm)}); YAML::Emitter emitter; emitter << plugin; - EXPECT_STREQ("name: 'Blank.esp'\n" - "req:\n" - " - 'Blank.esm'", emitter.c_str()); + EXPECT_STREQ( + "name: 'Blank.esp'\n" + "req:\n" + " - 'Blank.esm'", + emitter.c_str()); } -TEST_P(PluginMetadataTest, emittingAsYamlShouldOutputAPluginWithIncompatibilitiesCorrectly) { +TEST_P(PluginMetadataTest, + emittingAsYamlShouldOutputAPluginWithIncompatibilitiesCorrectly) { PluginMetadata plugin(blankEsp); plugin.SetIncompatibilities({File(blankEsm)}); YAML::Emitter emitter; emitter << plugin; - EXPECT_STREQ("name: 'Blank.esp'\n" - "inc:\n" - " - 'Blank.esm'", emitter.c_str()); + EXPECT_STREQ( + "name: 'Blank.esp'\n" + "inc:\n" + " - 'Blank.esm'", + emitter.c_str()); } -TEST_P(PluginMetadataTest, emittingAsYamlShouldOutputAPluginWithMessagesCorrectly) { +TEST_P(PluginMetadataTest, + emittingAsYamlShouldOutputAPluginWithMessagesCorrectly) { PluginMetadata plugin(blankEsp); plugin.SetMessages({Message(MessageType::say, "content")}); YAML::Emitter emitter; emitter << plugin; - EXPECT_STREQ("name: 'Blank.esp'\n" - "msg:\n" - " - type: say\n" - " content: 'content'", emitter.c_str()); + EXPECT_STREQ( + "name: 'Blank.esp'\n" + "msg:\n" + " - type: say\n" + " content: 'content'", + emitter.c_str()); } TEST_P(PluginMetadataTest, emittingAsYamlShouldOutputAPluginWithTagsCorrectly) { @@ -716,50 +784,61 @@ TEST_P(PluginMetadataTest, emittingAsYamlShouldOutputAPluginWithTagsCorrectly) { YAML::Emitter emitter; emitter << plugin; - EXPECT_STREQ("name: 'Blank.esp'\n" - "tag:\n" - " - Relev", emitter.c_str()); + EXPECT_STREQ( + "name: 'Blank.esp'\n" + "tag:\n" + " - Relev", + emitter.c_str()); } -TEST_P(PluginMetadataTest, emittingAsYamlShouldOutputAPluginWithDirtyInfoCorrectly) { +TEST_P(PluginMetadataTest, + emittingAsYamlShouldOutputAPluginWithDirtyInfoCorrectly) { PluginMetadata plugin(blankEsp); plugin.SetDirtyInfo({PluginCleaningData(5, "utility", info_, 0, 1, 2)}); YAML::Emitter emitter; emitter << plugin; - EXPECT_STREQ("name: 'Blank.esp'\n" - "dirty:\n" - " - crc: 0x5\n" - " util: 'utility'\n" - " info: 'info'\n" - " udr: 1\n" - " nav: 2", emitter.c_str()); + EXPECT_STREQ( + "name: 'Blank.esp'\n" + "dirty:\n" + " - crc: 0x5\n" + " util: 'utility'\n" + " info: 'info'\n" + " udr: 1\n" + " nav: 2", + emitter.c_str()); } -TEST_P(PluginMetadataTest, emittingAsYamlShouldOutputAPluginWithCleanInfoCorrectly) { +TEST_P(PluginMetadataTest, + emittingAsYamlShouldOutputAPluginWithCleanInfoCorrectly) { PluginMetadata plugin(blankEsp); plugin.SetCleanInfo({PluginCleaningData(5, "utility")}); YAML::Emitter emitter; emitter << plugin; - EXPECT_STREQ("name: 'Blank.esp'\n" - "clean:\n" - " - crc: 0x5\n" - " util: 'utility'", emitter.c_str()); + EXPECT_STREQ( + "name: 'Blank.esp'\n" + "clean:\n" + " - crc: 0x5\n" + " util: 'utility'", + emitter.c_str()); } -TEST_P(PluginMetadataTest, emittingAsYamlShouldOutputAPluginWithLocationsCorrectly) { +TEST_P(PluginMetadataTest, + emittingAsYamlShouldOutputAPluginWithLocationsCorrectly) { PluginMetadata plugin(blankEsp); plugin.SetLocations({Location("http://www.example.com")}); YAML::Emitter emitter; emitter << plugin; - EXPECT_STREQ("name: 'Blank.esp'\n" - "url:\n" - " - 'http://www.example.com'", emitter.c_str()); + EXPECT_STREQ( + "name: 'Blank.esp'\n" + "url:\n" + " - 'http://www.example.com'", + emitter.c_str()); } TEST_P(PluginMetadataTest, encodingAsYamlShouldOmitAllUnsetFields) { @@ -780,7 +859,8 @@ TEST_P(PluginMetadataTest, encodingAsYamlShouldOmitAllUnsetFields) { EXPECT_FALSE(node["url"]); } -TEST_P(PluginMetadataTest, encodingAsYamlShouldSetPriorityFieldIfLocalPriorityIsExplicit) { +TEST_P(PluginMetadataTest, + encodingAsYamlShouldSetPriorityFieldIfLocalPriorityIsExplicit) { PluginMetadata plugin(blankEsp); plugin.SetLocalPriority(Priority(0)); YAML::Node node; @@ -789,7 +869,8 @@ TEST_P(PluginMetadataTest, encodingAsYamlShouldSetPriorityFieldIfLocalPriorityIs EXPECT_EQ(0, node["priority"].as()); } -TEST_P(PluginMetadataTest, encodingAsYamlShouldSetGlobalPriorityFieldIfGlobalPriorityIsExplicit) { +TEST_P(PluginMetadataTest, + encodingAsYamlShouldSetGlobalPriorityFieldIfGlobalPriorityIsExplicit) { PluginMetadata plugin(blankEsp); plugin.SetGlobalPriority(Priority(0)); YAML::Node node; @@ -798,7 +879,8 @@ TEST_P(PluginMetadataTest, encodingAsYamlShouldSetGlobalPriorityFieldIfGlobalPri EXPECT_EQ(0, node["global_priority"].as()); } -TEST_P(PluginMetadataTest, encodingAsYamlShouldNotSetPriorityFieldIfLocalPriorityIsImplicit) { +TEST_P(PluginMetadataTest, + encodingAsYamlShouldNotSetPriorityFieldIfLocalPriorityIsImplicit) { PluginMetadata plugin(blankEsp); YAML::Node node; node = plugin; @@ -806,7 +888,8 @@ TEST_P(PluginMetadataTest, encodingAsYamlShouldNotSetPriorityFieldIfLocalPriorit EXPECT_FALSE(node["priority"]); } -TEST_P(PluginMetadataTest, encodingAsYamlShouldNotSetPriorityFieldIfGlobalPriorityIsImplicit) { +TEST_P(PluginMetadataTest, + encodingAsYamlShouldNotSetPriorityFieldIfGlobalPriorityIsImplicit) { PluginMetadata plugin(blankEsp); YAML::Node node; node = plugin; @@ -823,7 +906,8 @@ TEST_P(PluginMetadataTest, encodingAsYamlShouldSetEnabledFieldIfItIsFalse) { EXPECT_FALSE(node["enabled"].as()); } -TEST_P(PluginMetadataTest, encodingAsYamlShouldSetAfterFieldIfLoadAfterMetadataExists) { +TEST_P(PluginMetadataTest, + encodingAsYamlShouldSetAfterFieldIfLoadAfterMetadataExists) { PluginMetadata plugin(blankEsp); plugin.SetLoadAfterFiles({File(blankEsm)}); YAML::Node node; @@ -841,7 +925,8 @@ TEST_P(PluginMetadataTest, encodingAsYamlShouldSetReqFieldIfRequirementsExist) { EXPECT_EQ(plugin.GetRequirements(), node["req"].as>()); } -TEST_P(PluginMetadataTest, encodingAsYamlShouldSetIncFieldIfIncompatibilitiesExist) { +TEST_P(PluginMetadataTest, + encodingAsYamlShouldSetIncFieldIfIncompatibilitiesExist) { PluginMetadata plugin(blankEsp); plugin.SetIncompatibilities({File(blankEsm)}); YAML::Node node; @@ -874,7 +959,8 @@ TEST_P(PluginMetadataTest, encodingAsYamlShouldSetDirtyFieldIfDirtyInfoExists) { YAML::Node node; node = plugin; - EXPECT_EQ(plugin.GetDirtyInfo(), node["dirty"].as>()); + EXPECT_EQ(plugin.GetDirtyInfo(), + node["dirty"].as>()); } TEST_P(PluginMetadataTest, encodingAsYamlShouldSetCleanFieldIfCleanInfoExists) { @@ -883,7 +969,8 @@ TEST_P(PluginMetadataTest, encodingAsYamlShouldSetCleanFieldIfCleanInfoExists) { YAML::Node node; node = plugin; - EXPECT_EQ(plugin.GetCleanInfo(), node["clean"].as>()); + EXPECT_EQ(plugin.GetCleanInfo(), + node["clean"].as>()); } TEST_P(PluginMetadataTest, encodingAsYamlShouldSetUrlFieldIfLocationsExist) { @@ -895,7 +982,8 @@ TEST_P(PluginMetadataTest, encodingAsYamlShouldSetUrlFieldIfLocationsExist) { EXPECT_EQ(plugin.GetLocations(), node["url"].as>()); } -TEST_P(PluginMetadataTest, decodingFromYamlShouldSetDefaultPriorityValuesIfNoneAreSpecified) { +TEST_P(PluginMetadataTest, + decodingFromYamlShouldSetDefaultPriorityValuesIfNoneAreSpecified) { YAML::Node node = YAML::Load("name: " + blankEsp); PluginMetadata plugin = node.as(); @@ -907,89 +995,84 @@ TEST_P(PluginMetadataTest, decodingFromYamlShouldSetDefaultPriorityValuesIfNoneA } TEST_P(PluginMetadataTest, decodingFromYamlShouldStoreAllGivenData) { - YAML::Node node = YAML::Load("name: 'Blank.esp'\n" - "enabled: false\n" - "priority: 5\n" - "global_priority: 3\n" - "after:\n" - " - 'Blank.esm'\n" - "req:\n" - " - 'Blank.esm'\n" - "inc:\n" - " - 'Blank.esm'\n" - "msg:\n" - " - type: say\n" - " content: 'content'\n" - "tag:\n" - " - Relev\n" - "dirty:\n" - " - crc: 0x5\n" - " util: 'utility'\n" - " udr: 1\n" - " nav: 2\n" - "clean:\n" - " - crc: 0x6\n" - " util: 'utility'\n" - "url:\n" - " - 'http://www.example.com'"); + YAML::Node node = YAML::Load( + "name: 'Blank.esp'\n" + "enabled: false\n" + "priority: 5\n" + "global_priority: 3\n" + "after:\n" + " - 'Blank.esm'\n" + "req:\n" + " - 'Blank.esm'\n" + "inc:\n" + " - 'Blank.esm'\n" + "msg:\n" + " - type: say\n" + " content: 'content'\n" + "tag:\n" + " - Relev\n" + "dirty:\n" + " - crc: 0x5\n" + " util: 'utility'\n" + " udr: 1\n" + " nav: 2\n" + "clean:\n" + " - crc: 0x6\n" + " util: 'utility'\n" + "url:\n" + " - 'http://www.example.com'"); PluginMetadata plugin = node.as(); EXPECT_EQ("Blank.esp", plugin.GetName()); EXPECT_EQ(5, plugin.GetLocalPriority().GetValue()); EXPECT_EQ(3, plugin.GetGlobalPriority().GetValue()); - EXPECT_EQ(std::set({ - File("Blank.esm") - }), plugin.GetLoadAfterFiles()); - EXPECT_EQ(std::set({ - File("Blank.esm") - }), plugin.GetRequirements()); - EXPECT_EQ(std::set({ - File("Blank.esm") - }), plugin.GetIncompatibilities()); - EXPECT_EQ(std::vector({ - Message(MessageType::say, "content") - }), plugin.GetMessages()); - EXPECT_EQ(std::set({ - Tag("Relev") - }), plugin.GetTags()); - EXPECT_EQ(std::set({ - PluginCleaningData(5, "utility", info_, 0, 1, 2) - }), plugin.GetDirtyInfo()); - EXPECT_EQ(std::set({ - PluginCleaningData(6, "utility") - }), plugin.GetCleanInfo()); - EXPECT_EQ(std::set({ - Location("http://www.example.com") - }), plugin.GetLocations()); + EXPECT_EQ(std::set({File("Blank.esm")}), plugin.GetLoadAfterFiles()); + EXPECT_EQ(std::set({File("Blank.esm")}), plugin.GetRequirements()); + EXPECT_EQ(std::set({File("Blank.esm")}), plugin.GetIncompatibilities()); + EXPECT_EQ(std::vector({Message(MessageType::say, "content")}), + plugin.GetMessages()); + EXPECT_EQ(std::set({Tag("Relev")}), plugin.GetTags()); + EXPECT_EQ(std::set( + {PluginCleaningData(5, "utility", info_, 0, 1, 2)}), + plugin.GetDirtyInfo()); + EXPECT_EQ(std::set({PluginCleaningData(6, "utility")}), + plugin.GetCleanInfo()); + EXPECT_EQ(std::set({Location("http://www.example.com")}), + plugin.GetLocations()); } -TEST_P(PluginMetadataTest, decodingFromYamlWithDirtyInfoInARegexPluginMetadataObjectShouldThrow) { - YAML::Node node = YAML::Load("name: 'Blank\\.esp'\n" - "dirty:\n" - " - crc: 0x5\n" - " util: 'utility'\n" - " udr: 1\n" - " nav: 2"); +TEST_P(PluginMetadataTest, + decodingFromYamlWithDirtyInfoInARegexPluginMetadataObjectShouldThrow) { + YAML::Node node = YAML::Load( + "name: 'Blank\\.esp'\n" + "dirty:\n" + " - crc: 0x5\n" + " util: 'utility'\n" + " udr: 1\n" + " nav: 2"); EXPECT_THROW(node.as(), YAML::RepresentationException); } -TEST_P(PluginMetadataTest, decodingFromYamlWithCleanInfoInARegexPluginMetadataObjectShouldThrow) { - YAML::Node node = YAML::Load("name: 'Blank\\.esp'\n" - "clean:\n" - " - crc: 0x5\n" - " util: 'utility'"); +TEST_P(PluginMetadataTest, + decodingFromYamlWithCleanInfoInARegexPluginMetadataObjectShouldThrow) { + YAML::Node node = YAML::Load( + "name: 'Blank\\.esp'\n" + "clean:\n" + " - crc: 0x5\n" + " util: 'utility'"); EXPECT_THROW(node.as(), YAML::RepresentationException); } TEST_P(PluginMetadataTest, decodingFromYamlWithAnInvalidRegexNameShouldThrow) { - YAML::Node node = YAML::Load("name: 'RagnvaldBook(Farengar(+Ragnvald)?)?\\.esp'\n" - "dirty:\n" - " - crc: 0x5\n" - " util: 'utility'\n" - " udr: 1\n" - " nav: 2"); + YAML::Node node = YAML::Load( + "name: 'RagnvaldBook(Farengar(+Ragnvald)?)?\\.esp'\n" + "dirty:\n" + " - crc: 0x5\n" + " util: 'utility'\n" + " udr: 1\n" + " nav: 2"); EXPECT_THROW(node.as(), YAML::RepresentationException); } diff --git a/src/tests/api/internals/metadata/tag_test.h b/src/tests/api/internals/metadata/tag_test.h index 0cdbf9f8..3593ed73 100644 --- a/src/tests/api/internals/metadata/tag_test.h +++ b/src/tests/api/internals/metadata/tag_test.h @@ -33,7 +33,8 @@ along with LOOT. If not, see namespace loot { namespace test { -TEST(Tag, defaultConstructorShouldSetEmptyNameAndConditionStringsForATagAddition) { +TEST(Tag, + defaultConstructorShouldSetEmptyNameAndConditionStringsForATagAddition) { Tag tag; EXPECT_TRUE(tag.GetName().empty()); @@ -49,7 +50,8 @@ TEST(Tag, dataConstructorShouldSetFieldsToGivenValues) { EXPECT_EQ("condition", tag.GetCondition()); } -TEST(Tag, tagsWithCaseInsensitiveEqualNamesAndEqualAdditionStatesShouldBeEqual) { +TEST(Tag, + tagsWithCaseInsensitiveEqualNamesAndEqualAdditionStatesShouldBeEqual) { Tag tag1("Name", true, "condition1"); Tag tag2("name", true, "condition2"); @@ -70,7 +72,9 @@ TEST(Tag, tagsWithUnequalAdditionStatesShouldNotBeEqual) { EXPECT_FALSE(tag1 == tag2); } -TEST(Tag, lessThanOperatorShouldCaseInsensitivelyLexicographicallyCompareNameStrings) { +TEST( + Tag, + lessThanOperatorShouldCaseInsensitivelyLexicographicallyCompareNameStrings) { Tag tag1("Name"); Tag tag2("name"); @@ -92,7 +96,9 @@ TEST(Tag, lessThanOperatorShouldTreatTagAdditionsAsBeingLessThanRemovals) { EXPECT_FALSE(tag2 < tag1); } -TEST(Tag, emittingAsYamlShouldOutputOnlyTheNameStringIfTheTagIsAnAdditionWithNoCondition) { +TEST( + Tag, + emittingAsYamlShouldOutputOnlyTheNameStringIfTheTagIsAnAdditionWithNoCondition) { Tag tag("name1"); YAML::Emitter emitter; emitter << tag; @@ -100,7 +106,9 @@ TEST(Tag, emittingAsYamlShouldOutputOnlyTheNameStringIfTheTagIsAnAdditionWithNoC EXPECT_EQ(tag.GetName(), emitter.c_str()); } -TEST(Tag, emittingAsYamlShouldOutputOnlyTheNameStringPrefixedWithAHyphenIfTheTagIsARemovalWithNoCondition) { +TEST( + Tag, + emittingAsYamlShouldOutputOnlyTheNameStringPrefixedWithAHyphenIfTheTagIsARemovalWithNoCondition) { Tag tag("name1", false); YAML::Emitter emitter; emitter << tag; @@ -116,7 +124,8 @@ TEST(Tag, emittingAsYamlShouldOutputAMapIfTheTagHasACondition) { EXPECT_STREQ("name: -name1\ncondition: 'condition1'", emitter.c_str()); } -TEST(Tag, encodingAsYamlShouldOmitTheConditionFieldIfTheConditionStringIsEmpty) { +TEST(Tag, + encodingAsYamlShouldOmitTheConditionFieldIfTheConditionStringIsEmpty) { Tag tag; YAML::Node node; node = tag; @@ -132,7 +141,9 @@ TEST(Tag, encodingAsYamlShouldOutputTheNameFieldCorrectly) { EXPECT_EQ(tag.GetName(), node["name"].as()); } -TEST(Tag, encodingAsYamlShouldOutputTheNameFieldWithAHyphenPrefixIfTheTagIsARemoval) { +TEST( + Tag, + encodingAsYamlShouldOutputTheNameFieldWithAHyphenPrefixIfTheTagIsARemoval) { Tag tag("name1", false); YAML::Node node; node = tag; @@ -140,7 +151,9 @@ TEST(Tag, encodingAsYamlShouldOutputTheNameFieldWithAHyphenPrefixIfTheTagIsARemo EXPECT_EQ("-" + tag.GetName(), node["name"].as()); } -TEST(Tag, encodingAsYamlShouldOutputTheConditionFieldIfTheConditionStringIsNotEmpty) { +TEST( + Tag, + encodingAsYamlShouldOutputTheConditionFieldIfTheConditionStringIsNotEmpty) { Tag tag("name1", true, "condition1"); YAML::Node node; node = tag; diff --git a/src/tests/api/internals/metadata_list_test.h b/src/tests/api/internals/metadata_list_test.h index 6d6f41ba..e93a2e76 100644 --- a/src/tests/api/internals/metadata_list_test.h +++ b/src/tests/api/internals/metadata_list_test.h @@ -34,12 +34,11 @@ namespace test { class MetadataListTest : public CommonGameTestFixture { protected: MetadataListTest() : - metadataPath("./testing-metadata/masterlist.yaml"), - savedMetadataPath("./testing-metadata/saved.masterlist.yaml"), - missingMetadataPath("./missing-metadata.yaml"), - invalidMetadataPaths({ - "./testing-metadata/invalid/non_map_root.yaml", - "./testing-metadata/invalid/non_unique.yaml"}) {} + metadataPath("./testing-metadata/masterlist.yaml"), + savedMetadataPath("./testing-metadata/saved.masterlist.yaml"), + missingMetadataPath("./missing-metadata.yaml"), + invalidMetadataPaths({"./testing-metadata/invalid/non_map_root.yaml", + "./testing-metadata/invalid/non_unique.yaml"}) {} inline virtual void SetUp() { CommonGameTestFixture::SetUp(); @@ -75,18 +74,16 @@ protected: // Pass an empty first argument, as it's a prefix for the test instantation, // but we only have the one so no prefix is necessary. -INSTANTIATE_TEST_CASE_P(, - MetadataListTest, - ::testing::Values( - GameType::tes4)); +INSTANTIATE_TEST_CASE_P(, MetadataListTest, ::testing::Values(GameType::tes4)); TEST_P(MetadataListTest, loadShouldLoadGlobalMessages) { MetadataList metadataList; EXPECT_NO_THROW(metadataList.Load(metadataPath)); EXPECT_EQ(std::vector({ - Message(MessageType::say, "A global message."), - }), metadataList.Messages()); + Message(MessageType::say, "A global message."), + }), + metadataList.Messages()); } TEST_P(MetadataListTest, loadShouldLoadPluginMetadata) { @@ -98,27 +95,25 @@ TEST_P(MetadataListTest, loadShouldLoadPluginMetadata) { // comparison. std::list result(metadataList.Plugins()); std::set names; - std::transform(begin(result), - end(result), - std::insert_iterator>(names, begin(names)), - &MetadataListTest::PluginMetadataToString); + std::transform( + begin(result), + end(result), + std::insert_iterator>(names, begin(names)), + &MetadataListTest::PluginMetadataToString); - EXPECT_EQ(std::set({ - blankEsm, - blankEsp, - "Blank.+\\.esp", - "Blank.+(Different)?.*\\.esp", - }), names); + EXPECT_EQ( + std::set({ + blankEsm, blankEsp, "Blank.+\\.esp", "Blank.+(Different)?.*\\.esp", + }), + names); } TEST_P(MetadataListTest, loadShouldLoadBashTags) { MetadataList metadataList; ASSERT_NO_THROW(metadataList.Load(metadataPath)); - EXPECT_EQ(std::set({ - "C.Climate", - "Relev" - }), metadataList.BashTags()); + EXPECT_EQ(std::set({"C.Climate", "Relev"}), + metadataList.BashTags()); } TEST_P(MetadataListTest, loadShouldThrowIfAnInvalidMetadataFileIsGiven) { @@ -128,7 +123,8 @@ TEST_P(MetadataListTest, loadShouldThrowIfAnInvalidMetadataFileIsGiven) { } } -TEST_P(MetadataListTest, loadShouldClearExistingDataIfAnInvalidMetadataFileIsGiven) { +TEST_P(MetadataListTest, + loadShouldClearExistingDataIfAnInvalidMetadataFileIsGiven) { MetadataList metadataList; ASSERT_NO_THROW(metadataList.Load(metadataPath)); @@ -142,7 +138,8 @@ TEST_P(MetadataListTest, loadShouldClearExistingDataIfAnInvalidMetadataFileIsGiv EXPECT_TRUE(metadataList.BashTags().empty()); } -TEST_P(MetadataListTest, loadShouldClearExistingDataIfAMissingMetadataFileIsGiven) { +TEST_P(MetadataListTest, + loadShouldClearExistingDataIfAMissingMetadataFileIsGiven) { MetadataList metadataList; ASSERT_NO_THROW(metadataList.Load(metadataPath)); @@ -167,30 +164,29 @@ TEST_P(MetadataListTest, saveShouldWriteTheLoadedMetadataToTheGivenFilePath) { // Check the new file contains the same metadata. EXPECT_NO_THROW(metadataList.Load(savedMetadataPath)); - EXPECT_EQ(std::set({ - "C.Climate", - "Relev" - }), metadataList.BashTags()); + EXPECT_EQ(std::set({"C.Climate", "Relev"}), + metadataList.BashTags()); EXPECT_EQ(std::vector({ - Message(MessageType::say, "A global message."), - }), metadataList.Messages()); + Message(MessageType::say, "A global message."), + }), + metadataList.Messages()); // Non-regex plugins can be outputted in any order, and regex entries can // match each other, so convert the list to a set of strings for // comparison. std::list result(metadataList.Plugins()); std::set names; - std::transform(begin(result), - end(result), - std::insert_iterator>(names, begin(names)), - &MetadataListTest::PluginMetadataToString); - EXPECT_EQ(std::set({ - blankEsm, - blankEsp, - "Blank.+\\.esp", - "Blank.+(Different)?.*\\.esp", - }), names); + std::transform( + begin(result), + end(result), + std::insert_iterator>(names, begin(names)), + &MetadataListTest::PluginMetadataToString); + EXPECT_EQ( + std::set({ + blankEsm, blankEsp, "Blank.+\\.esp", "Blank.+(Different)?.*\\.esp", + }), + names); } TEST_P(MetadataListTest, clearShouldClearLoadedData) { @@ -206,33 +202,42 @@ TEST_P(MetadataListTest, clearShouldClearLoadedData) { EXPECT_TRUE(metadataList.BashTags().empty()); } -TEST_P(MetadataListTest, findPluginShouldReturnAnEmptyPluginObjectIfTheGivenPluginIsNotInTheMetadataList) { +TEST_P( + MetadataListTest, + findPluginShouldReturnAnEmptyPluginObjectIfTheGivenPluginIsNotInTheMetadataList) { MetadataList metadataList; - PluginMetadata plugin = metadataList.FindPlugin(PluginMetadata(blankDifferentEsm)); + PluginMetadata plugin = + metadataList.FindPlugin(PluginMetadata(blankDifferentEsm)); EXPECT_EQ(blankDifferentEsm, plugin.GetName()); EXPECT_TRUE(plugin.HasNameOnly()); } -TEST_P(MetadataListTest, findPluginShouldReturnTheMetadataObjectInTheMetadataListIfOneExistsForTheGivenPlugin) { +TEST_P( + MetadataListTest, + findPluginShouldReturnTheMetadataObjectInTheMetadataListIfOneExistsForTheGivenPlugin) { MetadataList metadataList; ASSERT_NO_THROW(metadataList.Load(metadataPath)); - PluginMetadata plugin = metadataList.FindPlugin(PluginMetadata(blankDifferentEsp)); + PluginMetadata plugin = + metadataList.FindPlugin(PluginMetadata(blankDifferentEsp)); EXPECT_EQ(blankDifferentEsp, plugin.GetName()); EXPECT_EQ(std::set({ - File(blankEsm), - }), plugin.GetLoadAfterFiles()); + File(blankEsm), + }), + plugin.GetLoadAfterFiles()); EXPECT_EQ(std::set({ - File(blankEsp), - }), plugin.GetIncompatibilities()); + File(blankEsp), + }), + plugin.GetIncompatibilities()); } TEST_P(MetadataListTest, addPluginShouldStoreGivenSpecificPluginMetadata) { MetadataList metadataList; ASSERT_NO_THROW(metadataList.Load(metadataPath)); - ASSERT_TRUE(metadataList.FindPlugin(PluginMetadata(blankDifferentEsm)).HasNameOnly()); + ASSERT_TRUE( + metadataList.FindPlugin(PluginMetadata(blankDifferentEsm)).HasNameOnly()); PluginMetadata plugin(blankDifferentEsm); plugin.SetLocalPriority(Priority(100)); @@ -265,10 +270,12 @@ TEST_P(MetadataListTest, addPluginShouldThrowIfAMatchingPluginAlreadyExists) { ASSERT_EQ(blankEsm, plugin.GetName()); ASSERT_FALSE(plugin.HasNameOnly()); - EXPECT_THROW(metadataList.AddPlugin(PluginMetadata(blankEsm)), std::invalid_argument); + EXPECT_THROW(metadataList.AddPlugin(PluginMetadata(blankEsm)), + std::invalid_argument); } -TEST_P(MetadataListTest, erasePluginShouldRemoveStoredMetadataForTheGivenPlugin) { +TEST_P(MetadataListTest, + erasePluginShouldRemoveStoredMetadataForTheGivenPlugin) { MetadataList metadataList; ASSERT_NO_THROW(metadataList.Load(metadataPath)); @@ -283,18 +290,26 @@ TEST_P(MetadataListTest, erasePluginShouldRemoveStoredMetadataForTheGivenPlugin) EXPECT_TRUE(plugin.HasNameOnly()); } -TEST_P(MetadataListTest, evalAllConditionsShouldEvaluateTheConditionsForThePluginsStoredInTeMetadataList) { +TEST_P( + MetadataListTest, + evalAllConditionsShouldEvaluateTheConditionsForThePluginsStoredInTeMetadataList) { Game game(GetParam(), dataPath.parent_path(), localPath); - ConditionEvaluator evaluator(game.Type(), game.DataPath(), game.GetCache(), game.GetLoadOrderHandler()); + ConditionEvaluator evaluator(game.Type(), + game.DataPath(), + game.GetCache(), + game.GetLoadOrderHandler()); MetadataList metadataList; ASSERT_NO_THROW(metadataList.Load(metadataPath)); PluginMetadata plugin = metadataList.FindPlugin(PluginMetadata(blankEsm)); - ASSERT_EQ(std::vector({ - Message(MessageType::warn, "This is a warning."), - Message(MessageType::say, "This message should be removed when evaluating conditions."), - }), plugin.GetMessages()); + ASSERT_EQ( + std::vector({ + Message(MessageType::warn, "This is a warning."), + Message(MessageType::say, + "This message should be removed when evaluating conditions."), + }), + plugin.GetMessages()); plugin = metadataList.FindPlugin(PluginMetadata(blankEsp)); ASSERT_EQ(blankEsp, plugin.GetName()); @@ -304,8 +319,9 @@ TEST_P(MetadataListTest, evalAllConditionsShouldEvaluateTheConditionsForThePlugi plugin = metadataList.FindPlugin(PluginMetadata(blankEsm)); EXPECT_EQ(std::vector({ - Message(MessageType::warn, "This is a warning."), - }), plugin.GetMessages()); + Message(MessageType::warn, "This is a warning."), + }), + plugin.GetMessages()); plugin = metadataList.FindPlugin(PluginMetadata(blankEsp)); EXPECT_EQ(blankEsp, plugin.GetName()); diff --git a/src/tests/api/internals/plugin/plugin_sorter_test.h b/src/tests/api/internals/plugin/plugin_sorter_test.h index 67b03b26..b5b2a970 100644 --- a/src/tests/api/internals/plugin/plugin_sorter_test.h +++ b/src/tests/api/internals/plugin/plugin_sorter_test.h @@ -38,17 +38,17 @@ protected: void loadInstalledPlugins(Game& game_, bool headersOnly) { const std::vector plugins({ - masterFile, - blankEsm, - blankDifferentEsm, - blankMasterDependentEsm, - blankDifferentMasterDependentEsm, - blankEsp, - blankDifferentEsp, - blankMasterDependentEsp, - blankDifferentMasterDependentEsp, - blankPluginDependentEsp, - blankDifferentPluginDependentEsp, + masterFile, + blankEsm, + blankDifferentEsm, + blankMasterDependentEsm, + blankDifferentMasterDependentEsm, + blankEsp, + blankDifferentEsp, + blankMasterDependentEsp, + blankDifferentMasterDependentEsp, + blankPluginDependentEsp, + blankDifferentPluginDependentEsp, }); game_.IdentifyMainMasterFile(masterFile); game_.LoadPlugins(plugins, headersOnly); @@ -59,10 +59,7 @@ protected: // Pass an empty first argument, as it's a prefix for the test instantation, // but we only have the one so no prefix is necessary. -INSTANTIATE_TEST_CASE_P(, - PluginSorterTest, - ::testing::Values( - GameType::tes4)); +INSTANTIATE_TEST_CASE_P(, PluginSorterTest, ::testing::Values(GameType::tes4)); TEST_P(PluginSorterTest, sortingWithNoLoadedPluginsShouldReturnAnEmptyList) { PluginSorter sorter; @@ -71,18 +68,21 @@ TEST_P(PluginSorterTest, sortingWithNoLoadedPluginsShouldReturnAnEmptyList) { EXPECT_TRUE(sorted.empty()); } -TEST_P(PluginSorterTest, sortingShouldNotMakeUnnecessaryChangesToAnExistingLoadOrder) { +TEST_P(PluginSorterTest, + sortingShouldNotMakeUnnecessaryChangesToAnExistingLoadOrder) { ASSERT_NO_THROW(loadInstalledPlugins(game_, false)); PluginSorter ps; std::vector expectedSortedOrder = getLoadOrder(); std::vector sorted = ps.Sort(game_); - EXPECT_TRUE(std::equal(begin(sorted), end(sorted), begin(expectedSortedOrder))); + EXPECT_TRUE( + std::equal(begin(sorted), end(sorted), begin(expectedSortedOrder))); // Check stability. sorted = ps.Sort(game_); - EXPECT_TRUE(std::equal(begin(sorted), end(sorted), begin(expectedSortedOrder))); + EXPECT_TRUE( + std::equal(begin(sorted), end(sorted), begin(expectedSortedOrder))); } TEST_P(PluginSorterTest, sortingShouldEvaluateRelativeGlobalPriorities) { @@ -110,7 +110,9 @@ TEST_P(PluginSorterTest, sortingShouldEvaluateRelativeGlobalPriorities) { EXPECT_EQ(expectedSortedOrder, sorted); } -TEST_P(PluginSorterTest, sortingWithGlobalPrioritiesShouldInheritRecursivelyRegardlessOfEvaluationOrder) { +TEST_P( + PluginSorterTest, + sortingWithGlobalPrioritiesShouldInheritRecursivelyRegardlessOfEvaluationOrder) { ASSERT_NO_THROW(loadInstalledPlugins(game_, false)); // Set Blank.esp's priority. @@ -122,7 +124,7 @@ TEST_P(PluginSorterTest, sortingWithGlobalPrioritiesShouldInheritRecursivelyRega // inherits Blank.esp's priority. plugin = PluginMetadata(blankMasterDependentEsp); plugin.SetLoadAfterFiles({ - File(blankEsp), + File(blankEsp), }); game_.GetDatabase()->SetPluginUserMetadata(plugin); @@ -130,7 +132,7 @@ TEST_P(PluginSorterTest, sortingWithGlobalPrioritiesShouldInheritRecursivelyRega // that it inherits its inherited priority. plugin = PluginMetadata(blankDifferentEsp); plugin.SetLoadAfterFiles({ - File(blankMasterDependentEsp), + File(blankMasterDependentEsp), }); game_.GetDatabase()->SetPluginUserMetadata(plugin); @@ -143,29 +145,29 @@ TEST_P(PluginSorterTest, sortingWithGlobalPrioritiesShouldInheritRecursivelyRega PluginSorter ps; std::vector expectedSortedOrder({ - masterFile, - blankEsm, - blankDifferentEsm, - blankMasterDependentEsm, - blankDifferentMasterDependentEsm, - blankDifferentMasterDependentEsp, - blankEsp, - blankMasterDependentEsp, - blankDifferentEsp, - blankPluginDependentEsp, - blankDifferentPluginDependentEsp, + masterFile, + blankEsm, + blankDifferentEsm, + blankMasterDependentEsm, + blankDifferentMasterDependentEsm, + blankDifferentMasterDependentEsp, + blankEsp, + blankMasterDependentEsp, + blankDifferentEsp, + blankPluginDependentEsp, + blankDifferentPluginDependentEsp, }); std::vector sorted = ps.Sort(game_); EXPECT_EQ(expectedSortedOrder, sorted); } -TEST_P(PluginSorterTest, sortingShouldUseLoadAfterMetadataWhenDecidingRelativePluginPositions) { +TEST_P(PluginSorterTest, + sortingShouldUseLoadAfterMetadataWhenDecidingRelativePluginPositions) { ASSERT_NO_THROW(loadInstalledPlugins(game_, false)); PluginMetadata plugin(blankEsp); plugin.SetLoadAfterFiles({ - File(blankDifferentEsp), - File(blankDifferentPluginDependentEsp), + File(blankDifferentEsp), File(blankDifferentPluginDependentEsp), }); game_.GetDatabase()->SetPluginUserMetadata(plugin); @@ -188,12 +190,12 @@ TEST_P(PluginSorterTest, sortingShouldUseLoadAfterMetadataWhenDecidingRelativePl EXPECT_EQ(expectedSortedOrder, sorted); } -TEST_P(PluginSorterTest, sortingShouldUseRequirementMetadataWhenDecidingRelativePluginPositions) { +TEST_P(PluginSorterTest, + sortingShouldUseRequirementMetadataWhenDecidingRelativePluginPositions) { ASSERT_NO_THROW(loadInstalledPlugins(game_, false)); PluginMetadata plugin(blankEsp); plugin.SetRequirements({ - File(blankDifferentEsp), - File(blankDifferentPluginDependentEsp), + File(blankDifferentEsp), File(blankDifferentPluginDependentEsp), }); game_.GetDatabase()->SetPluginUserMetadata(plugin); diff --git a/src/tests/api/internals/plugin/plugin_test.h b/src/tests/api/internals/plugin/plugin_test.h index 6c26bca3..45523fb5 100644 --- a/src/tests/api/internals/plugin/plugin_test.h +++ b/src/tests/api/internals/plugin/plugin_test.h @@ -35,12 +35,13 @@ namespace test { class PluginTest : public CommonGameTestFixture { protected: PluginTest() : - emptyFile("EmptyFile.esm"), - lowercaseBlankEsp("blank.esp"), - blankEsl("blank.esl"), - game_(GetParam(), dataPath.parent_path(), localPath), - blankArchive("Blank" + GetArchiveFileExtension(game_.Type())), - blankSuffixArchive("Blank - Different - suffix" + GetArchiveFileExtension(game_.Type())) {} + emptyFile("EmptyFile.esm"), + lowercaseBlankEsp("blank.esp"), + blankEsl("blank.esl"), + game_(GetParam(), dataPath.parent_path(), localPath), + blankArchive("Blank" + GetArchiveFileExtension(game_.Type())), + blankSuffixArchive("Blank - Different - suffix" + + GetArchiveFileExtension(game_.Type())) {} void SetUp() { CommonGameTestFixture::SetUp(); @@ -53,10 +54,12 @@ protected: ASSERT_TRUE(boost::filesystem::exists(dataPath / emptyFile)); #ifndef _WIN32 - ASSERT_NO_THROW(boost::filesystem::copy(dataPath / blankEsp, dataPath / lowercaseBlankEsp)); + ASSERT_NO_THROW(boost::filesystem::copy(dataPath / blankEsp, + dataPath / lowercaseBlankEsp)); #endif - ASSERT_NO_THROW(boost::filesystem::copy(dataPath / blankEsp, dataPath / blankEsl)); + ASSERT_NO_THROW( + boost::filesystem::copy(dataPath / blankEsp, dataPath / blankEsl)); // Create dummy archive files. out.open(dataPath / blankArchive); @@ -84,6 +87,7 @@ protected: const std::string blankEsl; const std::string blankArchive; const std::string blankSuffixArchive; + private: static std::string GetArchiveFileExtension(const GameType gameType) { if (gameType == GameType::fo4) @@ -98,7 +102,9 @@ public: std::string GetName() const { return ""; } std::string GetLowercasedName() const { return ""; } std::string GetVersion() const { return ""; } - std::vector GetMasters() const { return std::vector(); } + std::vector GetMasters() const { + return std::vector(); + } std::set GetBashTags() const { return std::set(); } uint32_t GetCRC() const { return 0; } @@ -113,16 +119,19 @@ public: // but we only have the one so no prefix is necessary. INSTANTIATE_TEST_CASE_P(, PluginTest, - ::testing::Values( - GameType::tes4, - GameType::tes5, - GameType::fo3, - GameType::fonv, - GameType::fo4, - GameType::tes5se)); + ::testing::Values(GameType::tes4, + GameType::tes5, + GameType::fo3, + GameType::fonv, + GameType::fo4, + GameType::tes5se)); TEST_P(PluginTest, loadingHeaderOnlyShouldReadHeaderData) { - Plugin plugin(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), blankEsm, true); + Plugin plugin(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + blankEsm, + true); EXPECT_EQ(blankEsm, plugin.GetName()); EXPECT_TRUE(plugin.GetMasters().empty()); @@ -132,13 +141,21 @@ TEST_P(PluginTest, loadingHeaderOnlyShouldReadHeaderData) { } TEST_P(PluginTest, loadingHeaderOnlyShouldNotReadFieldsOrCalculateCrc) { - Plugin plugin(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), blankEsm, true); + Plugin plugin(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + blankEsm, + true); EXPECT_EQ(0, plugin.GetCRC()); } TEST_P(PluginTest, loadingWholePluginShouldReadHeaderData) { - Plugin plugin(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), blankEsm, true); + Plugin plugin(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + blankEsm, + true); EXPECT_EQ(blankEsm, plugin.GetName()); EXPECT_TRUE(plugin.GetMasters().empty()); @@ -148,47 +165,88 @@ TEST_P(PluginTest, loadingWholePluginShouldReadHeaderData) { } TEST_P(PluginTest, loadingWholePluginShouldReadFields) { - Plugin plugin(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), blankMasterDependentEsm, false); + Plugin plugin(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + blankMasterDependentEsm, + false); EXPECT_EQ(4, plugin.NumOverrideFormIDs()); } TEST_P(PluginTest, loadingWholePluginShouldCalculateCrc) { - Plugin plugin(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), blankEsm, false); + Plugin plugin(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + blankEsm, + false); EXPECT_EQ(blankEsmCrc, plugin.GetCRC()); } TEST_P(PluginTest, loadingANonMasterPluginShouldReadTheMasterFlagAsFalse) { - Plugin plugin(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), blankMasterDependentEsp, true); + Plugin plugin(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + blankMasterDependentEsp, + true); EXPECT_FALSE(plugin.IsMaster()); } -TEST_P(PluginTest, isLightMasterShouldBeTrueForAPluginWithEslFileExtensionForFallout4AndSkyrimSeAndFalseOtherwise) { - Plugin plugin1(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), blankEsm, true); - Plugin plugin2(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), blankMasterDependentEsp, true); - Plugin plugin3(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), blankEsl, true); +TEST_P( + PluginTest, + isLightMasterShouldBeTrueForAPluginWithEslFileExtensionForFallout4AndSkyrimSeAndFalseOtherwise) { + Plugin plugin1(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + blankEsm, + true); + Plugin plugin2(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + blankMasterDependentEsp, + true); + Plugin plugin3(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + blankEsl, + true); EXPECT_FALSE(plugin1.IsLightMaster()); EXPECT_FALSE(plugin2.IsLightMaster()); - EXPECT_EQ(GetParam() == GameType::fo4 || GetParam() == GameType::tes5se, plugin3.IsLightMaster()); + EXPECT_EQ(GetParam() == GameType::fo4 || GetParam() == GameType::tes5se, + plugin3.IsLightMaster()); } TEST_P(PluginTest, loadingAPluginWithMastersShouldReadThemCorrectly) { - Plugin plugin(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), blankMasterDependentEsp, true); + Plugin plugin(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + blankMasterDependentEsp, + true); - EXPECT_EQ(std::vector({ - blankEsm - }), plugin.GetMasters()); + EXPECT_EQ(std::vector({blankEsm}), plugin.GetMasters()); } TEST_P(PluginTest, loadingAPluginThatDoesNotExistShouldThrow) { - EXPECT_THROW(Plugin(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), "Blank\\.esp", true), FileAccessError); + EXPECT_THROW(Plugin(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + "Blank\\.esp", + true), + FileAccessError); } -TEST_P(PluginTest, loadsArchiveForAnArchiveThatExactlyMatchesAnEsmFileBasenameShouldReturnTrueForAllGamesExceptOblivion) { - bool loadsArchive = Plugin(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), blankEsm, true).LoadsArchive(); +TEST_P( + PluginTest, + loadsArchiveForAnArchiveThatExactlyMatchesAnEsmFileBasenameShouldReturnTrueForAllGamesExceptOblivion) { + bool loadsArchive = Plugin(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + blankEsm, + true) + .LoadsArchive(); if (GetParam() == GameType::tes4) EXPECT_FALSE(loadsArchive); @@ -196,12 +254,26 @@ TEST_P(PluginTest, loadsArchiveForAnArchiveThatExactlyMatchesAnEsmFileBasenameSh EXPECT_TRUE(loadsArchive); } -TEST_P(PluginTest, loadsArchiveForAnArchiveThatExactlyMatchesAnEspFileBasenameShouldReturnTrue) { - EXPECT_TRUE(Plugin(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), blankEsp, true).LoadsArchive()); +TEST_P( + PluginTest, + loadsArchiveForAnArchiveThatExactlyMatchesAnEspFileBasenameShouldReturnTrue) { + EXPECT_TRUE(Plugin(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + blankEsp, + true) + .LoadsArchive()); } -TEST_P(PluginTest, loadsArchiveForAnArchiveWithAFilenameWhichStartsWithTheEsmFileBasenameShouldReturnTrueForAllGamesExceptOblivionAndSkyrim) { - bool loadsArchive = Plugin(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), blankDifferentEsm, true).LoadsArchive(); +TEST_P( + PluginTest, + loadsArchiveForAnArchiveWithAFilenameWhichStartsWithTheEsmFileBasenameShouldReturnTrueForAllGamesExceptOblivionAndSkyrim) { + bool loadsArchive = Plugin(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + blankDifferentEsm, + true) + .LoadsArchive(); if (GetParam() == GameType::tes4 || GetParam() == GameType::tes5) EXPECT_FALSE(loadsArchive); @@ -209,8 +281,15 @@ TEST_P(PluginTest, loadsArchiveForAnArchiveWithAFilenameWhichStartsWithTheEsmFil EXPECT_TRUE(loadsArchive); } -TEST_P(PluginTest, loadsArchiveForAnArchiveWithAFilenameWhichStartsWithTheEspFileBasenameShouldReturnTrueForAllGamesExceptSkyrim) { - bool loadsArchive = Plugin(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), blankDifferentEsp, true).LoadsArchive(); +TEST_P( + PluginTest, + loadsArchiveForAnArchiveWithAFilenameWhichStartsWithTheEspFileBasenameShouldReturnTrueForAllGamesExceptSkyrim) { + bool loadsArchive = Plugin(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + blankDifferentEsp, + true) + .LoadsArchive(); if (GetParam() == GameType::tes5) EXPECT_FALSE(loadsArchive); @@ -218,8 +297,14 @@ TEST_P(PluginTest, loadsArchiveForAnArchiveWithAFilenameWhichStartsWithTheEspFil EXPECT_TRUE(loadsArchive); } -TEST_P(PluginTest, loadsArchiveShouldReturnFalseForAPluginThatDoesNotLoadAnArchive) { - EXPECT_FALSE(Plugin(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), blankMasterDependentEsp, true).LoadsArchive()); +TEST_P(PluginTest, + loadsArchiveShouldReturnFalseForAPluginThatDoesNotLoadAnArchive) { + EXPECT_FALSE(Plugin(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + blankMasterDependentEsp, + true) + .LoadsArchive()); } TEST_P(PluginTest, isValidShouldReturnTrueForAValidPlugin) { @@ -235,69 +320,132 @@ TEST_P(PluginTest, isValidShouldReturnFalseForAnEmptyFile) { } TEST_P(PluginTest, isActiveShouldReturnTrueForAPluginThatIsActive) { - EXPECT_TRUE(Plugin(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), blankEsm, true).IsActive()); + EXPECT_TRUE(Plugin(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + blankEsm, + true) + .IsActive()); } TEST_P(PluginTest, isActiveShouldReturnFalseForAPluginThatIsNotActive) { - EXPECT_FALSE(Plugin(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), blankEsp, true).IsActive()); + EXPECT_FALSE(Plugin(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + blankEsp, + true) + .IsActive()); } -TEST_P(PluginTest, lessThanOperatorShouldUseCaseInsensitiveLexicographicalNameComparison) { - Plugin plugin1(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), blankEsp, true); - Plugin plugin2(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), lowercaseBlankEsp, true); +TEST_P(PluginTest, + lessThanOperatorShouldUseCaseInsensitiveLexicographicalNameComparison) { + Plugin plugin1(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + blankEsp, + true); + Plugin plugin2(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + lowercaseBlankEsp, + true); EXPECT_FALSE(plugin1 < plugin2); EXPECT_FALSE(plugin2 < plugin1); - Plugin plugin3 = Plugin(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), blankEsm, true); - Plugin plugin4 = Plugin(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), blankEsp, true); + Plugin plugin3 = Plugin(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + blankEsm, + true); + Plugin plugin4 = Plugin(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + blankEsp, + true); EXPECT_TRUE(plugin3 < plugin4); EXPECT_FALSE(plugin4 < plugin3); } -TEST_P(PluginTest, doFormIDsOverlapShouldReturnFalseIfTheArgumentIsNotAPluginObject) { - Plugin plugin1(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), blankEsm, false); +TEST_P(PluginTest, + doFormIDsOverlapShouldReturnFalseIfTheArgumentIsNotAPluginObject) { + Plugin plugin1(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + blankEsm, + false); OtherPluginType plugin2; EXPECT_FALSE(plugin1.DoFormIDsOverlap(plugin2)); EXPECT_TRUE(plugin2.DoFormIDsOverlap(plugin1)); } -TEST_P(PluginTest, doFormIDsOverlapShouldReturnFalseForTwoPluginsWithOnlyHeadersLoaded) { - Plugin plugin1(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), blankEsm, true); - Plugin plugin2(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), blankMasterDependentEsm, true); +TEST_P(PluginTest, + doFormIDsOverlapShouldReturnFalseForTwoPluginsWithOnlyHeadersLoaded) { + Plugin plugin1(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + blankEsm, + true); + Plugin plugin2(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + blankMasterDependentEsm, + true); EXPECT_FALSE(plugin1.DoFormIDsOverlap(plugin2)); EXPECT_FALSE(plugin2.DoFormIDsOverlap(plugin1)); } -TEST_P(PluginTest, doFormIDsOverlapShouldReturnFalseIfThePluginsHaveUnrelatedRecords) { - Plugin plugin1(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), blankEsm, false); - Plugin plugin2(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), blankEsp, false); +TEST_P(PluginTest, + doFormIDsOverlapShouldReturnFalseIfThePluginsHaveUnrelatedRecords) { + Plugin plugin1(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + blankEsm, + false); + Plugin plugin2(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + blankEsp, + false); EXPECT_FALSE(plugin1.DoFormIDsOverlap(plugin2)); EXPECT_FALSE(plugin2.DoFormIDsOverlap(plugin1)); } -TEST_P(PluginTest, doFormIDsOverlapShouldReturnTrueIfOnePluginOverridesTheOthersRecords) { - Plugin plugin1(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), blankEsm, false); - Plugin plugin2(game_.Type(), game_.DataPath(), game_.GetLoadOrderHandler(), blankMasterDependentEsm, false); +TEST_P(PluginTest, + doFormIDsOverlapShouldReturnTrueIfOnePluginOverridesTheOthersRecords) { + Plugin plugin1(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + blankEsm, + false); + Plugin plugin2(game_.Type(), + game_.DataPath(), + game_.GetLoadOrderHandler(), + blankMasterDependentEsm, + false); EXPECT_TRUE(plugin1.DoFormIDsOverlap(plugin2)); EXPECT_TRUE(plugin2.DoFormIDsOverlap(plugin1)); } -TEST_P(PluginTest, hasPluginFileExtensionShouldBeTrueIfFileEndsInDotEspOrDotEsm) { +TEST_P(PluginTest, + hasPluginFileExtensionShouldBeTrueIfFileEndsInDotEspOrDotEsm) { EXPECT_TRUE(hasPluginFileExtension("file.esp", GetParam())); EXPECT_TRUE(hasPluginFileExtension("file.esm", GetParam())); EXPECT_FALSE(hasPluginFileExtension("file.bsa", GetParam())); } -TEST_P(PluginTest, hasPluginFileExtensionShouldBeTrueIfFileEndsInDotEslOnlyForFallout4AndSkyrimSE) { +TEST_P( + PluginTest, + hasPluginFileExtensionShouldBeTrueIfFileEndsInDotEslOnlyForFallout4AndSkyrimSE) { bool result = hasPluginFileExtension("file.esl", GetParam()); - EXPECT_EQ(GetParam() == GameType::fo4 || GetParam() == GameType::tes5se, result); + EXPECT_EQ(GetParam() == GameType::fo4 || GetParam() == GameType::tes5se, + result); } } } diff --git a/src/tests/common_game_test_fixture.h b/src/tests/common_game_test_fixture.h index f220b270..477f4987 100644 --- a/src/tests/common_game_test_fixture.h +++ b/src/tests/common_game_test_fixture.h @@ -28,10 +28,10 @@ along with LOOT. If not, see #include #include +#include #include #include #include -#include #include "loot/enum/game_type.h" @@ -40,27 +40,30 @@ namespace test { class CommonGameTestFixture : public ::testing::TestWithParam { protected: CommonGameTestFixture() : - french("fr"), - german("de"), - missingPath("./missing"), - dataPath(getPluginsPath()), - localPath(getLocalPath()), - lootDataPath("./local/LOOT"), - masterFile(getMasterFile()), - missingEsp("Blank.missing.esp"), - nonPluginFile("NotAPlugin.esm"), - invalidPlugin("Invalid.esm"), - blankEsm("Blank.esm"), - blankDifferentEsm("Blank - Different.esm"), - blankMasterDependentEsm("Blank - Master Dependent.esm"), - blankDifferentMasterDependentEsm("Blank - Different Master Dependent.esm"), - blankEsp("Blank.esp"), - blankDifferentEsp("Blank - Different.esp"), - blankMasterDependentEsp("Blank - Master Dependent.esp"), - blankDifferentMasterDependentEsp("Blank - Different Master Dependent.esp"), - blankPluginDependentEsp("Blank - Plugin Dependent.esp"), - blankDifferentPluginDependentEsp("Blank - Different Plugin Dependent.esp"), - blankEsmCrc(getBlankEsmCrc()) { + french("fr"), + german("de"), + missingPath("./missing"), + dataPath(getPluginsPath()), + localPath(getLocalPath()), + lootDataPath("./local/LOOT"), + masterFile(getMasterFile()), + missingEsp("Blank.missing.esp"), + nonPluginFile("NotAPlugin.esm"), + invalidPlugin("Invalid.esm"), + blankEsm("Blank.esm"), + blankDifferentEsm("Blank - Different.esm"), + blankMasterDependentEsm("Blank - Master Dependent.esm"), + blankDifferentMasterDependentEsm( + "Blank - Different Master Dependent.esm"), + blankEsp("Blank.esp"), + blankDifferentEsp("Blank - Different.esp"), + blankMasterDependentEsp("Blank - Master Dependent.esp"), + blankDifferentMasterDependentEsp( + "Blank - Different Master Dependent.esp"), + blankPluginDependentEsp("Blank - Plugin Dependent.esp"), + blankDifferentPluginDependentEsp( + "Blank - Different Plugin Dependent.esp"), + blankEsmCrc(getBlankEsmCrc()) { assertInitialState(); } @@ -75,26 +78,34 @@ protected: ASSERT_TRUE(boost::filesystem::exists(dataPath / blankEsm)); ASSERT_TRUE(boost::filesystem::exists(dataPath / blankDifferentEsm)); ASSERT_TRUE(boost::filesystem::exists(dataPath / blankMasterDependentEsm)); - ASSERT_TRUE(boost::filesystem::exists(dataPath / blankDifferentMasterDependentEsm)); + ASSERT_TRUE( + boost::filesystem::exists(dataPath / blankDifferentMasterDependentEsm)); ASSERT_TRUE(boost::filesystem::exists(dataPath / blankEsp)); ASSERT_TRUE(boost::filesystem::exists(dataPath / blankDifferentEsp)); ASSERT_TRUE(boost::filesystem::exists(dataPath / blankMasterDependentEsp)); - ASSERT_TRUE(boost::filesystem::exists(dataPath / blankDifferentMasterDependentEsp)); + ASSERT_TRUE( + boost::filesystem::exists(dataPath / blankDifferentMasterDependentEsp)); ASSERT_TRUE(boost::filesystem::exists(dataPath / blankPluginDependentEsp)); - ASSERT_TRUE(boost::filesystem::exists(dataPath / blankDifferentPluginDependentEsp)); + ASSERT_TRUE( + boost::filesystem::exists(dataPath / blankDifferentPluginDependentEsp)); // Make sure the game master file exists. ASSERT_FALSE(boost::filesystem::exists(dataPath / masterFile)); - ASSERT_NO_THROW(boost::filesystem::copy_file(dataPath / blankEsm, dataPath / masterFile)); + ASSERT_NO_THROW(boost::filesystem::copy_file(dataPath / blankEsm, + dataPath / masterFile)); ASSERT_TRUE(boost::filesystem::exists(dataPath / masterFile)); // Set initial load order and active plugins. setLoadOrder(getInitialLoadOrder()); // Ghost a plugin. - ASSERT_FALSE(boost::filesystem::exists(dataPath / (blankMasterDependentEsm + ".ghost"))); - ASSERT_NO_THROW(boost::filesystem::rename(dataPath / blankMasterDependentEsm, dataPath / (blankMasterDependentEsm + ".ghost"))); - ASSERT_TRUE(boost::filesystem::exists(dataPath / (blankMasterDependentEsm + ".ghost"))); + ASSERT_FALSE(boost::filesystem::exists( + dataPath / (blankMasterDependentEsm + ".ghost"))); + ASSERT_NO_THROW(boost::filesystem::rename( + dataPath / blankMasterDependentEsm, + dataPath / (blankMasterDependentEsm + ".ghost"))); + ASSERT_TRUE(boost::filesystem::exists( + dataPath / (blankMasterDependentEsm + ".ghost"))); // Write out an non-empty, non-plugin file. boost::filesystem::ofstream out(dataPath / nonPluginFile); @@ -110,9 +121,13 @@ protected: ASSERT_NO_THROW(boost::filesystem::remove(dataPath / masterFile)); // Unghost the ghosted plugin. - ASSERT_TRUE(boost::filesystem::exists(dataPath / (blankMasterDependentEsm + ".ghost"))); - ASSERT_NO_THROW(boost::filesystem::rename(dataPath / (blankMasterDependentEsm + ".ghost"), dataPath / blankMasterDependentEsm)); - ASSERT_FALSE(boost::filesystem::exists(dataPath / (blankMasterDependentEsm + ".ghost"))); + ASSERT_TRUE(boost::filesystem::exists( + dataPath / (blankMasterDependentEsm + ".ghost"))); + ASSERT_NO_THROW(boost::filesystem::rename( + dataPath / (blankMasterDependentEsm + ".ghost"), + dataPath / blankMasterDependentEsm)); + ASSERT_FALSE(boost::filesystem::exists( + dataPath / (blankMasterDependentEsm + ".ghost"))); ASSERT_NO_THROW(boost::filesystem::remove(dataPath / nonPluginFile)); ASSERT_NO_THROW(boost::filesystem::remove(dataPath / invalidPlugin)); @@ -138,19 +153,22 @@ protected: std::vector actual; if (isLoadOrderTimestampBased(GetParam())) { std::map loadOrder; - for (boost::filesystem::directory_iterator it(dataPath); it != boost::filesystem::directory_iterator(); ++it) { + for (boost::filesystem::directory_iterator it(dataPath); + it != boost::filesystem::directory_iterator(); + ++it) { if (boost::filesystem::is_regular_file(it->status())) { std::string filename = it->path().filename().string(); if (filename == nonPluginFile) continue; if (boost::ends_with(filename, ".ghost")) filename = it->path().stem().string(); - if (boost::ends_with(filename, ".esp") || boost::ends_with(filename, ".esm")) - loadOrder.emplace(boost::filesystem::last_write_time(it->path()), filename); + if (boost::ends_with(filename, ".esp") || + boost::ends_with(filename, ".esm")) + loadOrder.emplace(boost::filesystem::last_write_time(it->path()), + filename); } } - for (const auto& plugin : loadOrder) - actual.push_back(plugin.second); + for (const auto& plugin : loadOrder) actual.push_back(plugin.second); } else if (GetParam() == GameType::tes5) { boost::filesystem::ifstream in(localPath / "loadorder.txt"); while (in) { @@ -173,17 +191,17 @@ protected: inline std::vector> getInitialLoadOrder() const { return std::vector>({ - {masterFile, true}, - {blankEsm, true}, - {blankDifferentEsm, false}, - {blankMasterDependentEsm, false}, - {blankDifferentMasterDependentEsm, false}, - {blankEsp, false}, - {blankDifferentEsp, false}, - {blankMasterDependentEsp, false}, - {blankDifferentMasterDependentEsp, true}, - {blankPluginDependentEsp, false}, - {blankDifferentPluginDependentEsp, false}, + {masterFile, true}, + {blankEsm, true}, + {blankDifferentEsm, false}, + {blankMasterDependentEsm, false}, + {blankDifferentMasterDependentEsm, false}, + {blankEsp, false}, + {blankDifferentEsp, false}, + {blankMasterDependentEsp, false}, + {blankDifferentMasterDependentEsp, true}, + {blankPluginDependentEsp, false}, + {blankDifferentPluginDependentEsp, false}, }); } @@ -248,9 +266,10 @@ private: return 0x187BE342; } - void setLoadOrder(const std::vector>& loadOrder) const { + void setLoadOrder( + const std::vector>& loadOrder) const { boost::filesystem::ofstream out(localPath / "plugins.txt"); - for (const auto &plugin : loadOrder) { + for (const auto& plugin : loadOrder) { if (GetParam() == GameType::fo4 || GetParam() == GameType::tes5se) { if (plugin.second) out << '*'; @@ -262,23 +281,27 @@ private: if (isLoadOrderTimestampBased(GetParam())) { time_t modificationTime = time(NULL); // Current time. - for (const auto &plugin : loadOrder) { - if (boost::filesystem::exists(dataPath / boost::filesystem::path(plugin.first + ".ghost"))) { - boost::filesystem::last_write_time(dataPath / boost::filesystem::path(plugin.first + ".ghost"), modificationTime); + for (const auto& plugin : loadOrder) { + if (boost::filesystem::exists( + dataPath / boost::filesystem::path(plugin.first + ".ghost"))) { + boost::filesystem::last_write_time( + dataPath / boost::filesystem::path(plugin.first + ".ghost"), + modificationTime); } else { - boost::filesystem::last_write_time(dataPath / plugin.first, modificationTime); + boost::filesystem::last_write_time(dataPath / plugin.first, + modificationTime); } modificationTime += 60; } } else if (GetParam() == GameType::tes5) { boost::filesystem::ofstream out(localPath / "loadorder.txt"); - for (const auto &plugin : loadOrder) - out << plugin.first << std::endl; + for (const auto& plugin : loadOrder) out << plugin.first << std::endl; } } inline static bool isLoadOrderTimestampBased(GameType gameType) { - return gameType == GameType::tes4 || gameType == GameType::fo3 || gameType == GameType::fonv; + return gameType == GameType::tes4 || gameType == GameType::fo3 || + gameType == GameType::fonv; } }; } diff --git a/src/tests/printers.h b/src/tests/printers.h index e80455a9..43b73fc2 100644 --- a/src/tests/printers.h +++ b/src/tests/printers.h @@ -29,28 +29,28 @@ along with LOOT. If not, see #include +#include "api/metadata/message_content.h" +#include "api/plugin/plugin.h" #include "loot/metadata/file.h" #include "loot/metadata/location.h" #include "loot/metadata/message.h" -#include "api/metadata/message_content.h" #include "loot/metadata/plugin_cleaning_data.h" #include "loot/metadata/plugin_metadata.h" #include "loot/metadata/tag.h" -#include "api/plugin/plugin.h" namespace loot { namespace test { void PrintTo(const File& value, ::std::ostream* os) { *os << "File(\"" << value.GetName() << "\", " - << "\"" << value.GetDisplayName() << "\", " - << "\"" << value.GetCondition() << "\"" - << ")"; + << "\"" << value.GetDisplayName() << "\", " + << "\"" << value.GetCondition() << "\"" + << ")"; } void PrintTo(const Location& value, ::std::ostream* os) { *os << "Location(\"" << value.GetURL() << "\", " - << "\"" << value.GetName() << "\", " - << ")"; + << "\"" << value.GetName() << "\", " + << ")"; } void PrintTo(const Message& value, ::std::ostream* os) { @@ -63,27 +63,24 @@ void PrintTo(const Message& value, ::std::ostream* os) { type = "say"; *os << "Message(\"" << type << "\", " - << ::testing::PrintToString(value.GetContent()) << ", " - << "\"" << value.GetCondition() << "\"" - << ")"; + << ::testing::PrintToString(value.GetContent()) << ", " + << "\"" << value.GetCondition() << "\"" + << ")"; } void PrintTo(const MessageContent& value, ::std::ostream* os) { *os << "MessageContent(\"" << value.GetText() << "\", " - << "\"" << Language(value.GetLanguage()).GetName() << "\"" - << ")"; + << "\"" << Language(value.GetLanguage()).GetName() << "\"" + << ")"; } void PrintTo(const PluginCleaningData& value, ::std::ostream* os) { - *os << "PluginCleaningData(0x" - << std::hex << std::uppercase - << value.GetCRC() - << std::nouppercase << std::dec << ", " - << value.GetITMCount() << ", " - << value.GetDeletedReferenceCount() << ", " - << value.GetDeletedNavmeshCount() << ", " - << "\"" << value.GetCleaningUtility() << "\"" - << ")"; + *os << "PluginCleaningData(0x" << std::hex << std::uppercase << value.GetCRC() + << std::nouppercase << std::dec << ", " << value.GetITMCount() << ", " + << value.GetDeletedReferenceCount() << ", " + << value.GetDeletedNavmeshCount() << ", " + << "\"" << value.GetCleaningUtility() << "\"" + << ")"; } void PrintTo(const PluginMetadata& value, ::std::ostream* os) { @@ -91,10 +88,9 @@ void PrintTo(const PluginMetadata& value, ::std::ostream* os) { } void PrintTo(const Tag& value, ::std::ostream* os) { - *os << "Tag(\"" << value.GetName() << "\", " - << value.IsAddition() << ", " - << "\"" << value.GetCondition() << "\"" - << ")"; + *os << "Tag(\"" << value.GetName() << "\", " << value.IsAddition() << ", " + << "\"" << value.GetCondition() << "\"" + << ")"; } void PrintTo(const Plugin& value, ::std::ostream* os) {