summaryrefslogtreecommitdiff
path: root/Source/Core/DolphinTool/ExtractCommand.cpp
blob: 57106d6406d1d2a2f234e6f86c1319ee12cb4aa0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
// Copyright 2024 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include "DolphinTool/ExtractCommand.h"

#include <filesystem>
#include <iostream>

#include <fmt/format.h>
#include <fmt/ostream.h>

#include <OptionParser.h>

#include "Common/FileUtil.h"

#include "DiscIO/DiscExtractor.h"
#include "DiscIO/DiscUtils.h"
#include "DiscIO/Filesystem.h"
#include "DiscIO/Volume.h"

namespace DolphinTool
{
static void ExtractFile(const DiscIO::Volume& disc_volume, const DiscIO::Partition& partition,
                        const std::string& path, const std::string& out)
{
  const DiscIO::FileSystem* filesystem = disc_volume.GetFileSystem(partition);
  if (!filesystem)
    return;

  ExportFile(disc_volume, partition, filesystem->FindFileInfo(path).get(), out);
}

static std::unique_ptr<DiscIO::FileInfo> GetFileInfo(const DiscIO::Volume& disc_volume,
                                                     const DiscIO::Partition& partition,
                                                     const std::string& path)
{
  const DiscIO::FileSystem* filesystem = disc_volume.GetFileSystem(partition);
  if (!filesystem)
    return nullptr;

  return filesystem->FindFileInfo(path);
}

static bool VolumeSupported(const DiscIO::Volume& disc_volume)
{
  switch (disc_volume.GetVolumeType())
  {
  case DiscIO::Platform::WiiWAD:
    fmt::println(std::cerr, "Error: Wii WADs are not supported.");
    return false;
  case DiscIO::Platform::ELFOrDOL:
    fmt::println(std::cerr,
                 "Error: *.elf or *.dol have no filesystem and are therefore not supported.");
    return false;
  case DiscIO::Platform::WiiDisc:
  case DiscIO::Platform::GameCubeDisc:
    return true;
  default:
    fmt::println(std::cerr, "Error: Unknown volume type.");
    return false;
  }
}

static void ExtractDirectory(const DiscIO::Volume& disc_volume, const DiscIO::Partition& partition,
                             const std::string& path, const std::string& out, bool quiet)
{
  const DiscIO::FileSystem* filesystem = disc_volume.GetFileSystem(partition);
  if (!filesystem)
    return;

  const std::unique_ptr<DiscIO::FileInfo> info = filesystem->FindFileInfo(path);
  u32 size = info->GetTotalChildren();
  u32 files = 0;
  ExportDirectory(
      disc_volume, partition, *info, true, "", out,
      [&files, &size, &quiet](const std::string& current) {
        files++;
        const float progress = static_cast<float>(files) / static_cast<float>(size) * 100;
        if (!quiet)
          fmt::println(std::cerr, "Extracting: {} | {}%", current, static_cast<int>(progress));
        return false;
      });
}

static bool ExtractSystemData(const DiscIO::Volume& disc_volume, const DiscIO::Partition& partition,
                              const std::string& out)
{
  return ExportSystemData(disc_volume, partition, out);
}

static void ExtractPartition(const DiscIO::Volume& disc_volume, const DiscIO::Partition& partition,
                             const std::string& out, bool quiet)
{
  ExtractDirectory(disc_volume, partition, "", out + "/files", quiet);
  ExtractSystemData(disc_volume, partition, out);
}

static void ListRecursively(const std::string& path, const DiscIO::FileInfo& info,
                            std::string* result_text)
{
  // Don't print the root.
  if (!path.empty())
  {
    const std::string line = fmt::format("{}\n", path);
    fmt::print("{}", line);
    result_text->append(line);
  }
  for (const DiscIO::FileInfo& child_info : info)
  {
    std::string child_path = path + child_info.GetName();
    if (child_info.IsDirectory())
      child_path += '/';
    ListRecursively(child_path, child_info, result_text);
  }
}

static bool ListPartition(const DiscIO::Volume& disc_volume, const DiscIO::Partition& partition,
                          const std::string& partition_name, const std::string& path,
                          std::string* result_text)
{
  const DiscIO::FileSystem* filesystem = disc_volume.GetFileSystem(partition);
  if (!filesystem)
  {
    fmt::println(std::cerr, "Warning: partition {} has no filesystem.", partition_name);
    return false;
  }
  const std::unique_ptr<DiscIO::FileInfo> info = filesystem->FindFileInfo(path);

  if (!info)
  {
    if (!partition_name.empty())
    {
      fmt::println(std::cerr, "Warning: {} does not exist in this partition.", path);
    }
    return false;
  }

  // Canonicalize user-provided path by reconstructing it using GetPath().
  ListRecursively(info->GetPath(), *info, result_text);
  return true;
}

static bool ListVolume(const DiscIO::Volume& disc_volume, const std::string& path,
                       const std::string& specific_partition_name, bool quiet,
                       std::string* result_text)
{
  if (disc_volume.GetPartitions().empty())
  {
    return ListPartition(disc_volume, DiscIO::PARTITION_NONE, specific_partition_name, path,
                         result_text);
  }

  bool success = false;
  for (DiscIO::Partition& p : disc_volume.GetPartitions())
  {
    const std::optional<u32> partition_type = disc_volume.GetPartitionType(p);
    if (!partition_type)
    {
      fmt::println(std::cerr, "Error: Could not get partition type.");
      return false;
    }
    const std::string partition_name = DiscIO::NameForPartitionType(*partition_type, true);

    if (!specific_partition_name.empty() &&
        !Common::CaseInsensitiveEquals(partition_name, specific_partition_name))
    {
      continue;
    }

    const std::string partition_start =
        fmt::format("/// PARTITION: {} <{}> ///\n", partition_name, path);
    fmt::print(std::cout, "{}", partition_start);
    result_text->append(partition_start);

    success |= ListPartition(disc_volume, p, partition_name, path, result_text);
  }

  return success;
}

static bool HandleExtractPartition(const std::string& output, const std::string& single_file_path,
                                   const std::string& partition_name,
                                   const DiscIO::Volume& disc_volume,
                                   const DiscIO::Partition& partition, bool quiet, bool single)
{
  std::string file;
  file.append(output).append("/");
  file.append(partition_name).append("/");
  if (!single)
  {
    ExtractPartition(disc_volume, partition, file, quiet);
    return true;
  }

  const auto file_info = GetFileInfo(disc_volume, partition, single_file_path);
  if (file_info != nullptr)
  {
    file.append("files/").append(single_file_path);
    File::CreateFullPath(file);
    if (file_info->IsDirectory())
    {
      file = PathToString(StringToPath(file).remove_filename());
      ExtractDirectory(disc_volume, partition, single_file_path, file, quiet);
    }
    else
    {
      ExtractFile(disc_volume, partition, single_file_path, file);
    }

    return true;
  }
  return false;
}

int Extract(const std::vector<std::string>& args)
{
  optparse::OptionParser parser;

  parser.usage("usage: extract [options]...");

  parser.add_option("-i", "--input")
      .type("string")
      .action("store")
      .help("Path to disc image FILE.")
      .metavar("FILE");
  parser.add_option("-o", "--output")
      .type("string")
      .action("store")
      .help("Path to the destination FOLDER.")
      .metavar("FOLDER");
  parser.add_option("-p", "--partition")
      .type("string")
      .action("store")
      .help("Which specific partition you want to extract.");
  parser.add_option("-s", "--single")
      .type("string")
      .action("store")
      .help("Which specific file/directory you want to extract.");
  parser.add_option("-l", "--list")
      .action("store_true")
      .help("List all files in volume/partition. Will print the directory/file specified with "
            "--single if defined.");
  parser.add_option("-q", "--quiet")
      .action("store_true")
      .help("Mute all messages except for errors.");
  parser.add_option("-g", "--gameonly")
      .action("store_true")
      .help("Only extracts the DATA partition.");

  const optparse::Values& options = parser.parse_args(args);

  const bool quiet = options.is_set("quiet");
  const bool gameonly = options.is_set("gameonly");

  if (!options.is_set("input"))
  {
    fmt::println(std::cerr, "Error: No input image set");
    return EXIT_FAILURE;
  }
  const std::string& input_file_path = options["input"];

  const std::string& output_folder_path = options["output"];

  if (!options.is_set("output") && !options.is_set("list"))
  {
    fmt::println(std::cerr, "Error: No output folder set");
    return EXIT_FAILURE;
  }

  const std::string& single_file_path = options["single"];
  std::string specific_partition = options["partition"];

  if (options.is_set("output") && !options.is_set("list"))
    File::CreateDirs(output_folder_path);

  if (gameonly)
    specific_partition = std::string("data");

  if (const std::unique_ptr<DiscIO::BlobReader> blob_reader =
          DiscIO::CreateBlobReader(input_file_path);
      !blob_reader)
  {
    fmt::println(std::cerr, "Error: Unable to open disc image");
    return EXIT_FAILURE;
  }

  const std::unique_ptr<DiscIO::Volume> disc_volume = DiscIO::CreateVolume(input_file_path);

  if (!disc_volume)
  {
    fmt::println(std::cerr, "Error: Unable to open volume");
    return EXIT_FAILURE;
  }

  if (!VolumeSupported(*disc_volume))
    return EXIT_FAILURE;

  if (options.is_set("list"))
  {
    std::string list_path = options.is_set("single") ? single_file_path : "/";
    if (quiet && !options.is_set("output"))
    {
      fmt::println(std::cerr, "Error: --quiet is set but no output file provided. Please either "
                              "remove the --quiet flag or specify --output");
      return EXIT_FAILURE;
    }

    std::string text;
    if (!ListVolume(*disc_volume, list_path, specific_partition, quiet, &text))
    {
      fmt::println(std::cerr, "Error: Found nothing to list");
      return EXIT_FAILURE;
    }

    if (options.is_set("output"))
    {
      File::CreateFullPath(output_folder_path);
      std::ofstream output_file;
      output_file.open(output_folder_path);
      if (!output_file.is_open())
      {
        fmt::println(std::cerr, "Error: Unable to open output file");
        return EXIT_FAILURE;
      }
      output_file << text;
    }

    return EXIT_SUCCESS;
  }

  bool extracted_one = false;

  if (disc_volume->GetPartitions().empty())
  {
    if (options.is_set("partition"))
    {
      fmt::println(
          std::cerr,
          "Warning: --partition has a value even though this image doesn't have any partitions.");
    }

    extracted_one = HandleExtractPartition(output_folder_path, single_file_path, "", *disc_volume,
                                           DiscIO::PARTITION_NONE, quiet, options.is_set("single"));
  }
  else
  {
    for (DiscIO::Partition& p : disc_volume->GetPartitions())
    {
      if (const std::optional<u32> partition_type = disc_volume->GetPartitionType(p))
      {
        const std::string partition_name = DiscIO::NameForPartitionType(*partition_type, true);

        if (!specific_partition.empty() &&
            !Common::CaseInsensitiveEquals(specific_partition, partition_name))
        {
          continue;
        }

        extracted_one |=
            HandleExtractPartition(output_folder_path, single_file_path, partition_name,
                                   *disc_volume, p, quiet, options.is_set("single"));
      }
    }
  }

  if (!extracted_one)
  {
    if (options.is_set("single"))
      fmt::print(std::cerr, "Error: No file/folder was extracted.");
    else
      fmt::print(std::cerr, "Error: No partitions were extracted.");
    if (options.is_set("partition"))
      fmt::println(std::cerr, " Maybe you misspelled your specified partition?");
    fmt::println(std::cerr, "\n");
    return EXIT_FAILURE;
  }

  if (!quiet)
    fmt::println(std::cerr, "Finished Successfully!");
  return EXIT_SUCCESS;
}
}  // namespace DolphinTool