Skip to content

Commit

Permalink
fix: second attempt at shortening filename
Browse files Browse the repository at this point in the history
  • Loading branch information
aalemayhu committed Oct 15, 2024
1 parent 71b1727 commit 19b6aa2
Showing 1 changed file with 21 additions and 4 deletions.
25 changes: 21 additions & 4 deletions helpers/write_apkg.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import os
import sys
import re
import tempfile

from genanki import Deck, Package

"""
Expand Down Expand Up @@ -44,7 +46,7 @@ def _write_new_apkg(deck_payloads, media_files):
package = Package(decks)
package.media_files = media_files

# Ensure deck_payload is defined before using it
# Ensure deck_payloads is defined before using it
if deck_payloads:
sanitized_name = sanitize_filename(deck_payloads[0]["name"])
else:
Expand All @@ -53,8 +55,23 @@ def _write_new_apkg(deck_payloads, media_files):
max_name_length = 255 - len(first_deck_id) - len('.apkg') - 1
truncated_name = sanitized_name[:max_name_length]

output_filename = f'{truncated_name}-{first_deck_id}.apkg'
# Use a temporary file to avoid file name too long errors
with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
output_filename = f'{truncated_name}-{first_deck_id}.apkg'
tmp_file.name = output_filename

try:
package.write_to_file(tmp_file.name)
except OSError as e:
if e.errno == 36: # File name too long
# Handle the error, e.g., shorten the filename or move to a different directory
print("File name too long. Shortening filename.")
tmp_file.name = f'{truncated_name[:max_name_length - 10]}-truncated-{first_deck_id}.apkg'
package.write_to_file(tmp_file.name)
else:
raise e # Re-raise other exceptions

package.write_to_file(output_filename)
final_path = os.path.join(os.getcwd() , tmp_file.name)
os.rename(tmp_file.name, final_path)

sys.stdout.write(os.getcwd() + "/" + output_filename)
sys.stdout.write(final_path)

0 comments on commit 19b6aa2

Please sign in to comment.