Skip to content

Commit

Permalink
python way format
Browse files Browse the repository at this point in the history
  • Loading branch information
ondratu committed Nov 14, 2023
1 parent 17f993d commit 84902c8
Show file tree
Hide file tree
Showing 8 changed files with 185 additions and 59 deletions.
4 changes: 2 additions & 2 deletions deps/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ if (APPLE)
# This ensures dependencies don't use SDK features which are not available in the version specified by Deployment target
# That can happen when one uses a recent SDK but specifies an older Deployment target
set(DEP_WERRORS_SDK "-Werror=partial-availability -Werror=unguarded-availability -Werror=unguarded-availability-new")

set(DEP_CMAKE_OPTS
"-DCMAKE_POSITION_INDEPENDENT_CODE=ON"
"-DCMAKE_OSX_SYSROOT=${CMAKE_OSX_SYSROOT}"
Expand All @@ -49,7 +49,7 @@ option(${PROJECT_NAME}_BUILD_ALL "Choose all external projects to be built." OFF

find_package(Git REQUIRED)

# The default command line for patching. Only works for newer
# The default command line for patching. Only works for newer
set(PATCH_CMD ${GIT_EXECUTABLE} apply --verbose --ignore-space-change --whitespace=fix)

foreach (pkg ${supported_packages})
Expand Down
2 changes: 2 additions & 0 deletions pybgcode/.pylintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[MASTER]
unsafe-load-any-extension=y
4 changes: 3 additions & 1 deletion pybgcode/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,9 @@ configure_file(${TEST_DATA_DIR}/mini_cube_b_ref.gcode ${CMAKE_CURRENT_BINARY_DIR
file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/pybgcode DESTINATION ${CMAKE_CURRENT_BINARY_DIR})

# Define the test for ctest and inject the correct PYTHONPATH env var for its runtime
add_test(NAME test_pybgcode COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_convert.py CONFIGURATIONS ${CMAKE_CONFIGURATION_TYPES})
add_test(NAME test_pybgcode
COMMAND ${Python3_EXECUTABLE} -m pytest -v ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_convert.py
CONFIGURATIONS ${CMAKE_CONFIGURATION_TYPES})
#$<TARGET_FILE_DIR:_bgcode>:
set_property(TEST test_pybgcode PROPERTY ENVIRONMENT PYTHONPATH=${CMAKE_CURRENT_BINARY_DIR})

Expand Down
82 changes: 79 additions & 3 deletions pybgcode/pybgcode/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,80 @@
from ._bgcode import *

"""Prusa Block & Binary G-code reader / writer / converter"""
__version__ = _bgcode.version()
# pylint: disable=redefined-builtin
from ._bgcode import ( # type: ignore
BlockHeader,
CompressionType,
EBlockType,
EResult,
EThumbnailFormat,
FileHeader,
FILEWrapper,
ThumbnailBlock,
close,
from_ascii_to_binary,
from_binary_to_ascii,
get_config,
is_open,
open,
read_header,
read_next_block_header,
rewind,
translate_result,
version,
)

__version__ = version()

__all__ = [
"BlockHeader",
"CompressionType",
"EBlockType",
"EResult",
"EThumbnailFormat",
"FileHeader",
"ThumbnailBlock",
"close",
"from_ascii_to_binary",
"from_binary_to_ascii",
"get_config",
"is_open",
"open",
"read_header",
"read_next_block_header",
"rewind",
"translate_result"]


class ResultError(Exception):
"""Exception based on EResult."""

def __init__(self, res: EResult):
super().__init__(translate_result(res))


def read_thumbnails(gcodefile: FILEWrapper):
"""Read thumbnails from binary gcode file."""
assert is_open(gcodefile)
rewind(gcodefile)

header = FileHeader()
res = read_header(gcodefile, header)
if res != EResult.Success:
raise ResultError(res)

block = BlockHeader()
thumbnails = []
while res == EResult.Success:
res = read_next_block_header(gcodefile, header, block,
EBlockType.Thumbnail)
if res != EResult.Success:
break

thumbnail_block = ThumbnailBlock()
res = thumbnail_block.read_data(gcodefile, header, block)
if res != EResult.Success:
raise ResultError(res)

thumbnails.append({"meta": thumbnail_block.params,
"bytes": thumbnail_block.data()})

return thumbnails
54 changes: 54 additions & 0 deletions pybgcode/ruff.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
select = [
"F", # pyflakes
"E", # pycodestyle
"W", # pycodestyle
"C90", # mccabe
"I", # isort
"N", # pep8-naming
# "D", # pydocstyle
# "UP", # pyupgrade
"YTT", # flake8-2020
# "ANN", # flake8-annotations
"S", # flake8-bandit
"BLE", # flake8-blind-except
# "FBT", # flake8-boolean-trap
"B", # flake8-bugbear
"A", # flake8-builtins
"COM", # flake8-commas
"C4", # flake8-comprehensions
# "DTZ", # flake8-datetimez
"T10", # flake8-debugger
"DJ", # flake8-django
# "EM", # flake8-errmsg
"EXE", # flake8-executable
"ISC", # flake8-implicit-str-concat
"ICN", # flake8-import-conventions
"G", # flake8-logging-format
"INP", # flake8-no-pep420
"PIE", # flake8-pie
"T20", # flake8-print
"PYI", # flake8-pyi
"PT", # flake8-pytest-style
"Q", # flake8-quotes
"RSE", # flake8-raise
"RET", # flake8-return
"SLF", # flake8-self
"SIM", # flake8-simplify
# "TID", # flake8-tidy-imports
"TCH", # flake8-type-checking
"INT", # flake8-gettext
"ARG", # flake8-unused-arguments
# "PTH", # flake8-use-pathlib
"ERA", # eradicate
"PD", # pandas-vet
"PGH", # pygrep-hooks
"PL", # Pylint
"TRY", # tryceratops
"FLY", # flynt
"NPY", # NumPy-specific rules
"RUF", # Ruff-specific rules
]
ignore = [
"PGH003", # Use specific rule codes when ignoring type issues
"S101", # Use of `assert` detected
]
Empty file added pybgcode/tests/__init__.py
Empty file.
96 changes: 44 additions & 52 deletions pybgcode/tests/test_convert.py
Original file line number Diff line number Diff line change
@@ -1,86 +1,78 @@
import pybgcode
"""Convert test functions."""
import filecmp
import io

import pytest

import pybgcode
from pybgcode import (
EResult,
EThumbnailFormat,
read_thumbnails,
)

# pylint: disable=missing-function-docstring
TEST_GCODE = "test.gcode"
TEST_REVERSE_GCODE = "test_reverse.gcode"
TEST_BGCODE = "test.bgcode"
TEST_THUMBNAILS = 2


def get_thumbnail_extension(format_id):
ret = "unknown"
if format_id == int(pybgcode.EThumbnailFormat.PNG):
if format_id == int(EThumbnailFormat.PNG):
ret = "png"
elif format_id == int(pybgcode.EThumbnailFormat.JPG):
elif format_id == int(EThumbnailFormat.JPG):
ret = "jpg"
elif format_id == int(pybgcode.EThumbnailFormat.QOI):
elif format_id == int(EThumbnailFormat.QOI):
ret = "qoi"

return ret

def read_thumbnails(gcodefile):
assert(pybgcode.is_open(gcodefile))
pybgcode.rewind(gcodefile)

header = pybgcode.FileHeader()
res = pybgcode.read_header(gcodefile, header)
if res != pybgcode.EResult.Success:
raise Exception(pybgcode.translate_result(res))

block = pybgcode.BlockHeader()
thumbnails = []
while res == pybgcode.EResult.Success:
res = pybgcode.read_next_block_header(gcodefile, header, block, pybgcode.EBlockType.Thumbnail)
if res != pybgcode.EResult.Success:
break

thumbnail_block = pybgcode.ThumbnailBlock()
res = thumbnail_block.read_data(gcodefile, header, block)
if res != pybgcode.EResult.Success:
raise Exception(pybgcode.translate_result(res))

thumbnails.append({"meta": thumbnail_block.params, "bytes": thumbnail_block.data()})

return thumbnails


def test_main():
assert(pybgcode.__version__ == pybgcode.version())
assert pybgcode.__version__ == pybgcode.version()

in_f = pybgcode.open("test.gcode", "r");
out_f = pybgcode.open("test.bgcode", "wb");
in_f = pybgcode.open(TEST_GCODE, "r")
out_f = pybgcode.open(TEST_BGCODE, "wb")

assert(in_f)
assert(out_f)
assert in_f
assert out_f

assert(pybgcode.is_open(in_f))
assert(pybgcode.is_open(out_f))
assert pybgcode.is_open(in_f)
assert pybgcode.is_open(out_f)

cfg = pybgcode.get_config();
cfg = pybgcode.get_config()
cfg.compression.file_metadata = pybgcode.CompressionType.Heatshrink_11_4
res = pybgcode.from_ascii_to_binary(in_f, out_f, cfg);
res = pybgcode.from_ascii_to_binary(in_f, out_f, cfg)

assert(res == pybgcode.EResult.Success)
assert res == EResult.Success

pybgcode.close(out_f)
pybgcode.close(in_f)

thumb_f = pybgcode.open("test.bgcode", "rb")
thumb_f = pybgcode.open(TEST_BGCODE, "rb")
thumbnails = read_thumbnails(thumb_f)
assert(len(thumbnails) == 2)
assert len(thumbnails) == TEST_THUMBNAILS
pybgcode.close(thumb_f)

# write thumbnails to png files
thumcnt = 0;
thumcnt = 0
for thumb in thumbnails:
with open("thumb" + str(thumcnt) + "." + get_thumbnail_extension(thumb["meta"].format), "wb") as outpng:
outpng.write(thumb["bytes"])
with open("thumb" + str(thumcnt) + "." +
get_thumbnail_extension(thumb["meta"].format), "wb") as out:
out.write(thumb["bytes"])
thumcnt = thumcnt + 1

in_f = pybgcode.open("test.bgcode", "rb");
out_f = pybgcode.open("test_reverse.gcode", "w");
in_f = pybgcode.open(TEST_BGCODE, "rb")
out_f = pybgcode.open(TEST_REVERSE_GCODE, "w")

res = pybgcode.from_binary_to_ascii(in_f, out_f, True)
assert(res == pybgcode.EResult.Success)
assert res == EResult.Success

pybgcode.close(out_f)

assert(filecmp.cmp("test.gcode", "test_reverse.gcode", shallow=False))
assert filecmp.cmp(TEST_GCODE, TEST_REVERSE_GCODE, shallow=False)


if __name__ == '__main__':
test_main()
if __name__ == "__main__":
pytest.main()
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ requires-python = ">=3.7"
"Bug Tracker" = "https://github.com/prusa3d/libbgcode/issues"

[build-system]
requires = ["py-build-cmake~=0.1.8"]
requires = ["py-build-cmake~=0.1.8", "pytest"]
build-backend = "py_build_cmake.build"

[tool.py-build-cmake.module] # Where to find the Python module to package
Expand Down

0 comments on commit 84902c8

Please sign in to comment.