3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 #include <json/json.h>
24 #include "content/mods.h"
27 #include "content/subgames.h"
30 #include "convert_json.h"
31 #include "script/common/c_internal.h"
33 void ModSpec::checkAndLog() const
35 if (!string_allowed(name, MODNAME_ALLOWED_CHARS)) {
36 throw ModError("Error loading mod \"" + name +
37 "\": Mod name does not follow naming conventions: "
38 "Only characters [a-z0-9_] are allowed.");
41 // Log deprecation messages
42 auto handling_mode = get_deprecated_handling_mode();
43 if (!deprecation_msgs.empty() && handling_mode != DeprecatedHandlingMode::Ignore) {
44 std::ostringstream os;
45 os << "Mod " << name << " at " << path << ":" << std::endl;
46 for (auto msg : deprecation_msgs)
47 os << "\t" << msg << std::endl;
49 if (handling_mode == DeprecatedHandlingMode::Error)
50 throw ModError(os.str());
52 warningstream << os.str();
56 bool parseDependsString(std::string &dep, std::unordered_set<char> &symbols)
60 size_t pos = dep.size();
62 !string_allowed(dep.substr(pos - 1, 1), MODNAME_ALLOWED_CHARS)) {
63 // last character is a symbol, not part of the modname
64 symbols.insert(dep[pos - 1]);
67 dep = trim(dep.substr(0, pos));
71 void parseModContents(ModSpec &spec)
73 // NOTE: this function works in mutual recursion with getModsInPath
76 spec.optdepends.clear();
77 spec.is_modpack = false;
78 spec.modpack_content.clear();
80 // Handle modpacks (defined by containing modpack.txt)
81 std::ifstream modpack_is((spec.path + DIR_DELIM + "modpack.txt").c_str());
82 std::ifstream modpack2_is((spec.path + DIR_DELIM + "modpack.conf").c_str());
83 if (modpack_is.good() || modpack2_is.good()) {
84 if (modpack_is.good())
87 if (modpack2_is.good())
90 spec.is_modpack = true;
91 spec.modpack_content = getModsInPath(spec.path, true);
95 info.readConfigFile((spec.path + DIR_DELIM + "mod.conf").c_str());
97 if (info.exists("name"))
98 spec.name = info.get("name");
100 spec.deprecation_msgs.push_back("Mods not having a mod.conf file with the name is deprecated.");
102 if (info.exists("author"))
103 spec.author = info.get("author");
105 if (info.exists("release"))
106 spec.release = info.getS32("release");
108 // Attempt to load dependencies from mod.conf
109 bool mod_conf_has_depends = false;
110 if (info.exists("depends")) {
111 mod_conf_has_depends = true;
112 std::string dep = info.get("depends");
114 dep.erase(std::remove_if(dep.begin(), dep.end(),
115 static_cast<int (*)(int)>(&std::isspace)), dep.end());
117 for (const auto &dependency : str_split(dep, ',')) {
118 spec.depends.insert(dependency);
122 if (info.exists("optional_depends")) {
123 mod_conf_has_depends = true;
124 std::string dep = info.get("optional_depends");
126 dep.erase(std::remove_if(dep.begin(), dep.end(),
127 static_cast<int (*)(int)>(&std::isspace)), dep.end());
129 for (const auto &dependency : str_split(dep, ',')) {
130 spec.optdepends.insert(dependency);
134 // Fallback to depends.txt
135 if (!mod_conf_has_depends) {
136 std::vector<std::string> dependencies;
138 std::ifstream is((spec.path + DIR_DELIM + "depends.txt").c_str());
141 spec.deprecation_msgs.push_back("depends.txt is deprecated, please use mod.conf instead.");
145 std::getline(is, dep);
146 dependencies.push_back(dep);
149 for (auto &dependency : dependencies) {
150 std::unordered_set<char> symbols;
151 if (parseDependsString(dependency, symbols)) {
152 if (symbols.count('?') != 0) {
153 spec.optdepends.insert(dependency);
155 spec.depends.insert(dependency);
161 if (info.exists("description"))
162 spec.desc = info.get("description");
163 else if (fs::ReadFile(spec.path + DIR_DELIM + "description.txt", spec.desc))
164 spec.deprecation_msgs.push_back("description.txt is deprecated, please use mod.conf instead.");
168 std::map<std::string, ModSpec> getModsInPath(
169 const std::string &path, bool part_of_modpack)
171 // NOTE: this function works in mutual recursion with parseModContents
173 std::map<std::string, ModSpec> result;
174 std::vector<fs::DirListNode> dirlist = fs::GetDirListing(path);
177 for (const fs::DirListNode &dln : dirlist) {
181 const std::string &modname = dln.name;
182 // Ignore all directories beginning with a ".", especially
183 // VCS directories like ".git" or ".svn"
184 if (modname[0] == '.')
188 modpath.append(path).append(DIR_DELIM).append(modname);
190 ModSpec spec(modname, modpath, part_of_modpack);
191 parseModContents(spec);
192 result.insert(std::make_pair(modname, spec));
197 std::vector<ModSpec> flattenMods(const std::map<std::string, ModSpec> &mods)
199 std::vector<ModSpec> result;
200 for (const auto &it : mods) {
201 const ModSpec &mod = it.second;
202 if (mod.is_modpack) {
203 std::vector<ModSpec> content = flattenMods(mod.modpack_content);
204 result.reserve(result.size() + content.size());
205 result.insert(result.end(), content.begin(), content.end());
207 } else // not a modpack
209 result.push_back(mod);
215 ModConfiguration::ModConfiguration(const std::string &worldpath)
219 void ModConfiguration::printUnsatisfiedModsError() const
221 for (const ModSpec &mod : m_unsatisfied_mods) {
222 errorstream << "mod \"" << mod.name
223 << "\" has unsatisfied dependencies: ";
224 for (const std::string &unsatisfied_depend : mod.unsatisfied_depends)
225 errorstream << " \"" << unsatisfied_depend << "\"";
226 errorstream << std::endl;
230 void ModConfiguration::addModsInPath(const std::string &path)
232 addMods(flattenMods(getModsInPath(path)));
235 void ModConfiguration::addMods(const std::vector<ModSpec> &new_mods)
237 // Maintain a map of all existing m_unsatisfied_mods.
238 // Keys are mod names and values are indices into m_unsatisfied_mods.
239 std::map<std::string, u32> existing_mods;
240 for (u32 i = 0; i < m_unsatisfied_mods.size(); ++i) {
241 existing_mods[m_unsatisfied_mods[i].name] = i;
245 for (int want_from_modpack = 1; want_from_modpack >= 0; --want_from_modpack) {
247 // Add all the mods that come from modpacks
249 // Add all the mods that didn't come from modpacks
251 std::set<std::string> seen_this_iteration;
253 for (const ModSpec &mod : new_mods) {
254 if (mod.part_of_modpack != (bool)want_from_modpack)
257 if (existing_mods.count(mod.name) == 0) {
258 // GOOD CASE: completely new mod.
259 m_unsatisfied_mods.push_back(mod);
260 existing_mods[mod.name] = m_unsatisfied_mods.size() - 1;
261 } else if (seen_this_iteration.count(mod.name) == 0) {
262 // BAD CASE: name conflict in different levels.
263 u32 oldindex = existing_mods[mod.name];
264 const ModSpec &oldmod = m_unsatisfied_mods[oldindex];
265 warningstream << "Mod name conflict detected: \""
266 << mod.name << "\"" << std::endl
267 << "Will not load: " << oldmod.path
269 << "Overridden by: " << mod.path
271 m_unsatisfied_mods[oldindex] = mod;
273 // If there was a "VERY BAD CASE" name conflict
274 // in an earlier level, ignore it.
275 m_name_conflicts.erase(mod.name);
277 // VERY BAD CASE: name conflict in the same level.
278 u32 oldindex = existing_mods[mod.name];
279 const ModSpec &oldmod = m_unsatisfied_mods[oldindex];
280 warningstream << "Mod name conflict detected: \""
281 << mod.name << "\"" << std::endl
282 << "Will not load: " << oldmod.path
284 << "Will not load: " << mod.path
286 m_unsatisfied_mods[oldindex] = mod;
287 m_name_conflicts.insert(mod.name);
290 seen_this_iteration.insert(mod.name);
295 void ModConfiguration::addModsFromConfig(
296 const std::string &settings_path, const std::set<std::string> &mods)
299 std::set<std::string> load_mod_names;
301 conf.readConfigFile(settings_path.c_str());
302 std::vector<std::string> names = conf.getNames();
303 for (const std::string &name : names) {
304 if (name.compare(0, 9, "load_mod_") == 0 && conf.get(name) != "false" &&
305 conf.get(name) != "nil")
306 load_mod_names.insert(name.substr(9));
309 std::vector<ModSpec> addon_mods;
310 for (const std::string &i : mods) {
311 std::vector<ModSpec> addon_mods_in_path = flattenMods(getModsInPath(i));
312 for (std::vector<ModSpec>::const_iterator it = addon_mods_in_path.begin();
313 it != addon_mods_in_path.end(); ++it) {
314 const ModSpec &mod = *it;
315 if (load_mod_names.count(mod.name) != 0)
316 addon_mods.push_back(mod);
318 conf.setBool("load_mod_" + mod.name, false);
321 conf.updateConfigFile(settings_path.c_str());
324 checkConflictsAndDeps();
326 // complain about mods declared to be loaded, but not found
327 for (const ModSpec &addon_mod : addon_mods)
328 load_mod_names.erase(addon_mod.name);
330 std::vector<ModSpec> unsatisfiedMods = getUnsatisfiedMods();
332 for (const ModSpec &unsatisfiedMod : unsatisfiedMods)
333 load_mod_names.erase(unsatisfiedMod.name);
335 if (!load_mod_names.empty()) {
336 errorstream << "The following mods could not be found:";
337 for (const std::string &mod : load_mod_names)
338 errorstream << " \"" << mod << "\"";
339 errorstream << std::endl;
343 void ModConfiguration::checkConflictsAndDeps()
345 // report on name conflicts
346 if (!m_name_conflicts.empty()) {
347 std::string s = "Unresolved name conflicts for mods ";
348 for (std::unordered_set<std::string>::const_iterator it =
349 m_name_conflicts.begin();
350 it != m_name_conflicts.end(); ++it) {
351 if (it != m_name_conflicts.begin())
353 s += std::string("\"") + (*it) + "\"";
359 // get the mods in order
360 resolveDependencies();
363 void ModConfiguration::resolveDependencies()
365 // Step 1: Compile a list of the mod names we're working with
366 std::set<std::string> modnames;
367 for (const ModSpec &mod : m_unsatisfied_mods) {
368 modnames.insert(mod.name);
371 // Step 2: get dependencies (including optional dependencies)
372 // of each mod, split mods into satisfied and unsatisfied
373 std::list<ModSpec> satisfied;
374 std::list<ModSpec> unsatisfied;
375 for (ModSpec mod : m_unsatisfied_mods) {
376 mod.unsatisfied_depends = mod.depends;
377 // check which optional dependencies actually exist
378 for (const std::string &optdep : mod.optdepends) {
379 if (modnames.count(optdep) != 0)
380 mod.unsatisfied_depends.insert(optdep);
382 // if a mod has no depends it is initially satisfied
383 if (mod.unsatisfied_depends.empty())
384 satisfied.push_back(mod);
386 unsatisfied.push_back(mod);
389 // Step 3: mods without unmet dependencies can be appended to
391 while (!satisfied.empty()) {
392 ModSpec mod = satisfied.back();
393 m_sorted_mods.push_back(mod);
394 satisfied.pop_back();
395 for (auto it = unsatisfied.begin(); it != unsatisfied.end();) {
397 mod2.unsatisfied_depends.erase(mod.name);
398 if (mod2.unsatisfied_depends.empty()) {
399 satisfied.push_back(mod2);
400 it = unsatisfied.erase(it);
407 // Step 4: write back list of unsatisfied mods
408 m_unsatisfied_mods.assign(unsatisfied.begin(), unsatisfied.end());
412 ClientModConfiguration::ClientModConfiguration(const std::string &path) :
413 ModConfiguration(path)
415 std::set<std::string> paths;
416 std::string path_user = porting::path_user + DIR_DELIM + "clientmods";
418 paths.insert(path_user);
420 std::string settings_path = path_user + DIR_DELIM + "mods.conf";
421 addModsFromConfig(settings_path, paths);
425 ModMetadata::ModMetadata(const std::string &mod_name) : m_mod_name(mod_name)
429 void ModMetadata::clear()
435 bool ModMetadata::save(const std::string &root_path)
438 for (StringMap::const_iterator it = m_stringvars.begin();
439 it != m_stringvars.end(); ++it) {
440 json[it->first] = it->second;
443 if (!fs::PathExists(root_path)) {
444 if (!fs::CreateAllDirs(root_path)) {
445 errorstream << "ModMetadata[" << m_mod_name
446 << "]: Unable to save. '" << root_path
447 << "' tree cannot be created." << std::endl;
450 } else if (!fs::IsDir(root_path)) {
451 errorstream << "ModMetadata[" << m_mod_name << "]: Unable to save. '"
452 << root_path << "' is not a directory." << std::endl;
456 bool w_ok = fs::safeWriteToFile(
457 root_path + DIR_DELIM + m_mod_name, fastWriteJson(json));
462 errorstream << "ModMetadata[" << m_mod_name << "]: failed write file."
468 bool ModMetadata::load(const std::string &root_path)
470 m_stringvars.clear();
472 std::ifstream is((root_path + DIR_DELIM + m_mod_name).c_str(),
473 std::ios_base::binary);
479 Json::CharReaderBuilder builder;
480 builder.settings_["collectComments"] = false;
483 if (!Json::parseFromStream(builder, is, &root, &errs)) {
484 errorstream << "ModMetadata[" << m_mod_name
485 << "]: failed read data "
486 "(Json decoding failure). Message: "
487 << errs << std::endl;
491 const Json::Value::Members attr_list = root.getMemberNames();
492 for (const auto &it : attr_list) {
493 Json::Value attr_value = root[it];
494 m_stringvars[it] = attr_value.asString();
500 bool ModMetadata::setString(const std::string &name, const std::string &var)
502 m_modified = Metadata::setString(name, var);