Skip to content

Commit 09b28aa

Browse files
committed
Scratch3Reader: Use ZipReader
1 parent 197ea0b commit 09b28aa

File tree

2 files changed

+12
-40
lines changed

2 files changed

+12
-40
lines changed

src/internal/scratch3reader.cpp

Lines changed: 12 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
#include "scratch3reader.h"
1616
#include "reader_common.h"
17+
#include "zipreader.h"
1718

1819
using namespace libscratchcpp;
1920
using json = nlohmann::json;
@@ -299,14 +300,9 @@ bool Scratch3Reader::load()
299300
else
300301
printErr(std::string("could not parse ") + step, e.what());
301302

302-
// Close the zip file
303-
zip_close(m_zip);
304-
305303
return false;
306304
}
307305

308-
// Close the zip file
309-
zip_close(m_zip);
310306
return true;
311307
}
312308

@@ -352,37 +348,15 @@ std::vector<std::string> Scratch3Reader::extensions()
352348

353349
void Scratch3Reader::read()
354350
{
355-
// Open the zip file
356-
unsigned char *buf;
357-
size_t bufsize;
358-
m_zip = zip_open(fileName().c_str(), 0, 'r');
359-
if (!m_zip) {
360-
std::cerr << "Failed to open project file" << std::endl;
361-
return;
362-
}
363-
364-
// Extract project.json
365-
zip_entry_open(m_zip, "project.json");
366-
bufsize = zip_entry_size(m_zip);
367-
buf = (unsigned char *)calloc(sizeof(unsigned char), bufsize);
368-
zip_entry_noallocread(m_zip, (void *)buf, bufsize);
369-
zip_entry_close(m_zip);
370-
std::string str(reinterpret_cast<char const *>(buf));
371-
free(buf);
372-
373-
// Remove garbage after the JSON
374-
int end;
375-
for (end = str.size(); end >= 0; end--) {
376-
char ch = str[end];
377-
if (ch == '}')
378-
break;
379-
}
380-
std::string out = str.substr(0, end + 1);
381-
382-
// Parse the JSON
383-
try {
384-
m_json = json::parse(out);
385-
} catch (std::exception &e) {
386-
printErr("invalid JSON file", e.what());
387-
}
351+
// Read project.json
352+
ZipReader reader(fileName());
353+
if (reader.open()) {
354+
// Parse the JSON
355+
try {
356+
m_json = json::parse(reader.readFileToString("project.json"));
357+
} catch (std::exception &e) {
358+
printErr("invalid JSON file", e.what());
359+
}
360+
} else
361+
printErr("could not read " + fileName());
388362
}

src/internal/scratch3reader.h

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44

55
#include "iprojectreader.h"
66
#include <nlohmann/json.hpp>
7-
#include <zip.h>
87

98
namespace libscratchcpp
109
{
@@ -21,7 +20,6 @@ class Scratch3Reader : public IProjectReader
2120

2221
private:
2322
void read();
24-
struct zip_t *m_zip = nullptr;
2523
nlohmann::json m_json = "";
2624
std::vector<std::shared_ptr<Target>> m_targets;
2725
std::vector<std::shared_ptr<Broadcast>> m_broadcasts;

0 commit comments

Comments
 (0)