]> git.lizzy.rs Git - minetest.git/blob - src/content/mods.cpp
Add updating to online content browser
[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         if (info.exists("release"))
60                 spec.release = info.getS32("release");
61
62         spec.depends.clear();
63         spec.optdepends.clear();
64         spec.is_modpack = false;
65         spec.modpack_content.clear();
66
67         // Handle modpacks (defined by containing modpack.txt)
68         std::ifstream modpack_is((spec.path + DIR_DELIM + "modpack.txt").c_str());
69         if (modpack_is.good()) {    // a modpack, recursively get the mods in it
70                 modpack_is.close(); // We don't actually need the file
71                 spec.is_modpack = true;
72                 spec.modpack_content = getModsInPath(spec.path, true);
73                 // modpacks have no dependencies; they are defined and
74                 // tracked separately for each mod in the modpack
75
76         } else {
77                 // Attempt to load dependencies from mod.conf
78                 bool mod_conf_has_depends = false;
79                 if (info.exists("depends")) {
80                         mod_conf_has_depends = true;
81                         std::string dep = info.get("depends");
82                         // clang-format off
83                         dep.erase(std::remove_if(dep.begin(), dep.end(),
84                                         static_cast<int (*)(int)>(&std::isspace)), dep.end());
85                         // clang-format on
86                         for (const auto &dependency : str_split(dep, ',')) {
87                                 spec.depends.insert(dependency);
88                         }
89                 }
90
91                 if (info.exists("optional_depends")) {
92                         mod_conf_has_depends = true;
93                         std::string dep = info.get("optional_depends");
94                         // clang-format off
95                         dep.erase(std::remove_if(dep.begin(), dep.end(),
96                                         static_cast<int (*)(int)>(&std::isspace)), dep.end());
97                         // clang-format on
98                         for (const auto &dependency : str_split(dep, ',')) {
99                                 spec.optdepends.insert(dependency);
100                         }
101                 }
102
103                 // Fallback to depends.txt
104                 if (!mod_conf_has_depends) {
105                         std::vector<std::string> dependencies;
106
107                         std::ifstream is((spec.path + DIR_DELIM + "depends.txt").c_str());
108                         while (is.good()) {
109                                 std::string dep;
110                                 std::getline(is, dep);
111                                 dependencies.push_back(dep);
112                         }
113
114                         for (auto &dependency : dependencies) {
115                                 std::unordered_set<char> symbols;
116                                 if (parseDependsString(dependency, symbols)) {
117                                         if (symbols.count('?') != 0) {
118                                                 spec.optdepends.insert(dependency);
119                                         } else {
120                                                 spec.depends.insert(dependency);
121                                         }
122                                 }
123                         }
124                 }
125
126                 if (info.exists("description")) {
127                         spec.desc = info.get("description");
128                 } else {
129                         std::ifstream is((spec.path + DIR_DELIM + "description.txt")
130                                                          .c_str());
131                         spec.desc = std::string((std::istreambuf_iterator<char>(is)),
132                                         std::istreambuf_iterator<char>());
133                 }
134         }
135 }
136
137 std::map<std::string, ModSpec> getModsInPath(
138                 const std::string &path, bool part_of_modpack)
139 {
140         // NOTE: this function works in mutual recursion with parseModContents
141
142         std::map<std::string, ModSpec> result;
143         std::vector<fs::DirListNode> dirlist = fs::GetDirListing(path);
144         std::string modpath;
145
146         for (const fs::DirListNode &dln : dirlist) {
147                 if (!dln.dir)
148                         continue;
149
150                 const std::string &modname = dln.name;
151                 // Ignore all directories beginning with a ".", especially
152                 // VCS directories like ".git" or ".svn"
153                 if (modname[0] == '.')
154                         continue;
155
156                 modpath.clear();
157                 modpath.append(path).append(DIR_DELIM).append(modname);
158
159                 ModSpec spec(modname, modpath, part_of_modpack);
160                 parseModContents(spec);
161                 result.insert(std::make_pair(modname, spec));
162         }
163         return result;
164 }
165
166 std::vector<ModSpec> flattenMods(std::map<std::string, ModSpec> mods)
167 {
168         std::vector<ModSpec> result;
169         for (const auto &it : mods) {
170                 const ModSpec &mod = it.second;
171                 if (mod.is_modpack) {
172                         std::vector<ModSpec> content = flattenMods(mod.modpack_content);
173                         result.reserve(result.size() + content.size());
174                         result.insert(result.end(), content.begin(), content.end());
175
176                 } else // not a modpack
177                 {
178                         result.push_back(mod);
179                 }
180         }
181         return result;
182 }
183
184 ModConfiguration::ModConfiguration(const std::string &worldpath)
185 {
186 }
187
188 void ModConfiguration::printUnsatisfiedModsError() const
189 {
190         for (const ModSpec &mod : m_unsatisfied_mods) {
191                 errorstream << "mod \"" << mod.name
192                             << "\" has unsatisfied dependencies: ";
193                 for (const std::string &unsatisfied_depend : mod.unsatisfied_depends)
194                         errorstream << " \"" << unsatisfied_depend << "\"";
195                 errorstream << std::endl;
196         }
197 }
198
199 void ModConfiguration::addModsInPath(const std::string &path)
200 {
201         addMods(flattenMods(getModsInPath(path)));
202 }
203
204 void ModConfiguration::addMods(const std::vector<ModSpec> &new_mods)
205 {
206         // Maintain a map of all existing m_unsatisfied_mods.
207         // Keys are mod names and values are indices into m_unsatisfied_mods.
208         std::map<std::string, u32> existing_mods;
209         for (u32 i = 0; i < m_unsatisfied_mods.size(); ++i) {
210                 existing_mods[m_unsatisfied_mods[i].name] = i;
211         }
212
213         // Add new mods
214         for (int want_from_modpack = 1; want_from_modpack >= 0; --want_from_modpack) {
215                 // First iteration:
216                 // Add all the mods that come from modpacks
217                 // Second iteration:
218                 // Add all the mods that didn't come from modpacks
219
220                 std::set<std::string> seen_this_iteration;
221
222                 for (const ModSpec &mod : new_mods) {
223                         if (mod.part_of_modpack != (bool)want_from_modpack)
224                                 continue;
225
226                         if (existing_mods.count(mod.name) == 0) {
227                                 // GOOD CASE: completely new mod.
228                                 m_unsatisfied_mods.push_back(mod);
229                                 existing_mods[mod.name] = m_unsatisfied_mods.size() - 1;
230                         } else if (seen_this_iteration.count(mod.name) == 0) {
231                                 // BAD CASE: name conflict in different levels.
232                                 u32 oldindex = existing_mods[mod.name];
233                                 const ModSpec &oldmod = m_unsatisfied_mods[oldindex];
234                                 warningstream << "Mod name conflict detected: \""
235                                               << mod.name << "\"" << std::endl
236                                               << "Will not load: " << oldmod.path
237                                               << std::endl
238                                               << "Overridden by: " << mod.path
239                                               << std::endl;
240                                 m_unsatisfied_mods[oldindex] = mod;
241
242                                 // If there was a "VERY BAD CASE" name conflict
243                                 // in an earlier level, ignore it.
244                                 m_name_conflicts.erase(mod.name);
245                         } else {
246                                 // VERY BAD CASE: name conflict in the same level.
247                                 u32 oldindex = existing_mods[mod.name];
248                                 const ModSpec &oldmod = m_unsatisfied_mods[oldindex];
249                                 warningstream << "Mod name conflict detected: \""
250                                               << mod.name << "\"" << std::endl
251                                               << "Will not load: " << oldmod.path
252                                               << std::endl
253                                               << "Will not load: " << mod.path
254                                               << std::endl;
255                                 m_unsatisfied_mods[oldindex] = mod;
256                                 m_name_conflicts.insert(mod.name);
257                         }
258
259                         seen_this_iteration.insert(mod.name);
260                 }
261         }
262 }
263
264 void ModConfiguration::addModsFromConfig(
265                 const std::string &settings_path, const std::set<std::string> &mods)
266 {
267         Settings conf;
268         std::set<std::string> load_mod_names;
269
270         conf.readConfigFile(settings_path.c_str());
271         std::vector<std::string> names = conf.getNames();
272         for (const std::string &name : names) {
273                 if (name.compare(0, 9, "load_mod_") == 0 && conf.getBool(name))
274                         load_mod_names.insert(name.substr(9));
275         }
276
277         std::vector<ModSpec> addon_mods;
278         for (const std::string &i : mods) {
279                 std::vector<ModSpec> addon_mods_in_path = flattenMods(getModsInPath(i));
280                 for (std::vector<ModSpec>::const_iterator it = addon_mods_in_path.begin();
281                                 it != addon_mods_in_path.end(); ++it) {
282                         const ModSpec &mod = *it;
283                         if (load_mod_names.count(mod.name) != 0)
284                                 addon_mods.push_back(mod);
285                         else
286                                 conf.setBool("load_mod_" + mod.name, false);
287                 }
288         }
289         conf.updateConfigFile(settings_path.c_str());
290
291         addMods(addon_mods);
292         checkConflictsAndDeps();
293
294         // complain about mods declared to be loaded, but not found
295         for (const ModSpec &addon_mod : addon_mods)
296                 load_mod_names.erase(addon_mod.name);
297
298         std::vector<ModSpec> unsatisfiedMods = getUnsatisfiedMods();
299
300         for (const ModSpec &unsatisfiedMod : unsatisfiedMods)
301                 load_mod_names.erase(unsatisfiedMod.name);
302
303         if (!load_mod_names.empty()) {
304                 errorstream << "The following mods could not be found:";
305                 for (const std::string &mod : load_mod_names)
306                         errorstream << " \"" << mod << "\"";
307                 errorstream << std::endl;
308         }
309 }
310
311 void ModConfiguration::checkConflictsAndDeps()
312 {
313         // report on name conflicts
314         if (!m_name_conflicts.empty()) {
315                 std::string s = "Unresolved name conflicts for mods ";
316                 for (std::unordered_set<std::string>::const_iterator it =
317                                                 m_name_conflicts.begin();
318                                 it != m_name_conflicts.end(); ++it) {
319                         if (it != m_name_conflicts.begin())
320                                 s += ", ";
321                         s += std::string("\"") + (*it) + "\"";
322                 }
323                 s += ".";
324                 throw ModError(s);
325         }
326
327         // get the mods in order
328         resolveDependencies();
329 }
330
331 void ModConfiguration::resolveDependencies()
332 {
333         // Step 1: Compile a list of the mod names we're working with
334         std::set<std::string> modnames;
335         for (const ModSpec &mod : m_unsatisfied_mods) {
336                 modnames.insert(mod.name);
337         }
338
339         // Step 2: get dependencies (including optional dependencies)
340         // of each mod, split mods into satisfied and unsatisfied
341         std::list<ModSpec> satisfied;
342         std::list<ModSpec> unsatisfied;
343         for (ModSpec mod : m_unsatisfied_mods) {
344                 mod.unsatisfied_depends = mod.depends;
345                 // check which optional dependencies actually exist
346                 for (const std::string &optdep : mod.optdepends) {
347                         if (modnames.count(optdep) != 0)
348                                 mod.unsatisfied_depends.insert(optdep);
349                 }
350                 // if a mod has no depends it is initially satisfied
351                 if (mod.unsatisfied_depends.empty())
352                         satisfied.push_back(mod);
353                 else
354                         unsatisfied.push_back(mod);
355         }
356
357         // Step 3: mods without unmet dependencies can be appended to
358         // the sorted list.
359         while (!satisfied.empty()) {
360                 ModSpec mod = satisfied.back();
361                 m_sorted_mods.push_back(mod);
362                 satisfied.pop_back();
363                 for (auto it = unsatisfied.begin(); it != unsatisfied.end();) {
364                         ModSpec &mod2 = *it;
365                         mod2.unsatisfied_depends.erase(mod.name);
366                         if (mod2.unsatisfied_depends.empty()) {
367                                 satisfied.push_back(mod2);
368                                 it = unsatisfied.erase(it);
369                         } else {
370                                 ++it;
371                         }
372                 }
373         }
374
375         // Step 4: write back list of unsatisfied mods
376         m_unsatisfied_mods.assign(unsatisfied.begin(), unsatisfied.end());
377 }
378
379 #ifndef SERVER
380 ClientModConfiguration::ClientModConfiguration(const std::string &path) :
381                 ModConfiguration(path)
382 {
383         std::set<std::string> paths;
384         std::string path_user = porting::path_user + DIR_DELIM + "clientmods";
385         paths.insert(path);
386         paths.insert(path_user);
387
388         std::string settings_path = path_user + DIR_DELIM + "mods.conf";
389         addModsFromConfig(settings_path, paths);
390 }
391 #endif
392
393 ModMetadata::ModMetadata(const std::string &mod_name) : m_mod_name(mod_name)
394 {
395 }
396
397 void ModMetadata::clear()
398 {
399         Metadata::clear();
400         m_modified = true;
401 }
402
403 bool ModMetadata::save(const std::string &root_path)
404 {
405         Json::Value json;
406         for (StringMap::const_iterator it = m_stringvars.begin();
407                         it != m_stringvars.end(); ++it) {
408                 json[it->first] = it->second;
409         }
410
411         if (!fs::PathExists(root_path)) {
412                 if (!fs::CreateAllDirs(root_path)) {
413                         errorstream << "ModMetadata[" << m_mod_name
414                                     << "]: Unable to save. '" << root_path
415                                     << "' tree cannot be created." << std::endl;
416                         return false;
417                 }
418         } else if (!fs::IsDir(root_path)) {
419                 errorstream << "ModMetadata[" << m_mod_name << "]: Unable to save. '"
420                             << root_path << "' is not a directory." << std::endl;
421                 return false;
422         }
423
424         bool w_ok = fs::safeWriteToFile(
425                         root_path + DIR_DELIM + m_mod_name, fastWriteJson(json));
426
427         if (w_ok) {
428                 m_modified = false;
429         } else {
430                 errorstream << "ModMetadata[" << m_mod_name << "]: failed write file."
431                             << std::endl;
432         }
433         return w_ok;
434 }
435
436 bool ModMetadata::load(const std::string &root_path)
437 {
438         m_stringvars.clear();
439
440         std::ifstream is((root_path + DIR_DELIM + m_mod_name).c_str(),
441                         std::ios_base::binary);
442         if (!is.good()) {
443                 return false;
444         }
445
446         Json::Value root;
447         Json::CharReaderBuilder builder;
448         builder.settings_["collectComments"] = false;
449         std::string errs;
450
451         if (!Json::parseFromStream(builder, is, &root, &errs)) {
452                 errorstream << "ModMetadata[" << m_mod_name
453                             << "]: failed read data "
454                                "(Json decoding failure). Message: "
455                             << errs << std::endl;
456                 return false;
457         }
458
459         const Json::Value::Members attr_list = root.getMemberNames();
460         for (const auto &it : attr_list) {
461                 Json::Value attr_value = root[it];
462                 m_stringvars[it] = attr_value.asString();
463         }
464
465         return true;
466 }
467
468 bool ModMetadata::setString(const std::string &name, const std::string &var)
469 {
470         m_modified = Metadata::setString(name, var);
471         return m_modified;
472 }