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