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"
32 bool parseDependsString(std::string &dep, std::unordered_set<char> &symbols)
36 size_t pos = dep.size();
38 !string_allowed(dep.substr(pos - 1, 1), MODNAME_ALLOWED_CHARS)) {
39 // last character is a symbol, not part of the modname
40 symbols.insert(dep[pos - 1]);
43 dep = trim(dep.substr(0, pos));
47 void parseModContents(ModSpec &spec)
49 // NOTE: this function works in mutual recursion with getModsInPath
51 info.readConfigFile((spec.path + DIR_DELIM + "mod.conf").c_str());
53 if (info.exists("name"))
54 spec.name = info.get("name");
56 if (info.exists("author"))
57 spec.author = info.get("author");
60 spec.optdepends.clear();
61 spec.is_modpack = false;
62 spec.modpack_content.clear();
64 // Handle modpacks (defined by containing modpack.txt)
65 std::ifstream modpack_is((spec.path + DIR_DELIM + "modpack.txt").c_str());
66 if (modpack_is.good()) { // a modpack, recursively get the mods in it
67 modpack_is.close(); // We don't actually need the file
68 spec.is_modpack = true;
69 spec.modpack_content = getModsInPath(spec.path, true);
70 // modpacks have no dependencies; they are defined and
71 // tracked separately for each mod in the modpack
74 // Attempt to load dependencies from mod.conf
75 bool mod_conf_has_depends = false;
76 if (info.exists("depends")) {
77 mod_conf_has_depends = true;
78 std::string dep = info.get("depends");
80 dep.erase(std::remove_if(dep.begin(), dep.end(),
81 static_cast<int (*)(int)>(&std::isspace)), dep.end());
83 for (const auto &dependency : str_split(dep, ',')) {
84 spec.depends.insert(dependency);
88 if (info.exists("optional_depends")) {
89 mod_conf_has_depends = true;
90 std::string dep = info.get("optional_depends");
92 dep.erase(std::remove_if(dep.begin(), dep.end(),
93 static_cast<int (*)(int)>(&std::isspace)), dep.end());
95 for (const auto &dependency : str_split(dep, ',')) {
96 spec.optdepends.insert(dependency);
100 // Fallback to depends.txt
101 if (!mod_conf_has_depends) {
102 std::vector<std::string> dependencies;
104 std::ifstream is((spec.path + DIR_DELIM + "depends.txt").c_str());
107 std::getline(is, dep);
108 dependencies.push_back(dep);
111 for (auto &dependency : dependencies) {
112 std::unordered_set<char> symbols;
113 if (parseDependsString(dependency, symbols)) {
114 if (symbols.count('?') != 0) {
115 spec.optdepends.insert(dependency);
117 spec.depends.insert(dependency);
123 if (info.exists("description")) {
124 spec.desc = info.get("description");
126 std::ifstream is((spec.path + DIR_DELIM + "description.txt")
128 spec.desc = std::string((std::istreambuf_iterator<char>(is)),
129 std::istreambuf_iterator<char>());
134 std::map<std::string, ModSpec> getModsInPath(
135 const std::string &path, bool part_of_modpack)
137 // NOTE: this function works in mutual recursion with parseModContents
139 std::map<std::string, ModSpec> result;
140 std::vector<fs::DirListNode> dirlist = fs::GetDirListing(path);
143 for (const fs::DirListNode &dln : dirlist) {
147 const std::string &modname = dln.name;
148 // Ignore all directories beginning with a ".", especially
149 // VCS directories like ".git" or ".svn"
150 if (modname[0] == '.')
154 modpath.append(path).append(DIR_DELIM).append(modname);
156 ModSpec spec(modname, modpath, part_of_modpack);
157 parseModContents(spec);
158 result.insert(std::make_pair(modname, spec));
163 std::vector<ModSpec> flattenMods(std::map<std::string, ModSpec> mods)
165 std::vector<ModSpec> result;
166 for (const auto &it : mods) {
167 const ModSpec &mod = it.second;
168 if (mod.is_modpack) {
169 std::vector<ModSpec> content = flattenMods(mod.modpack_content);
170 result.reserve(result.size() + content.size());
171 result.insert(result.end(), content.begin(), content.end());
173 } else // not a modpack
175 result.push_back(mod);
181 ModConfiguration::ModConfiguration(const std::string &worldpath)
185 void ModConfiguration::printUnsatisfiedModsError() const
187 for (const ModSpec &mod : m_unsatisfied_mods) {
188 errorstream << "mod \"" << mod.name
189 << "\" has unsatisfied dependencies: ";
190 for (const std::string &unsatisfied_depend : mod.unsatisfied_depends)
191 errorstream << " \"" << unsatisfied_depend << "\"";
192 errorstream << std::endl;
196 void ModConfiguration::addModsInPath(const std::string &path)
198 addMods(flattenMods(getModsInPath(path)));
201 void ModConfiguration::addMods(const std::vector<ModSpec> &new_mods)
203 // Maintain a map of all existing m_unsatisfied_mods.
204 // Keys are mod names and values are indices into m_unsatisfied_mods.
205 std::map<std::string, u32> existing_mods;
206 for (u32 i = 0; i < m_unsatisfied_mods.size(); ++i) {
207 existing_mods[m_unsatisfied_mods[i].name] = i;
211 for (int want_from_modpack = 1; want_from_modpack >= 0; --want_from_modpack) {
213 // Add all the mods that come from modpacks
215 // Add all the mods that didn't come from modpacks
217 std::set<std::string> seen_this_iteration;
219 for (const ModSpec &mod : new_mods) {
220 if (mod.part_of_modpack != (bool)want_from_modpack)
223 if (existing_mods.count(mod.name) == 0) {
224 // GOOD CASE: completely new mod.
225 m_unsatisfied_mods.push_back(mod);
226 existing_mods[mod.name] = m_unsatisfied_mods.size() - 1;
227 } else if (seen_this_iteration.count(mod.name) == 0) {
228 // BAD CASE: name conflict in different levels.
229 u32 oldindex = existing_mods[mod.name];
230 const ModSpec &oldmod = m_unsatisfied_mods[oldindex];
231 warningstream << "Mod name conflict detected: \""
232 << mod.name << "\"" << std::endl
233 << "Will not load: " << oldmod.path
235 << "Overridden by: " << mod.path
237 m_unsatisfied_mods[oldindex] = mod;
239 // If there was a "VERY BAD CASE" name conflict
240 // in an earlier level, ignore it.
241 m_name_conflicts.erase(mod.name);
243 // VERY BAD CASE: name conflict in the same level.
244 u32 oldindex = existing_mods[mod.name];
245 const ModSpec &oldmod = m_unsatisfied_mods[oldindex];
246 warningstream << "Mod name conflict detected: \""
247 << mod.name << "\"" << std::endl
248 << "Will not load: " << oldmod.path
250 << "Will not load: " << mod.path
252 m_unsatisfied_mods[oldindex] = mod;
253 m_name_conflicts.insert(mod.name);
256 seen_this_iteration.insert(mod.name);
261 void ModConfiguration::addModsFromConfig(
262 const std::string &settings_path, const std::set<std::string> &mods)
265 std::set<std::string> load_mod_names;
267 conf.readConfigFile(settings_path.c_str());
268 std::vector<std::string> names = conf.getNames();
269 for (const std::string &name : names) {
270 if (name.compare(0, 9, "load_mod_") == 0 && conf.getBool(name))
271 load_mod_names.insert(name.substr(9));
274 std::vector<ModSpec> addon_mods;
275 for (const std::string &i : mods) {
276 std::vector<ModSpec> addon_mods_in_path = flattenMods(getModsInPath(i));
277 for (std::vector<ModSpec>::const_iterator it = addon_mods_in_path.begin();
278 it != addon_mods_in_path.end(); ++it) {
279 const ModSpec &mod = *it;
280 if (load_mod_names.count(mod.name) != 0)
281 addon_mods.push_back(mod);
283 conf.setBool("load_mod_" + mod.name, false);
286 conf.updateConfigFile(settings_path.c_str());
289 checkConflictsAndDeps();
291 // complain about mods declared to be loaded, but not found
292 for (const ModSpec &addon_mod : addon_mods)
293 load_mod_names.erase(addon_mod.name);
295 std::vector<ModSpec> unsatisfiedMods = getUnsatisfiedMods();
297 for (const ModSpec &unsatisfiedMod : unsatisfiedMods)
298 load_mod_names.erase(unsatisfiedMod.name);
300 if (!load_mod_names.empty()) {
301 errorstream << "The following mods could not be found:";
302 for (const std::string &mod : load_mod_names)
303 errorstream << " \"" << mod << "\"";
304 errorstream << std::endl;
308 void ModConfiguration::checkConflictsAndDeps()
310 // report on name conflicts
311 if (!m_name_conflicts.empty()) {
312 std::string s = "Unresolved name conflicts for mods ";
313 for (std::unordered_set<std::string>::const_iterator it =
314 m_name_conflicts.begin();
315 it != m_name_conflicts.end(); ++it) {
316 if (it != m_name_conflicts.begin())
318 s += std::string("\"") + (*it) + "\"";
324 // get the mods in order
325 resolveDependencies();
328 void ModConfiguration::resolveDependencies()
330 // Step 1: Compile a list of the mod names we're working with
331 std::set<std::string> modnames;
332 for (const ModSpec &mod : m_unsatisfied_mods) {
333 modnames.insert(mod.name);
336 // Step 2: get dependencies (including optional dependencies)
337 // of each mod, split mods into satisfied and unsatisfied
338 std::list<ModSpec> satisfied;
339 std::list<ModSpec> unsatisfied;
340 for (ModSpec mod : m_unsatisfied_mods) {
341 mod.unsatisfied_depends = mod.depends;
342 // check which optional dependencies actually exist
343 for (const std::string &optdep : mod.optdepends) {
344 if (modnames.count(optdep) != 0)
345 mod.unsatisfied_depends.insert(optdep);
347 // if a mod has no depends it is initially satisfied
348 if (mod.unsatisfied_depends.empty())
349 satisfied.push_back(mod);
351 unsatisfied.push_back(mod);
354 // Step 3: mods without unmet dependencies can be appended to
356 while (!satisfied.empty()) {
357 ModSpec mod = satisfied.back();
358 m_sorted_mods.push_back(mod);
359 satisfied.pop_back();
360 for (auto it = unsatisfied.begin(); it != unsatisfied.end();) {
362 mod2.unsatisfied_depends.erase(mod.name);
363 if (mod2.unsatisfied_depends.empty()) {
364 satisfied.push_back(mod2);
365 it = unsatisfied.erase(it);
372 // Step 4: write back list of unsatisfied mods
373 m_unsatisfied_mods.assign(unsatisfied.begin(), unsatisfied.end());
377 ClientModConfiguration::ClientModConfiguration(const std::string &path) :
378 ModConfiguration(path)
380 std::set<std::string> paths;
381 std::string path_user = porting::path_user + DIR_DELIM + "clientmods";
383 paths.insert(path_user);
385 std::string settings_path = path_user + DIR_DELIM + "mods.conf";
386 addModsFromConfig(settings_path, paths);
390 ModMetadata::ModMetadata(const std::string &mod_name) : m_mod_name(mod_name)
394 void ModMetadata::clear()
400 bool ModMetadata::save(const std::string &root_path)
403 for (StringMap::const_iterator it = m_stringvars.begin();
404 it != m_stringvars.end(); ++it) {
405 json[it->first] = it->second;
408 if (!fs::PathExists(root_path)) {
409 if (!fs::CreateAllDirs(root_path)) {
410 errorstream << "ModMetadata[" << m_mod_name
411 << "]: Unable to save. '" << root_path
412 << "' tree cannot be created." << std::endl;
415 } else if (!fs::IsDir(root_path)) {
416 errorstream << "ModMetadata[" << m_mod_name << "]: Unable to save. '"
417 << root_path << "' is not a directory." << std::endl;
421 bool w_ok = fs::safeWriteToFile(
422 root_path + DIR_DELIM + m_mod_name, fastWriteJson(json));
427 errorstream << "ModMetadata[" << m_mod_name << "]: failed write file."
433 bool ModMetadata::load(const std::string &root_path)
435 m_stringvars.clear();
437 std::ifstream is((root_path + DIR_DELIM + m_mod_name).c_str(),
438 std::ios_base::binary);
444 Json::CharReaderBuilder builder;
445 builder.settings_["collectComments"] = false;
448 if (!Json::parseFromStream(builder, is, &root, &errs)) {
449 errorstream << "ModMetadata[" << m_mod_name
450 << "]: failed read data "
451 "(Json decoding failure). Message: "
452 << errs << std::endl;
456 const Json::Value::Members attr_list = root.getMemberNames();
457 for (const auto &it : attr_list) {
458 Json::Value attr_value = root[it];
459 m_stringvars[it] = attr_value.asString();
465 bool ModMetadata::setString(const std::string &name, const std::string &var)
467 m_modified = Metadata::setString(name, var);