safeEval: Fix support for Python 3.14

This commit is contained in:
Valentin Lorentz 2024-05-29 07:37:39 +02:00 committed by Val Lorentz
parent 9a4dca8054
commit f5302f0bfc

View File

@ -167,7 +167,9 @@ def saltHash(password, salt=None, hash='sha'):
hasher = crypt.md5 hasher = crypt.md5
return '|'.join([salt, hasher((salt + password).encode('utf8')).hexdigest()]) return '|'.join([salt, hasher((salt + password).encode('utf8')).hexdigest()])
_astStr2 = ast.Str if minisix.PY2 else ast.Bytes _OLD_AST = sys.version_info[0:2] < (3, 8)
"""Whether the AST classes predate the python 3.8 API changes"""
def safeEval(s, namespace=None): def safeEval(s, namespace=None):
"""Evaluates s, safely. Useful for turning strings into tuples/lists/etc. """Evaluates s, safely. Useful for turning strings into tuples/lists/etc.
without unsafely using eval().""" without unsafely using eval()."""
@ -175,12 +177,11 @@ def safeEval(s, namespace=None):
node = ast.parse(s, mode='eval').body node = ast.parse(s, mode='eval').body
except SyntaxError as e: except SyntaxError as e:
raise ValueError('Invalid string: %s.' % e) raise ValueError('Invalid string: %s.' % e)
def checkNode(node): def checkNode(node):
if node.__class__ is ast.Expr: if node.__class__ is ast.Expr:
node = node.value node = node.value
if node.__class__ in (ast.Num, if not _OLD_AST and node.__class__ is ast.Constant:
ast.Str,
_astStr2):
return True return True
elif node.__class__ in (ast.List, elif node.__class__ in (ast.List,
ast.Tuple): ast.Tuple):
@ -196,10 +197,12 @@ def safeEval(s, namespace=None):
return True return True
else: else:
return False return False
elif node.__class__ is ast.NameConstant: elif _OLD_AST and node.__class__ in (ast.Num, ast.Str, ast.Bytes):
# ast.Num, ast.Str, ast.Bytes are deprecated since Python 3.8
# and removed since Python 3.14; replaced by ast.Constant.
return True return True
elif sys.version_info[0:2] >= (3, 8) and \ elif _OLD_AST and node.__class__ is ast.NameConstant:
node.__class__ is ast.Constant: # ditto
return True return True
else: else:
return False return False