Add online content repository
[oweals/minetest.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 "filesys.h"
26 #include "log.h"
27 #include "content/subgames.h"
28 #include "settings.h"
29 #include "porting.h"
30 #include "convert_json.h"
31
32 bool parseDependsString(std::string &dep, std::unordered_set<char> &symbols)
33 {
34         dep = trim(dep);
35         symbols.clear();
36         size_t pos = dep.size();
37         while (pos > 0 &&
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]);
41                 --pos;
42         }
43         dep = trim(dep.substr(0, pos));
44         return !dep.empty();
45 }
46
47 void parseModContents(ModSpec &spec)
48 {
49         // NOTE: this function works in mutual recursion with getModsInPath
50         Settings info;
51         info.readConfigFile((spec.path + DIR_DELIM + "mod.conf").c_str());
52
53         if (info.exists("name"))
54                 spec.name = info.get("name");
55
56         if (info.exists("author"))
57                 spec.author = info.get("author");
58
59         spec.depends.clear();
60         spec.optdepends.clear();
61         spec.is_modpack = false;
62         spec.modpack_content.clear();
63
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
72
73         } else {
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");
79                         // clang-format off
80                         dep.erase(std::remove_if(dep.begin(), dep.end(),
81                                         static_cast<int (*)(int)>(&std::isspace)), dep.end());
82                         // clang-format on
83                         for (const auto &dependency : str_split(dep, ',')) {
84                                 spec.depends.insert(dependency);
85                         }
86                 }
87
88                 if (info.exists("optional_depends")) {
89                         mod_conf_has_depends = true;
90                         std::string dep = info.get("optional_depends");
91                         // clang-format off
92                         dep.erase(std::remove_if(dep.begin(), dep.end(),
93                                         static_cast<int (*)(int)>(&std::isspace)), dep.end());
94                         // clang-format on
95                         for (const auto &dependency : str_split(dep, ',')) {
96                                 spec.optdepends.insert(dependency);
97                         }
98                 }
99
100                 // Fallback to depends.txt
101                 if (!mod_conf_has_depends) {
102                         std::vector<std::string> dependencies;
103
104                         std::ifstream is((spec.path + DIR_DELIM + "depends.txt").c_str());
105                         while (is.good()) {
106                                 std::string dep;
107                                 std::getline(is, dep);
108                                 dependencies.push_back(dep);
109                         }
110
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);
116                                         } else {
117                                                 spec.depends.insert(dependency);
118                                         }
119                                 }
120                         }
121                 }
122
123                 if (info.exists("description")) {
124                         spec.desc = info.get("description");
125                 } else {
126                         std::ifstream is((spec.path + DIR_DELIM + "description.txt")
127                                                          .c_str());
128                         spec.desc = std::string((std::istreambuf_iterator<char>(is)),
129                                         std::istreambuf_iterator<char>());
130                 }
131         }
132 }
133
134 std::map<std::string, ModSpec> getModsInPath(
135                 const std::string &path, bool part_of_modpack)
136 {
137         // NOTE: this function works in mutual recursion with parseModContents
138
139         std::map<std::string, ModSpec> result;
140         std::vector<fs::DirListNode> dirlist = fs::GetDirListing(path);
141         std::string modpath;
142
143         for (const fs::DirListNode &dln : dirlist) {
144                 if (!dln.dir)
145                         continue;
146
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] == '.')
151                         continue;
152
153                 modpath.clear();
154                 modpath.append(path).append(DIR_DELIM).append(modname);
155
156                 ModSpec spec(modname, modpath, part_of_modpack);
157                 parseModContents(spec);
158                 result.insert(std::make_pair(modname, spec));
159         }
160         return result;
161 }
162
163 std::vector<ModSpec> flattenMods(std::map<std::string, ModSpec> mods)
164 {
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());
172
173                 } else // not a modpack
174                 {
175                         result.push_back(mod);
176                 }
177         }
178         return result;
179 }
180
181 ModConfiguration::ModConfiguration(const std::string &worldpath)
182 {
183 }
184
185 void ModConfiguration::printUnsatisfiedModsError() const
186 {
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;
193         }
194 }
195
196 void ModConfiguration::addModsInPath(const std::string &path)
197 {
198         addMods(flattenMods(getModsInPath(path)));
199 }
200
201 void ModConfiguration::addMods(const std::vector<ModSpec> &new_mods)
202 {
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;
208         }
209
210         // Add new mods
211         for (int want_from_modpack = 1; want_from_modpack >= 0; --want_from_modpack) {
212                 // First iteration:
213                 // Add all the mods that come from modpacks
214                 // Second iteration:
215                 // Add all the mods that didn't come from modpacks
216
217                 std::set<std::string> seen_this_iteration;
218
219                 for (const ModSpec &mod : new_mods) {
220                         if (mod.part_of_modpack != (bool)want_from_modpack)
221                                 continue;
222
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
234                                               << std::endl
235                                               << "Overridden by: " << mod.path
236                                               << std::endl;
237                                 m_unsatisfied_mods[oldindex] = mod;
238
239                                 // If there was a "VERY BAD CASE" name conflict
240                                 // in an earlier level, ignore it.
241                                 m_name_conflicts.erase(mod.name);
242                         } else {
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
249                                               << std::endl
250                                               << "Will not load: " << mod.path
251                                               << std::endl;
252                                 m_unsatisfied_mods[oldindex] = mod;
253                                 m_name_conflicts.insert(mod.name);
254                         }
255
256                         seen_this_iteration.insert(mod.name);
257                 }
258         }
259 }
260
261 void ModConfiguration::addModsFromConfig(
262                 const std::string &settings_path, const std::set<std::string> &mods)
263 {
264         Settings conf;
265         std::set<std::string> load_mod_names;
266
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));
272         }
273
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);
282                         else
283                                 conf.setBool("load_mod_" + mod.name, false);
284                 }
285         }
286         conf.updateConfigFile(settings_path.c_str());
287
288         addMods(addon_mods);
289         checkConflictsAndDeps();
290
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);
294
295         std::vector<ModSpec> unsatisfiedMods = getUnsatisfiedMods();
296
297         for (const ModSpec &unsatisfiedMod : unsatisfiedMods)
298                 load_mod_names.erase(unsatisfiedMod.name);
299
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;
305         }
306 }
307
308 void ModConfiguration::checkConflictsAndDeps()
309 {
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())
317                                 s += ", ";
318                         s += std::string("\"") + (*it) + "\"";
319                 }
320                 s += ".";
321                 throw ModError(s);
322         }
323
324         // get the mods in order
325         resolveDependencies();
326 }
327
328 void ModConfiguration::resolveDependencies()
329 {
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);
334         }
335
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);
346                 }
347                 // if a mod has no depends it is initially satisfied
348                 if (mod.unsatisfied_depends.empty())
349                         satisfied.push_back(mod);
350                 else
351                         unsatisfied.push_back(mod);
352         }
353
354         // Step 3: mods without unmet dependencies can be appended to
355         // the sorted list.
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();) {
361                         ModSpec &mod2 = *it;
362                         mod2.unsatisfied_depends.erase(mod.name);
363                         if (mod2.unsatisfied_depends.empty()) {
364                                 satisfied.push_back(mod2);
365                                 it = unsatisfied.erase(it);
366                         } else {
367                                 ++it;
368                         }
369                 }
370         }
371
372         // Step 4: write back list of unsatisfied mods
373         m_unsatisfied_mods.assign(unsatisfied.begin(), unsatisfied.end());
374 }
375
376 #ifndef SERVER
377 ClientModConfiguration::ClientModConfiguration(const std::string &path) :
378                 ModConfiguration(path)
379 {
380         std::set<std::string> paths;
381         std::string path_user = porting::path_user + DIR_DELIM + "clientmods";
382         paths.insert(path);
383         paths.insert(path_user);
384
385         std::string settings_path = path_user + DIR_DELIM + "mods.conf";
386         addModsFromConfig(settings_path, paths);
387 }
388 #endif
389
390 ModMetadata::ModMetadata(const std::string &mod_name) : m_mod_name(mod_name)
391 {
392 }
393
394 void ModMetadata::clear()
395 {
396         Metadata::clear();
397         m_modified = true;
398 }
399
400 bool ModMetadata::save(const std::string &root_path)
401 {
402         Json::Value json;
403         for (StringMap::const_iterator it = m_stringvars.begin();
404                         it != m_stringvars.end(); ++it) {
405                 json[it->first] = it->second;
406         }
407
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;
413                         return false;
414                 }
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;
418                 return false;
419         }
420
421         bool w_ok = fs::safeWriteToFile(
422                         root_path + DIR_DELIM + m_mod_name, fastWriteJson(json));
423
424         if (w_ok) {
425                 m_modified = false;
426         } else {
427                 errorstream << "ModMetadata[" << m_mod_name << "]: failed write file."
428                             << std::endl;
429         }
430         return w_ok;
431 }
432
433 bool ModMetadata::load(const std::string &root_path)
434 {
435         m_stringvars.clear();
436
437         std::ifstream is((root_path + DIR_DELIM + m_mod_name).c_str(),
438                         std::ios_base::binary);
439         if (!is.good()) {
440                 return false;
441         }
442
443         Json::Value root;
444         Json::CharReaderBuilder builder;
445         builder.settings_["collectComments"] = false;
446         std::string errs;
447
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;
453                 return false;
454         }
455
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();
460         }
461
462         return true;
463 }
464
465 bool ModMetadata::setString(const std::string &name, const std::string &var)
466 {
467         m_modified = Metadata::setString(name, var);
468         return m_modified;
469 }