Skip to content

Commit

Permalink
Handle absent lzma library
Browse files Browse the repository at this point in the history
The lzma library may be missing in some environments as it is an
optional dependency [1]. Fall back to bz2 in this instance.

[1] https://devguide.python.org/getting-started/setup-building/

Signed-off-by: Stephen Finucane <[email protected]>
  • Loading branch information
stephenfin committed Aug 19, 2024
1 parent be15939 commit 8b639b9
Showing 1 changed file with 20 additions and 4 deletions.
24 changes: 20 additions & 4 deletions cmd2/cmd2.py
Original file line number Diff line number Diff line change
Expand Up @@ -4813,7 +4813,12 @@ def _initialize_history(self, hist_file: str) -> None:
to this file when the application exits.
"""
import json
import lzma
try:
import lzma
bz2 = None
except ModuleNotFoundError: # pragma: no cover
lzma = None
import bz2

self.history = History()
# with no persistent history, nothing else in this method is relevant
Expand Down Expand Up @@ -4841,7 +4846,10 @@ def _initialize_history(self, hist_file: str) -> None:
try:
with open(hist_file, 'rb') as fobj:
compressed_bytes = fobj.read()
history_json = lzma.decompress(compressed_bytes).decode(encoding='utf-8')
if lzma is not None:
history_json = lzma.decompress(compressed_bytes).decode(encoding='utf-8')
else:
history_json = bz2.decompress(compressed_bytes).decode(encoding='utf-8')
self.history = History.from_json(history_json)
except FileNotFoundError:
# Just use an empty history
Expand Down Expand Up @@ -4879,15 +4887,23 @@ def _initialize_history(self, hist_file: str) -> None:

def _persist_history(self) -> None:
"""Write history out to the persistent history file as compressed JSON"""
import lzma
try:
import lzma
bz2 = None
except ModuleNotFoundError: # pragma: no cover
lzma = None
import bz2

if not self.persistent_history_file:
return

self.history.truncate(self._persistent_history_length)
try:
history_json = self.history.to_json()
compressed_bytes = lzma.compress(history_json.encode(encoding='utf-8'))
if lzma is not None:
compressed_bytes = lzma.compress(history_json.encode(encoding='utf-8'))
else:
compressed_bytes = bz2.compress(history_json.encode(encoding='utf-8'))

with open(self.persistent_history_file, 'wb') as fobj:
fobj.write(compressed_bytes)
Expand Down

0 comments on commit 8b639b9

Please sign in to comment.