]> git.lizzy.rs Git - dragonfireclient.git/blob - src/content/mods.cpp
455506967d6d1f22a0dfb5d0f3b7b351758a06d8
[dragonfireclient.git] / src / content / mods.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
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.
9
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.
14
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.
18 */
19
20 #include <cctype>
21 #include <fstream>
22 #include <json/json.h>
23 #include <algorithm>
24 #include "content/mods.h"
25 #include "database/database.h"
26 #include "filesys.h"
27 #include "log.h"
28 #include "content/subgames.h"
29 #include "settings.h"
30 #include "porting.h"
31 #include "convert_json.h"
32 #include "script/common/c_internal.h"
33
34 void ModSpec::checkAndLog() const
35 {
36         if (!string_allowed(name, MODNAME_ALLOWED_CHARS)) {
37                 throw ModError("Error loading mod \"" + name +
38                         "\": Mod name does not follow naming conventions: "
39                                 "Only characters [a-z0-9_] are allowed.");
40         }
41
42         // Log deprecation messages
43         auto handling_mode = get_deprecated_handling_mode();
44         if (!deprecation_msgs.empty() && handling_mode != DeprecatedHandlingMode::Ignore) {
45                 std::ostringstream os;
46                 os << "Mod " << name << " at " << path << ":" << std::endl;
47                 for (auto msg : deprecation_msgs)
48                         os << "\t" << msg << std::endl;
49
50                 if (handling_mode == DeprecatedHandlingMode::Error)
51                         throw ModError(os.str());
52                 else
53                         warningstream << os.str();
54         }
55 }
56
57 bool parseDependsString(std::string &dep, std::unordered_set<char> &symbols)
58 {
59         dep = trim(dep);
60         symbols.clear();
61         size_t pos = dep.size();
62         while (pos > 0 &&
63                         !string_allowed(dep.substr(pos - 1, 1), MODNAME_ALLOWED_CHARS)) {
64                 // last character is a symbol, not part of the modname
65                 symbols.insert(dep[pos - 1]);
66                 --pos;
67         }
68         dep = trim(dep.substr(0, pos));
69         return !dep.empty();
70 }
71
72 void parseModContents(ModSpec &spec)
73 {
74         // NOTE: this function works in mutual recursion with getModsInPath
75
76         spec.depends.clear();
77         spec.optdepends.clear();
78         spec.is_modpack = false;
79         spec.modpack_content.clear();
80
81         // Handle modpacks (defined by containing modpack.txt)
82         std::ifstream modpack_is((spec.path + DIR_DELIM + "modpack.txt").c_str());
83         std::ifstream modpack2_is((spec.path + DIR_DELIM + "modpack.conf").c_str());
84         if (modpack_is.good() || modpack2_is.good()) {
85                 if (modpack_is.good())
86                         modpack_is.close();
87
88                 if (modpack2_is.good())
89                         modpack2_is.close();
90
91                 spec.is_modpack = true;
92                 spec.modpack_content = getModsInPath(spec.path, true);
93
94         } else {
95                 Settings info;
96                 info.readConfigFile((spec.path + DIR_DELIM + "mod.conf").c_str());
97
98                 if (info.exists("name"))
99                         spec.name = info.get("name");
100                 else
101                         spec.deprecation_msgs.push_back("Mods not having a mod.conf file with the name is deprecated.");
102
103                 if (info.exists("author"))
104                         spec.author = info.get("author");
105
106                 if (info.exists("release"))
107                         spec.release = info.getS32("release");
108
109                 // Attempt to load dependencies from mod.conf
110                 bool mod_conf_has_depends = false;
111                 if (info.exists("depends")) {
112                         mod_conf_has_depends = true;
113                         std::string dep = info.get("depends");
114                         // clang-format off
115                         dep.erase(std::remove_if(dep.begin(), dep.end(),
116                                         static_cast<int (*)(int)>(&std::isspace)), dep.end());
117                         // clang-format on
118                         for (const auto &dependency : str_split(dep, ',')) {
119                                 spec.depends.insert(dependency);
120                         }
121                 }
122
123                 if (info.exists("optional_depends")) {
124                         mod_conf_has_depends = true;
125                         std::string dep = info.get("optional_depends");
126                         // clang-format off
127                         dep.erase(std::remove_if(dep.begin(), dep.end(),
128                                         static_cast<int (*)(int)>(&std::isspace)), dep.end());
129                         // clang-format on
130                         for (const auto &dependency : str_split(dep, ',')) {
131                                 spec.optdepends.insert(dependency);
132                         }
133                 }
134
135                 // Fallback to depends.txt
136                 if (!mod_conf_has_depends) {
137                         std::vector<std::string> dependencies;
138
139                         std::ifstream is((spec.path + DIR_DELIM + "depends.txt").c_str());
140
141                         if (is.good())
142                                 spec.deprecation_msgs.push_back("depends.txt is deprecated, please use mod.conf instead.");
143
144                         while (is.good()) {
145                                 std::string dep;
146                                 std::getline(is, dep);
147                                 dependencies.push_back(dep);
148                         }
149
150                         for (auto &dependency : dependencies) {
151                                 std::unordered_set<char> symbols;
152                                 if (parseDependsString(dependency, symbols)) {
153                                         if (symbols.count('?') != 0) {
154                                                 spec.optdepends.insert(dependency);
155                                         } else {
156                                                 spec.depends.insert(dependency);
157                                         }
158                                 }
159                         }
160                 }
161
162                 if (info.exists("description"))
163                         spec.desc = info.get("description");
164                 else if (fs::ReadFile(spec.path + DIR_DELIM + "description.txt", spec.desc))
165                         spec.deprecation_msgs.push_back("description.txt is deprecated, please use mod.conf instead.");
166         }
167 }
168
169 std::map<std::string, ModSpec> getModsInPath(
170                 const std::string &path, bool part_of_modpack)
171 {
172         // NOTE: this function works in mutual recursion with parseModContents
173
174         std::map<std::string, ModSpec> result;
175         std::vector<fs::DirListNode> dirlist = fs::GetDirListing(path);
176         std::string modpath;
177
178         for (const fs::DirListNode &dln : dirlist) {
179                 if (!dln.dir)
180                         continue;
181
182                 const std::string &modname = dln.name;
183                 // Ignore all directories beginning with a ".", especially
184                 // VCS directories like ".git" or ".svn"
185                 if (modname[0] == '.')
186                         continue;
187
188                 modpath.clear();
189                 modpath.append(path).append(DIR_DELIM).append(modname);
190
191                 ModSpec spec(modname, modpath, part_of_modpack);
192                 parseModContents(spec);
193                 result.insert(std::make_pair(modname, spec));
194         }
195         return result;
196 }
197
198 std::vector<ModSpec> flattenMods(const std::map<std::string, ModSpec> &mods)
199 {
200         std::vector<ModSpec> result;
201         for (const auto &it : mods) {
202                 const ModSpec &mod = it.second;
203                 if (mod.is_modpack) {
204                         std::vector<ModSpec> content = flattenMods(mod.modpack_content);
205                         result.reserve(result.size() + content.size());
206                         result.insert(result.end(), content.begin(), content.end());
207
208                 } else // not a modpack
209                 {
210                         result.push_back(mod);
211                 }
212         }
213         return result;
214 }
215
216 ModConfiguration::ModConfiguration(const std::string &worldpath)
217 {
218 }
219
220 void ModConfiguration::printUnsatisfiedModsError() const
221 {
222         for (const ModSpec &mod : m_unsatisfied_mods) {
223                 errorstream << "mod \"" << mod.name
224                             << "\" has unsatisfied dependencies: ";
225                 for (const std::string &unsatisfied_depend : mod.unsatisfied_depends)
226                         errorstream << " \"" << unsatisfied_depend << "\"";
227                 errorstream << std::endl;
228         }
229 }
230
231 void ModConfiguration::addModsInPath(const std::string &path)
232 {
233         addMods(flattenMods(getModsInPath(path)));
234 }
235
236 void ModConfiguration::addMods(const std::vector<ModSpec> &new_mods)
237 {
238         // Maintain a map of all existing m_unsatisfied_mods.
239         // Keys are mod names and values are indices into m_unsatisfied_mods.
240         std::map<std::string, u32> existing_mods;
241         for (u32 i = 0; i < m_unsatisfied_mods.size(); ++i) {
242                 existing_mods[m_unsatisfied_mods[i].name] = i;
243         }
244
245         // Add new mods
246         for (int want_from_modpack = 1; want_from_modpack >= 0; --want_from_modpack) {
247                 // First iteration:
248                 // Add all the mods that come from modpacks
249                 // Second iteration:
250                 // Add all the mods that didn't come from modpacks
251
252                 std::set<std::string> seen_this_iteration;
253
254                 for (const ModSpec &mod : new_mods) {
255                         if (mod.part_of_modpack != (bool)want_from_modpack)
256                                 continue;
257
258                         if (existing_mods.count(mod.name) == 0) {
259                                 // GOOD CASE: completely new mod.
260                                 m_unsatisfied_mods.push_back(mod);
261                                 existing_mods[mod.name] = m_unsatisfied_mods.size() - 1;
262                         } else if (seen_this_iteration.count(mod.name) == 0) {
263                                 // BAD CASE: name conflict in different levels.
264                                 u32 oldindex = existing_mods[mod.name];
265                                 const ModSpec &oldmod = m_unsatisfied_mods[oldindex];
266                                 warningstream << "Mod name conflict detected: \""
267                                               << mod.name << "\"" << std::endl
268                                               << "Will not load: " << oldmod.path
269                                               << std::endl
270                                               << "Overridden by: " << mod.path
271                                               << std::endl;
272                                 m_unsatisfied_mods[oldindex] = mod;
273
274                                 // If there was a "VERY BAD CASE" name conflict
275                                 // in an earlier level, ignore it.
276                                 m_name_conflicts.erase(mod.name);
277                         } else {
278                                 // VERY BAD CASE: name conflict in the same level.
279                                 u32 oldindex = existing_mods[mod.name];
280                                 const ModSpec &oldmod = m_unsatisfied_mods[oldindex];
281                                 warningstream << "Mod name conflict detected: \""
282                                               << mod.name << "\"" << std::endl
283                                               << "Will not load: " << oldmod.path
284                                               << std::endl
285                                               << "Will not load: " << mod.path
286                                               << std::endl;
287                                 m_unsatisfied_mods[oldindex] = mod;
288                                 m_name_conflicts.insert(mod.name);
289                         }
290
291                         seen_this_iteration.insert(mod.name);
292                 }
293         }
294 }
295
296 void ModConfiguration::addModsFromConfig(
297                 const std::string &settings_path, const std::set<std::string> &mods)
298 {
299         Settings conf;
300         std::set<std::string> load_mod_names;
301
302         conf.readConfigFile(settings_path.c_str());
303         std::vector<std::string> names = conf.getNames();
304         for (const std::string &name : names) {
305                 if (name.compare(0, 9, "load_mod_") == 0 && conf.get(name) != "false" &&
306                                 conf.get(name) != "nil")
307                         load_mod_names.insert(name.substr(9));
308         }
309
310         std::vector<ModSpec> addon_mods;
311         for (const std::string &i : mods) {
312                 std::vector<ModSpec> addon_mods_in_path = flattenMods(getModsInPath(i));
313                 for (std::vector<ModSpec>::const_iterator it = addon_mods_in_path.begin();
314                                 it != addon_mods_in_path.end(); ++it) {
315                         const ModSpec &mod = *it;
316                         if (load_mod_names.count(mod.name) != 0)
317                                 addon_mods.push_back(mod);
318                         else
319                                 conf.setBool("load_mod_" + mod.name, false);
320                 }
321         }
322         conf.updateConfigFile(settings_path.c_str());
323
324         addMods(addon_mods);
325         checkConflictsAndDeps();
326
327         // complain about mods declared to be loaded, but not found
328         for (const ModSpec &addon_mod : addon_mods)
329                 load_mod_names.erase(addon_mod.name);
330
331         std::vector<ModSpec> unsatisfiedMods = getUnsatisfiedMods();
332
333         for (const ModSpec &unsatisfiedMod : unsatisfiedMods)
334                 load_mod_names.erase(unsatisfiedMod.name);
335
336         if (!load_mod_names.empty()) {
337                 errorstream << "The following mods could not be found:";
338                 for (const std::string &mod : load_mod_names)
339                         errorstream << " \"" << mod << "\"";
340                 errorstream << std::endl;
341         }
342 }
343
344 void ModConfiguration::checkConflictsAndDeps()
345 {
346         // report on name conflicts
347         if (!m_name_conflicts.empty()) {
348                 std::string s = "Unresolved name conflicts for mods ";
349                 for (std::unordered_set<std::string>::const_iterator it =
350                                                 m_name_conflicts.begin();
351                                 it != m_name_conflicts.end(); ++it) {
352                         if (it != m_name_conflicts.begin())
353                                 s += ", ";
354                         s += std::string("\"") + (*it) + "\"";
355                 }
356                 s += ".";
357                 throw ModError(s);
358         }
359
360         // get the mods in order
361         resolveDependencies();
362 }
363
364 void ModConfiguration::resolveDependencies()
365 {
366         // Step 1: Compile a list of the mod names we're working with
367         std::set<std::string> modnames;
368         for (const ModSpec &mod : m_unsatisfied_mods) {
369                 modnames.insert(mod.name);
370         }
371
372         // Step 2: get dependencies (including optional dependencies)
373         // of each mod, split mods into satisfied and unsatisfied
374         std::list<ModSpec> satisfied;
375         std::list<ModSpec> unsatisfied;
376         for (ModSpec mod : m_unsatisfied_mods) {
377                 mod.unsatisfied_depends = mod.depends;
378                 // check which optional dependencies actually exist
379                 for (const std::string &optdep : mod.optdepends) {
380                         if (modnames.count(optdep) != 0)
381                                 mod.unsatisfied_depends.insert(optdep);
382                 }
383                 // if a mod has no depends it is initially satisfied
384                 if (mod.unsatisfied_depends.empty())
385                         satisfied.push_back(mod);
386                 else
387                         unsatisfied.push_back(mod);
388         }
389
390         // Step 3: mods without unmet dependencies can be appended to
391         // the sorted list.
392         while (!satisfied.empty()) {
393                 ModSpec mod = satisfied.back();
394                 m_sorted_mods.push_back(mod);
395                 satisfied.pop_back();
396                 for (auto it = unsatisfied.begin(); it != unsatisfied.end();) {
397                         ModSpec &mod2 = *it;
398                         mod2.unsatisfied_depends.erase(mod.name);
399                         if (mod2.unsatisfied_depends.empty()) {
400                                 satisfied.push_back(mod2);
401                                 it = unsatisfied.erase(it);
402                         } else {
403                                 ++it;
404                         }
405                 }
406         }
407
408         // Step 4: write back list of unsatisfied mods
409         m_unsatisfied_mods.assign(unsatisfied.begin(), unsatisfied.end());
410 }
411
412 #ifndef SERVER
413 ClientModConfiguration::ClientModConfiguration(const std::string &path) :
414                 ModConfiguration(path)
415 {
416         std::set<std::string> paths;
417         std::string path_user = porting::path_user + DIR_DELIM + "clientmods";
418         paths.insert(path);
419         paths.insert(path_user);
420
421         std::string settings_path = path_user + DIR_DELIM + "mods.conf";
422         addModsFromConfig(settings_path, paths);
423 }
424 #endif
425
426 ModMetadata::ModMetadata(const std::string &mod_name, ModMetadataDatabase *database):
427         m_mod_name(mod_name), m_database(database)
428 {
429         m_database->getModEntries(m_mod_name, &m_stringvars);
430 }
431
432 void ModMetadata::clear()
433 {
434         for (const auto &pair : m_stringvars) {
435                 m_database->removeModEntry(m_mod_name, pair.first);
436         }
437         Metadata::clear();
438 }
439
440 bool ModMetadata::setString(const std::string &name, const std::string &var)
441 {
442         if (Metadata::setString(name, var)) {
443                 if (var.empty()) {
444                         m_database->removeModEntry(m_mod_name, name);
445                 } else {
446                         m_database->setModEntry(m_mod_name, name, var);
447                 }
448                 return true;
449         }
450         return false;
451 }