Skip to content

Commit

Permalink
Add overwrite mode compatibility
Browse files Browse the repository at this point in the history
This is done by creating a copy of the input file that is then used to
copy over onto the output file, effectively reverting it. This was the
best solution I could find.
  • Loading branch information
ARAKHN1D committed May 14, 2024
1 parent 1a3a6ec commit e3149d3
Showing 1 changed file with 16 additions and 7 deletions.
23 changes: 16 additions & 7 deletions src/compressor.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,13 @@ def _compress_images(self):
GLib.idle_add(self.c_enable_compression, True)

def run_command(self, command, result_item):
if not self.do_new_file:
# Creates a copy of the input file
# This is done in case the output file is larger than the input file
result_item_path = Path(result_item.filename)
original_filename = Path(result_item.filename).with_stem(f"{result_item_path.stem}-og")
shutil.copy2(result_item.filename, original_filename)

error = False
error_message = ''
try:
Expand All @@ -99,14 +106,16 @@ def run_command(self, command, result_item):
if new_file_data.is_file():
result_item.new_size = new_file_data.stat().st_size

# This check is mainly for WebP compression
try:
if result_item.new_size > result_item.size:
# This check is mainly for compressors that don't have a way
# to automatically detect and skip files
if result_item.new_size > result_item.size:
if self.do_new_file:
shutil.copy2(result_item.filename, result_item.new_filename)
result_item.new_size = new_file_data.stat().st_size
except shutil.SameFileError as err:
# This will happen with overwrite mode on
pass
else:
shutil.copy2(original_filename, result_item.new_filename)
result_item.new_size = new_file_data.stat().st_size
original_filename.unlink(True)

else:
logging.error(str(output))
error_message = _("Can't find the compressed file")
Expand Down

0 comments on commit e3149d3

Please sign in to comment.