Skip to content

Commit 8b639b9

Browse files
committed
Handle absent lzma library
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 <stephen@that.guru>
1 parent be15939 commit 8b639b9

File tree

1 file changed

+20
-4
lines changed

1 file changed

+20
-4
lines changed

cmd2/cmd2.py

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4813,7 +4813,12 @@ def _initialize_history(self, hist_file: str) -> None:
48134813
to this file when the application exits.
48144814
"""
48154815
import json
4816-
import lzma
4816+
try:
4817+
import lzma
4818+
bz2 = None
4819+
except ModuleNotFoundError: # pragma: no cover
4820+
lzma = None
4821+
import bz2
48174822

48184823
self.history = History()
48194824
# with no persistent history, nothing else in this method is relevant
@@ -4841,7 +4846,10 @@ def _initialize_history(self, hist_file: str) -> None:
48414846
try:
48424847
with open(hist_file, 'rb') as fobj:
48434848
compressed_bytes = fobj.read()
4844-
history_json = lzma.decompress(compressed_bytes).decode(encoding='utf-8')
4849+
if lzma is not None:
4850+
history_json = lzma.decompress(compressed_bytes).decode(encoding='utf-8')
4851+
else:
4852+
history_json = bz2.decompress(compressed_bytes).decode(encoding='utf-8')
48454853
self.history = History.from_json(history_json)
48464854
except FileNotFoundError:
48474855
# Just use an empty history
@@ -4879,15 +4887,23 @@ def _initialize_history(self, hist_file: str) -> None:
48794887

48804888
def _persist_history(self) -> None:
48814889
"""Write history out to the persistent history file as compressed JSON"""
4882-
import lzma
4890+
try:
4891+
import lzma
4892+
bz2 = None
4893+
except ModuleNotFoundError: # pragma: no cover
4894+
lzma = None
4895+
import bz2
48834896

48844897
if not self.persistent_history_file:
48854898
return
48864899

48874900
self.history.truncate(self._persistent_history_length)
48884901
try:
48894902
history_json = self.history.to_json()
4890-
compressed_bytes = lzma.compress(history_json.encode(encoding='utf-8'))
4903+
if lzma is not None:
4904+
compressed_bytes = lzma.compress(history_json.encode(encoding='utf-8'))
4905+
else:
4906+
compressed_bytes = bz2.compress(history_json.encode(encoding='utf-8'))
48914907

48924908
with open(self.persistent_history_file, 'wb') as fobj:
48934909
fobj.write(compressed_bytes)

0 commit comments

Comments
 (0)