Skip to content

Commit

Permalink
Refactor file size code
Browse files Browse the repository at this point in the history
  • Loading branch information
zachleat committed Dec 19, 2024
1 parent 8b7f9e2 commit 124a9c0
Showing 1 changed file with 19 additions and 12 deletions.
31 changes: 19 additions & 12 deletions src/image.js
Original file line number Diff line number Diff line change
Expand Up @@ -483,6 +483,19 @@ class Image {
return this._transformRawFiles(results, outputFormats);
}

getOutputSize(contents, filePath) {
if(this.options.svgCompressionSize === "br") {
return brotliSize.sync(contents);
}

if(filePath) {
return fs.statSync(filePath).size;
}

// when filePath does not exist, this contents is a string from SVG
return contents.length;
}

isOutputCached(targetFile, sourceInput) {
if(!this.options.useCache) {
return false;
Expand Down Expand Up @@ -524,15 +537,12 @@ class Image {
stat.buffer = contents;
}

if(outputFormat === "svg" && this.options.svgCompressionSize === "br") {
if(!contents) {
contents = this.getFileContents(stat.outputPath);
}
stat.size = brotliSize.sync(contents);
} else {
stat.size = fs.statSync(stat.outputPath).size;
if(outputFormat === "svg" && this.options.svgCompressionSize === "br" && !contents) {
contents = this.getFileContents(stat.outputPath);
}

stat.size = this.getOutputSize(contents, stat.outputPath);

outputFilePromises.push(Promise.resolve(stat));
continue;
}
Expand Down Expand Up @@ -560,15 +570,12 @@ class Image {
this.directoryManager.create(this.options.outputDir);
}

// Format hooks take priority over Sharp processing.
// format hooks are only used for SVG out of the box
if(this.options.formatHooks && this.options.formatHooks[outputFormat]) {
let hookResult = await this.options.formatHooks[outputFormat].call(stat, sharpInstance);
if(hookResult) {
if(this.options.svgCompressionSize === "br") {
stat.size = brotliSize.sync(hookResult);
} else {
stat.size = hookResult.length;
}
stat.size = this.getOutputSize(hookResult);

if(this.options.dryRun) {
stat.buffer = Buffer.from(hookResult);
Expand Down

0 comments on commit 124a9c0

Please sign in to comment.