Debian Codegraph @

Source/Core/DolphinTool/ExtractCommand.cpp

raw symbols SCIP
1 // Copyright 2024 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "DolphinTool/ExtractCommand.h"
5
6 #include <filesystem>
7 #include <iostream>
8
9 #include <fmt/format.h>
10 #include <fmt/ostream.h>
11
12 #include <OptionParser.h>
13
14 #include "Common/FileUtil.h"
15
16 #include "DiscIO/DiscExtractor.h"
17 #include "DiscIO/DiscUtils.h"
18 #include "DiscIO/Filesystem.h"
19 #include "DiscIO/Volume.h"
20
21 namespace DolphinTool
22 {
23 static void ExtractFile(const DiscIO::Volume& disc_volume, const DiscIO::Partition& partition,
24 const std::string& path, const std::string& out)
25 {
26 const DiscIO::FileSystem* filesystem = disc_volume.GetFileSystem(partition);
27 if (!filesystem)
28 return;
29
30 ExportFile(disc_volume, partition, filesystem->FindFileInfo(path).get(), out);
31 }
32
33 static std::unique_ptr<DiscIO::FileInfo> GetFileInfo(const DiscIO::Volume& disc_volume,
34 const DiscIO::Partition& partition,
35 const std::string& path)
36 {
37 const DiscIO::FileSystem* filesystem = disc_volume.GetFileSystem(partition);
38 if (!filesystem)
39 return nullptr;
40
41 return filesystem->FindFileInfo(path);
42 }
43
44 static bool VolumeSupported(const DiscIO::Volume& disc_volume)
45 {
46 switch (disc_volume.GetVolumeType())
47 {
48 case DiscIO::Platform::WiiWAD:
49 fmt::println(std::cerr, "Error: Wii WADs are not supported.");
50 return false;
51 case DiscIO::Platform::ELFOrDOL:
52 fmt::println(std::cerr,
53 "Error: *.elf or *.dol have no filesystem and are therefore not supported.");
54 return false;
55 case DiscIO::Platform::WiiDisc:
56 case DiscIO::Platform::GameCubeDisc:
57 return true;
58 default:
59 fmt::println(std::cerr, "Error: Unknown volume type.");
60 return false;
61 }
62 }
63
64 static void ExtractDirectory(const DiscIO::Volume& disc_volume, const DiscIO::Partition& partition,
65 const std::string& path, const std::string& out, bool quiet)
66 {
67 const DiscIO::FileSystem* filesystem = disc_volume.GetFileSystem(partition);
68 if (!filesystem)
69 return;
70
71 const std::unique_ptr<DiscIO::FileInfo> info = filesystem->FindFileInfo(path);
72 u32 size = info->GetTotalChildren();
73 u32 files = 0;
74 ExportDirectory(
75 disc_volume, partition, *info, true, "", out,
76 [&files, &size, &quiet](const std::string& current) {
77 files++;
78 const float progress = static_cast<float>(files) / static_cast<float>(size) * 100;
79 if (!quiet)
80 fmt::println(std::cerr, "Extracting: {} | {}%", current, static_cast<int>(progress));
81 return false;
82 });
83 }
84
85 static bool ExtractSystemData(const DiscIO::Volume& disc_volume, const DiscIO::Partition& partition,
86 const std::string& out)
87 {
88 return ExportSystemData(disc_volume, partition, out);
89 }
90
91 static void ExtractPartition(const DiscIO::Volume& disc_volume, const DiscIO::Partition& partition,
92 const std::string& out, bool quiet)
93 {
94 ExtractDirectory(disc_volume, partition, "", out + "/files", quiet);
95 ExtractSystemData(disc_volume, partition, out);
96 }
97
98 static void ListRecursively(const std::string& path, const DiscIO::FileInfo& info,
99 std::string* result_text)
100 {
101 // Don't print the root.
102 if (!path.empty())
103 {
104 const std::string line = fmt::format("{}\n", path);
105 fmt::print("{}", line);
106 result_text->append(line);
107 }
108 for (const DiscIO::FileInfo& child_info : info)
109 {
110 std::string child_path = path + child_info.GetName();
111 if (child_info.IsDirectory())
112 child_path += '/';
113 ListRecursively(child_path, child_info, result_text);
114 }
115 }
116
117 static bool ListPartition(const DiscIO::Volume& disc_volume, const DiscIO::Partition& partition,
118 const std::string& partition_name, const std::string& path,
119 std::string* result_text)
120 {
121 const DiscIO::FileSystem* filesystem = disc_volume.GetFileSystem(partition);
122 if (!filesystem)
123 {
124 fmt::println(std::cerr, "Warning: partition {} has no filesystem.", partition_name);
125 return false;
126 }
127 const std::unique_ptr<DiscIO::FileInfo> info = filesystem->FindFileInfo(path);
128
129 if (!info)
130 {
131 if (!partition_name.empty())
132 {
133 fmt::println(std::cerr, "Warning: {} does not exist in this partition.", path);
134 }
135 return false;
136 }
137
138 // Canonicalize user-provided path by reconstructing it using GetPath().
139 ListRecursively(info->GetPath(), *info, result_text);
140 return true;
141 }
142
143 static bool ListVolume(const DiscIO::Volume& disc_volume, const std::string& path,
144 const std::string& specific_partition_name, bool quiet,
145 std::string* result_text)
146 {
147 if (disc_volume.GetPartitions().empty())
148 {
149 return ListPartition(disc_volume, DiscIO::PARTITION_NONE, specific_partition_name, path,
150 result_text);
151 }
152
153 bool success = false;
154 for (DiscIO::Partition& p : disc_volume.GetPartitions())
155 {
156 const std::optional<u32> partition_type = disc_volume.GetPartitionType(p);
157 if (!partition_type)
158 {
159 fmt::println(std::cerr, "Error: Could not get partition type.");
160 return false;
161 }
162 const std::string partition_name = DiscIO::NameForPartitionType(*partition_type, true);
163
164 if (!specific_partition_name.empty() &&
165 !Common::CaseInsensitiveEquals(partition_name, specific_partition_name))
166 {
167 continue;
168 }
169
170 const std::string partition_start =
171 fmt::format("/// PARTITION: {} <{}> ///\n", partition_name, path);
172 fmt::print(std::cout, "{}", partition_start);
173 result_text->append(partition_start);
174
175 success |= ListPartition(disc_volume, p, partition_name, path, result_text);
176 }
177
178 return success;
179 }
180
181 static bool HandleExtractPartition(const std::string& output, const std::string& single_file_path,
182 const std::string& partition_name,
183 const DiscIO::Volume& disc_volume,
184 const DiscIO::Partition& partition, bool quiet, bool single)
185 {
186 std::string file;
187 file.append(output).append("/");
188 file.append(partition_name).append("/");
189 if (!single)
190 {
191 ExtractPartition(disc_volume, partition, file, quiet);
192 return true;
193 }
194
195 const auto file_info = GetFileInfo(disc_volume, partition, single_file_path);
196 if (file_info != nullptr)
197 {
198 file.append("files/").append(single_file_path);
199 File::CreateFullPath(file);
200 if (file_info->IsDirectory())
201 {
202 file = PathToString(StringToPath(file).remove_filename());
203 ExtractDirectory(disc_volume, partition, single_file_path, file, quiet);
204 }
205 else
206 {
207 ExtractFile(disc_volume, partition, single_file_path, file);
208 }
209
210 return true;
211 }
212 return false;
213 }
214
215 int Extract(const std::vector<std::string>& args)
216 {
217 optparse::OptionParser parser;
218
219 parser.usage("usage: extract [options]...");
220
221 parser.add_option("-i", "--input")
222 .type("string")
223 .action("store")
224 .help("Path to disc image FILE.")
225 .metavar("FILE");
226 parser.add_option("-o", "--output")
227 .type("string")
228 .action("store")
229 .help("Path to the destination FOLDER.")
230 .metavar("FOLDER");
231 parser.add_option("-p", "--partition")
232 .type("string")
233 .action("store")
234 .help("Which specific partition you want to extract.");
235 parser.add_option("-s", "--single")
236 .type("string")
237 .action("store")
238 .help("Which specific file/directory you want to extract.");
239 parser.add_option("-l", "--list")
240 .action("store_true")
241 .help("List all files in volume/partition. Will print the directory/file specified with "
242 "--single if defined.");
243 parser.add_option("-q", "--quiet")
244 .action("store_true")
245 .help("Mute all messages except for errors.");
246 parser.add_option("-g", "--gameonly")
247 .action("store_true")
248 .help("Only extracts the DATA partition.");
249
250 const optparse::Values& options = parser.parse_args(args);
251
252 const bool quiet = options.is_set("quiet");
253 const bool gameonly = options.is_set("gameonly");
254
255 if (!options.is_set("input"))
256 {
257 fmt::println(std::cerr, "Error: No input image set");
258 return EXIT_FAILURE;
259 }
260 const std::string& input_file_path = options["input"];
261
262 const std::string& output_folder_path = options["output"];
263
264 if (!options.is_set("output") && !options.is_set("list"))
265 {
266 fmt::println(std::cerr, "Error: No output folder set");
267 return EXIT_FAILURE;
268 }
269
270 const std::string& single_file_path = options["single"];
271 std::string specific_partition = options["partition"];
272
273 if (options.is_set("output") && !options.is_set("list"))
274 File::CreateDirs(output_folder_path);
275
276 if (gameonly)
277 specific_partition = std::string("data");
278
279 if (const std::unique_ptr<DiscIO::BlobReader> blob_reader =
280 DiscIO::CreateBlobReader(input_file_path);
281 !blob_reader)
282 {
283 fmt::println(std::cerr, "Error: Unable to open disc image");
284 return EXIT_FAILURE;
285 }
286
287 const std::unique_ptr<DiscIO::Volume> disc_volume = DiscIO::CreateVolume(input_file_path);
288
289 if (!disc_volume)
290 {
291 fmt::println(std::cerr, "Error: Unable to open volume");
292 return EXIT_FAILURE;
293 }
294
295 if (!VolumeSupported(*disc_volume))
296 return EXIT_FAILURE;
297
298 if (options.is_set("list"))
299 {
300 std::string list_path = options.is_set("single") ? single_file_path : "/";
301 if (quiet && !options.is_set("output"))
302 {
303 fmt::println(std::cerr, "Error: --quiet is set but no output file provided. Please either "
304 "remove the --quiet flag or specify --output");
305 return EXIT_FAILURE;
306 }
307
308 std::string text;
309 if (!ListVolume(*disc_volume, list_path, specific_partition, quiet, &text))
310 {
311 fmt::println(std::cerr, "Error: Found nothing to list");
312 return EXIT_FAILURE;
313 }
314
315 if (options.is_set("output"))
316 {
317 File::CreateFullPath(output_folder_path);
318 std::ofstream output_file;
319 output_file.open(output_folder_path);
320 if (!output_file.is_open())
321 {
322 fmt::println(std::cerr, "Error: Unable to open output file");
323 return EXIT_FAILURE;
324 }
325 output_file << text;
326 }
327
328 return EXIT_SUCCESS;
329 }
330
331 bool extracted_one = false;
332
333 if (disc_volume->GetPartitions().empty())
334 {
335 if (options.is_set("partition"))
336 {
337 fmt::println(
338 std::cerr,
339 "Warning: --partition has a value even though this image doesn't have any partitions.");
340 }
341
342 extracted_one = HandleExtractPartition(output_folder_path, single_file_path, "", *disc_volume,
343 DiscIO::PARTITION_NONE, quiet, options.is_set("single"));
344 }
345 else
346 {
347 for (DiscIO::Partition& p : disc_volume->GetPartitions())
348 {
349 if (const std::optional<u32> partition_type = disc_volume->GetPartitionType(p))
350 {
351 const std::string partition_name = DiscIO::NameForPartitionType(*partition_type, true);
352
353 if (!specific_partition.empty() &&
354 !Common::CaseInsensitiveEquals(specific_partition, partition_name))
355 {
356 continue;
357 }
358
359 extracted_one |=
360 HandleExtractPartition(output_folder_path, single_file_path, partition_name,
361 *disc_volume, p, quiet, options.is_set("single"));
362 }
363 }
364 }
365
366 if (!extracted_one)
367 {
368 if (options.is_set("single"))
369 fmt::print(std::cerr, "Error: No file/folder was extracted.");
370 else
371 fmt::print(std::cerr, "Error: No partitions were extracted.");
372 if (options.is_set("partition"))
373 fmt::println(std::cerr, " Maybe you misspelled your specified partition?");
374 fmt::println(std::cerr, "\n");
375 return EXIT_FAILURE;
376 }
377
378 if (!quiet)
379 fmt::println(std::cerr, "Finished Successfully!");
380 return EXIT_SUCCESS;
381 }
382 } // namespace DolphinTool