Skip to content

Commit

Permalink
fix: long file names (#95)
Browse files Browse the repository at this point in the history
  • Loading branch information
aalemayhu authored Oct 17, 2024
1 parent 71b1727 commit 972e76a
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 10 deletions.
4 changes: 2 additions & 2 deletions .pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -336,7 +336,7 @@ indent-after-paren=4
indent-string=' '

# Maximum number of characters on a single line.
max-line-length=100
max-line-length=150

# Maximum number of lines in a module.
max-module-lines=1000
Expand Down Expand Up @@ -629,4 +629,4 @@ init-import=no
# builtins.
redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io

disable=import-error
disable=import-error
33 changes: 25 additions & 8 deletions helpers/write_apkg.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
"""
This module provides functionality to write a new Anki package file (.apkg) using provided deck payloads and media files.
"""

import os
import sys
import re
from genanki import Deck, Package
import tempfile

"""
This module provides functionality to write a new Anki package file (.apkg) using provided deck payloads and media files.
"""
from genanki import Deck, Package

def sanitize_filename(filename):
"""
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 error:
if error.errno == 36: # File name too long
tmp_file.name = (
f'{truncated_name[:max_name_length - 10]}-truncated-{first_deck_id}.apkg'
)
package.write_to_file(tmp_file.name)
else:
raise error # 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 972e76a

Please sign in to comment.