utils: add support for msgspec with stdlib json fallback
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
This commit is contained in:
@@ -14,13 +14,13 @@ import sys
|
||||
import subprocess
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import shlex
|
||||
import re
|
||||
import struct
|
||||
import socket
|
||||
import enum
|
||||
from . import source_info
|
||||
from . import json_wrapper
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
@@ -190,7 +190,7 @@ def verify_source(
|
||||
if not rfile.exists():
|
||||
return None
|
||||
try:
|
||||
rinfo = json.loads(rfile.read_text())
|
||||
rinfo = json_wrapper.loads(rfile.read_text())
|
||||
except Exception:
|
||||
return None
|
||||
orig_chksum = rinfo['source_checksum']
|
||||
|
33
moonraker/utils/json_wrapper.py
Normal file
33
moonraker/utils/json_wrapper.py
Normal file
@@ -0,0 +1,33 @@
|
||||
# Wrapper for msgspec with stdlib fallback
|
||||
#
|
||||
# Copyright (C) 2023 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license
|
||||
|
||||
from __future__ import annotations
|
||||
import os
|
||||
import contextlib
|
||||
from typing import Any, Union, TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
def dumps(obj: Any) -> bytes: ... # type: ignore
|
||||
def loads(data: Union[str, bytes, bytearray]) -> Any: ...
|
||||
|
||||
MSGSPEC_ENABLED = False
|
||||
_msgspc_var = os.getenv("MOONRAKER_ENABLE_MSGSPEC", "y").lower()
|
||||
if _msgspc_var in ["y", "yes", "true"]:
|
||||
with contextlib.suppress(ImportError):
|
||||
import msgspec
|
||||
from msgspec import DecodeError as JSONDecodeError
|
||||
encoder = msgspec.json.Encoder()
|
||||
decoder = msgspec.json.Decoder()
|
||||
dumps = encoder.encode
|
||||
loads = decoder.decode
|
||||
MSGSPEC_ENABLED = True
|
||||
if not MSGSPEC_ENABLED:
|
||||
import json
|
||||
from json import JSONDecodeError # type: ignore
|
||||
loads = json.loads # type: ignore
|
||||
|
||||
def dumps(obj) -> bytes: # type: ignore
|
||||
return json.dumps(obj).encode("utf-8")
|
Reference in New Issue
Block a user