Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

1.0.alpha 13 #358

Merged
merged 70 commits into from
Oct 4, 2024
Merged

1.0.alpha 13 #358

merged 70 commits into from
Oct 4, 2024

Conversation

cleder
Copy link
Owner

@cleder cleder commented Oct 4, 2024

workerB


Important

Enhance test coverage for fastkml library by adding and updating tests for geometry, styles, and KML parsing.

  • Geometry Tests:
    • Add tests for OuterBoundaryIs and InnerBoundaryIs in boundaries_test.py.
    • Add tests for Coordinates handling whitespace in coordinates_test.py.
    • Add tests for various geometry classes like Point, LineString, Polygon in geometry_test.py.
  • Polygon Tests:
    • Add tests for polygons with and without inner boundaries in polygon_test.py.
  • KML Tests:
    • Add tests for KML parsing from files and strings in kml_test.py.
  • Repr and Equality Tests:
    • Add tests for __repr__ and __eq__ methods in repr_eq_test.py.
  • Style Tests:
    • Add tests for style serialization and deserialization in styles_test.py.

This description was created by Ellipsis for 3ecc272. It will automatically update as commits are pushed.

Summary by Sourcery

Enhance the codebase with improved documentation, refactorings for better namespace handling, and expanded test coverage. Update dependencies and pre-commit hooks to their latest versions.

Enhancements:

  • Add detailed docstrings to various classes and methods across the codebase to improve code documentation and clarity.
  • Refactor the KML class to include a parse method for parsing KML files from different input types, enhancing flexibility.
  • Update the __repr__ and __eq__ methods for several classes to ensure accurate string representation and equality checks.
  • Improve the handling of XML namespaces by introducing _default_nsid and updating namespace management logic.
  • Enhance the test suite with additional tests for parsing KML files and verifying the __repr__ and __eq__ methods.

Tests:

  • Add tests for parsing KML files from different input types, including file paths and file-like objects.
  • Introduce tests for the __repr__ and __eq__ methods to ensure accurate object representation and equality checks.
  • Add tests for handling whitespace in coordinate strings to ensure robust parsing.

Chores:

  • Update pre-commit hooks and dependencies to their latest versions for improved code quality and consistency.
  • Add a _typos.toml configuration file to manage custom dictionary entries for typo checks.

Summary by CodeRabbit

  • New Features

    • Enhanced testing coverage by including additional Python versions in the testing matrix.
    • Added a new repository for typo checking in the configuration.
  • Documentation

    • Updated README.rst for terminology consistency and clarified attribute assignments.
    • Restructured docs/contributing.rst to improve clarity on setting up the development environment.
    • Updated docs/HISTORY.rst to reflect significant project changes and version updates.
  • Bug Fixes

    • Corrected the version number of the fastkml package.
  • Refactor

    • Improved documentation within several classes and methods for better clarity and understanding.

cleder and others added 30 commits June 20, 2024 00:30
updates:
- [github.com/astral-sh/ruff-pre-commit: v0.4.9 → v0.4.10](astral-sh/ruff-pre-commit@v0.4.9...v0.4.10)
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/astral-sh/ruff-pre-commit: v0.4.10 → v0.5.0](astral-sh/ruff-pre-commit@v0.4.10...v0.5.0)
- [github.com/pre-commit/mirrors-mypy: v1.10.0 → v1.10.1](pre-commit/mirrors-mypy@v1.10.0...v1.10.1)
- [github.com/adamchainz/blacken-docs: 1.16.0 → 1.18.0](adamchainz/blacken-docs@1.16.0...1.18.0)
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/astral-sh/ruff-pre-commit: v0.5.0 → v0.5.1](astral-sh/ruff-pre-commit@v0.5.0...v0.5.1)
- [github.com/rstcheck/rstcheck: v6.2.0 → v6.2.4](rstcheck/rstcheck@v6.2.0...v6.2.4)
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/astral-sh/ruff-pre-commit: v0.5.1 → v0.5.2](astral-sh/ruff-pre-commit@v0.5.1...v0.5.2)
[pre-commit.ci] pre-commit autoupdate
Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
…st-usage-guide-is-broken-for-version-1x

add docstrings and fixes for ruff
updates:
- [github.com/astral-sh/ruff-pre-commit: v0.5.2 → v0.5.4](astral-sh/ruff-pre-commit@v0.5.2...v0.5.4)
- [github.com/pre-commit/mirrors-mypy: v1.10.1 → v1.11.0](pre-commit/mirrors-mypy@v1.10.1...v1.11.0)
[pre-commit.ci] pre-commit autoupdate
cleder and others added 16 commits September 22, 2024 01:05
Refactor KML class and related styles and geometries

This commit refactors the KML class in the fastkml module. The `_features` attribute has been renamed to `features` to follow naming conventions.

In the styles module, the `LineStyle` and `PolyStyle` classes have been modified. The `__bool__` method in `LineStyle` now checks for the presence of `width`, `color`, and `color_mode` attributes. Similarly, the `__bool__` method in `PolyStyle` now checks for the presence of `fill`, `outline`, `color`, and `color_mode` attributes.

The coordinates_test module in the tests directory has been updated with a new test case. The `test_coordinates_from_string_with_whitespace` method tests the `from_string` method with whitespace.

Lastly, the geometry module has been modified. The `OuterBoundaryIs` and `InnerBoundaryIs` classes now have `__repr__` methods to provide a string representation of the objects.
updates:
- [github.com/astral-sh/ruff-pre-commit: v0.6.5 → v0.6.7](astral-sh/ruff-pre-commit@v0.6.5...v0.6.7)
[pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/abravalheri/validate-pyproject: v0.19 → v0.20.2](abravalheri/validate-pyproject@v0.19...v0.20.2)
- [github.com/astral-sh/ruff-pre-commit: v0.6.7 → v0.6.8](astral-sh/ruff-pre-commit@v0.6.7...v0.6.8)
[pre-commit.ci] pre-commit autoupdate
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
Copy link

semanticdiff-com bot commented Oct 4, 2024

Review changes with SemanticDiff.

Analyzed 31 of 38 files.

Overall, the semantic diff is 4% smaller than the GitHub diff.

File Information
Filename Status
.pre-commit-config.yaml Unsupported file format
README.rst Unsupported file format
_typos.toml Unsupported file format
pyproject.toml Unsupported file format
✔️ tests/atom_test.py Analyzed
✔️ tests/base_test.py 5.82% smaller
✔️ tests/config_test.py 2.08% smaller
✔️ tests/kml_test.py 3.37% smaller
✔️ tests/registry_test.py Analyzed
✔️ tests/repr_eq_test.py Analyzed
✔️ tests/styles_test.py Analyzed
✔️ tests/geometries/boundaries_test.py 30.71% smaller
✔️ tests/geometries/coordinates_test.py Analyzed
✔️ tests/geometries/geometry_test.py 9.26% smaller
✔️ tests/geometries/polygon_test.py 38.85% smaller
✔️ fastkml/about.py Analyzed
✔️ fastkml/atom.py 6.94% smaller
✔️ fastkml/base.py 3.9% smaller
✔️ fastkml/config.py Analyzed
✔️ fastkml/containers.py 18.53% smaller
✔️ fastkml/data.py 0.43% smaller
✔️ fastkml/enums.py 33.53% smaller
✔️ fastkml/features.py 3.74% smaller
✔️ fastkml/geometry.py 14.89% smaller
✔️ fastkml/gx.py 0.06% smaller
✔️ fastkml/helpers.py 8.64% smaller
✔️ fastkml/kml.py 5.65% smaller
✔️ fastkml/kml_base.py Analyzed
✔️ fastkml/links.py Analyzed
✔️ fastkml/mixins.py Analyzed
✔️ fastkml/overlays.py 0.12% smaller
✔️ fastkml/registry.py 76.06% smaller
✔️ fastkml/styles.py 2.78% smaller
✔️ fastkml/times.py 0.81% smaller
✔️ fastkml/views.py 3.77% smaller
docs/HISTORY.rst Unsupported file format
docs/contributing.rst Unsupported file format
.github/workflows/run-all-tests.yml Unsupported file format

Copy link
Contributor

sourcery-ai bot commented Oct 4, 2024

Reviewer's Guide by Sourcery

This pull request implements several improvements and updates to the fastkml library. The changes focus on code quality, performance enhancements, and adherence to best practices. Key modifications include updating namespace handling, improving type hinting, enhancing documentation, and refactoring various components for better maintainability and functionality.

Updated class diagram for fastkml.geometry module

classDiagram
    class Coordinates {
        -_default_nsid: config.KML
        -coords: LineType
        +__init__(ns: Optional[str], name_spaces: Optional[Dict[str, str]], coords: Optional[LineType], **kwargs: Any) -> None
        +__bool__() bool
    }
    class OuterBoundaryIs {
        -_default_nsid: config.KML
        -kml_geometry: Optional[LinearRing]
        +__init__(ns: Optional[str], name_spaces: Optional[Dict[str, str]], geometry: Optional[geo.LinearRing], kml_geometry: Optional[LinearRing], **kwargs: Any) -> None
        +__bool__() bool
        +geometry() Optional[geo.LinearRing]
    }
    class InnerBoundaryIs {
        -_default_nsid: config.KML
        -kml_geometry: Optional[LinearRing]
        +__init__(ns: Optional[str], name_spaces: Optional[Dict[str, str]], geometry: Optional[geo.LinearRing], kml_geometry: Optional[LinearRing], **kwargs: Any) -> None
        +__bool__() bool
        +geometry() Optional[geo.LinearRing]
    }
    class Polygon {
        -outer_boundary: Optional[OuterBoundaryIs]
        -inner_boundaries: List[InnerBoundaryIs]
        +__init__(ns: Optional[str], name_spaces: Optional[Dict[str, str]], id: Optional[str], target_id: Optional[str], extrude: Optional[bool], tessellate: Optional[bool], altitude_mode: Optional[AltitudeMode], outer_boundary: Optional[OuterBoundaryIs], inner_boundaries: Optional[Iterable[InnerBoundaryIs]], geometry: Optional[geo.Polygon], **kwargs: Any) -> None
        +__bool__() bool
        +geometry() Optional[geo.Polygon]
    }
Loading

Updated class diagram for fastkml.styles module

classDiagram
    class Style {
        +__init__(ns: Optional[str], name_spaces: Optional[Dict[str, str]], id: Optional[str], target_id: Optional[str], url: Optional[str], **kwargs: Any) -> None
        +__bool__() bool
    }
    class _ColorStyle {
        +__init__(ns: Optional[str], name_spaces: Optional[Dict[str, str]], id: Optional[str], target_id: Optional[str], color: Optional[str], color_mode: Optional[ColorMode], **kwargs: Any) -> None
    }
    class HotSpot {
        -_default_nsid: config.KML
        +__init__(ns: Optional[str], name_spaces: Optional[Dict[str, str]], x: Optional[float], y: Optional[float], xunits: Optional[Units], yunits: Optional[Units], **kwargs: Any) -> None
        +__bool__() bool
    }
Loading

Updated class diagram for fastkml.features module

classDiagram
    class _Feature {
        +__init__(ns: Optional[str], name_spaces: Optional[Dict[str, str]], id: Optional[str], target_id: Optional[str], name: Optional[str], visibility: Optional[bool], isopen: Optional[bool], atom_link: Optional[atom.Link], atom_author: Optional[atom.Author], address: Optional[str], phone_number: Optional[str], snippet: Optional[Snippet], description: Optional[str], view: Optional[Union[Camera, LookAt]], times: Optional[Union[TimeSpan, TimeStamp]], style_url: Optional[StyleUrl], styles: Optional[Iterable[Union[Style, StyleMap]]], region: Optional[Region], extended_data: Optional[ExtendedData], **kwargs: Any) -> None
    }
    class Placemark {
        +__init__(ns: Optional[str], name_spaces: Optional[Dict[str, str]], id: Optional[str], target_id: Optional[str], name: Optional[str], visibility: Optional[bool], isopen: Optional[bool], atom_link: Optional[atom.Link], atom_author: Optional[atom.Author], address: Optional[str], phone_number: Optional[str], snippet: Optional[Snippet], description: Optional[str], view: Optional[Union[Camera, LookAt]], times: Optional[Union[TimeSpan, TimeStamp]], style_url: Optional[StyleUrl], styles: Optional[Iterable[Union[Style, StyleMap]]], region: Optional[Region], extended_data: Optional[ExtendedData], kml_geometry: KmlGeometry, geometry: Optional[Union[GeoType, GeoCollectionType]], **kwargs: Any) -> None
        +geometry() Optional[AnyGeometryType]
    }
Loading

File-Level Changes

Change Details Files
Updated namespace handling and improved type hinting
  • Changed _default_ns to _default_nsid in multiple classes
  • Updated namespace-related code to use the new _default_nsid attribute
  • Improved type hinting throughout the codebase
  • Refactored namespace-related methods for better consistency
fastkml/base.py
fastkml/kml_base.py
fastkml/geometry.py
fastkml/styles.py
fastkml/overlays.py
fastkml/views.py
fastkml/gx.py
Enhanced documentation and code comments
  • Added or improved docstrings for classes and methods
  • Updated comments to provide more context and explanations
  • Improved type annotations in function signatures
fastkml/geometry.py
fastkml/styles.py
fastkml/overlays.py
fastkml/views.py
fastkml/gx.py
fastkml/data.py
fastkml/features.py
fastkml/containers.py
Refactored and optimized various components
  • Simplified and improved the implementation of several methods
  • Updated class structures for better consistency and maintainability
  • Optimized performance-critical sections of the code
fastkml/geometry.py
fastkml/styles.py
fastkml/overlays.py
fastkml/views.py
fastkml/gx.py
fastkml/data.py
fastkml/features.py
fastkml/containers.py
fastkml/kml.py
Updated testing infrastructure and added new tests
  • Added new test cases to improve code coverage
  • Updated existing tests to reflect changes in the library
  • Improved test infrastructure for better maintainability
tests/geometries/boundaries_test.py
tests/styles_test.py
tests/geometries/geometry_test.py
tests/geometries/coordinates_test.py
tests/geometries/polygon_test.py
tests/atom_test.py
tests/repr_eq_test.py
Updated dependencies and development tools
  • Updated pre-commit hooks and their configurations
  • Added support for newer Python versions in CI workflows
  • Updated dependencies in pyproject.toml
.pre-commit-config.yaml
.github/workflows/run-all-tests.yml
pyproject.toml

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Contributor

coderabbitai bot commented Oct 4, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The pull request introduces several updates across multiple files, including modifications to the testing workflow to support additional Python versions and adjustments to dependency installations. The .pre-commit-config.yaml file has been updated with new versions for various hooks and added a new repository for typo checking. Documentation files, including README.rst and docs/contributing.rst, have been enhanced for clarity and accuracy. Additionally, changes in the fastkml package involve updates to versioning, class attributes, and method documentation, improving overall code clarity and structure.

Changes

File Change Summary
.github/workflows/run-all-tests.yml Updated testing matrix to include Python versions 3.14-dev and 3.13-dev. Modified installation command to include tests and updated mypy command.
.pre-commit-config.yaml Updated versions for multiple hooks and added a new typos hook repository.
README.rst Corrected "Tesselate" to "Tessellate" and clarified attribute assignments for Geometry collections.
_typos.toml Added [default.extend-words] section with entries for lod and Lod, and specified extend-exclude for KML files.
docs/HISTORY.rst Updated changelog for version 1.0, documenting significant changes and previous versions.
docs/contributing.rst Restructured content with new section for environment setup, expanded instructions for virtual environment, and clarified test running commands.
fastkml/about.py Updated package version from "1.0.a12" to "1.0.a13".
fastkml/atom.py Renamed _default_ns to _default_nsid, enhanced documentation for Link and _Person classes, and modified registry registration for namespaces.
fastkml/base.py Renamed _default_ns to _default_nsid, expanded docstrings for multiple methods, and updated equality comparison logic.
fastkml/config.py Added etree variable to __all__ for export in the module.
fastkml/containers.py Enhanced docstrings for _Container, Folder, and Document classes, clarifying their purposes and functionalities.

Possibly related PRs

Suggested labels

Configuration changes, Review effort [1-5]: 3

🐰 In the garden of code, we hop with glee,
New versions and fixes, as bright as can be!
With tests and hooks, our workflow's a charm,
Together we build, with no hint of harm.
So let’s celebrate, with a joyful cheer,
For every small change, brings us all near! 🌼


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@pep8speaks
Copy link

Hello @cleder! Thanks for opening this PR. We checked the lines you've touched for PEP 8 issues, and found:

Line 107:90: E501 line too long (134 > 89 characters)
Line 152:90: E501 line too long (134 > 89 characters)
Line 197:90: E501 line too long (126 > 89 characters)
Line 393:90: E501 line too long (165 > 89 characters)
Line 399:90: E501 line too long (90 > 89 characters)
Line 401:90: E501 line too long (92 > 89 characters)
Line 413:90: E501 line too long (90 > 89 characters)
Line 415:90: E501 line too long (92 > 89 characters)
Line 420:90: E501 line too long (90 > 89 characters)
Line 424:90: E501 line too long (94 > 89 characters)
Line 425:90: E501 line too long (92 > 89 characters)
Line 426:90: E501 line too long (96 > 89 characters)
Line 457:90: E501 line too long (90 > 89 characters)
Line 459:90: E501 line too long (92 > 89 characters)
Line 471:90: E501 line too long (90 > 89 characters)
Line 473:90: E501 line too long (92 > 89 characters)
Line 480:90: E501 line too long (92 > 89 characters)
Line 483:90: E501 line too long (94 > 89 characters)
Line 484:90: E501 line too long (92 > 89 characters)
Line 485:90: E501 line too long (96 > 89 characters)
Line 488:90: E501 line too long (90 > 89 characters)
Line 490:90: E501 line too long (98 > 89 characters)
Line 491:90: E501 line too long (96 > 89 characters)
Line 492:90: E501 line too long (100 > 89 characters)
Line 555:90: E501 line too long (90 > 89 characters)
Line 557:90: E501 line too long (92 > 89 characters)
Line 569:90: E501 line too long (90 > 89 characters)
Line 571:90: E501 line too long (92 > 89 characters)
Line 578:90: E501 line too long (92 > 89 characters)
Line 581:90: E501 line too long (94 > 89 characters)
Line 582:90: E501 line too long (92 > 89 characters)
Line 583:90: E501 line too long (96 > 89 characters)
Line 586:90: E501 line too long (90 > 89 characters)
Line 588:90: E501 line too long (98 > 89 characters)
Line 589:90: E501 line too long (96 > 89 characters)
Line 590:90: E501 line too long (100 > 89 characters)
Line 653:90: E501 line too long (90 > 89 characters)
Line 655:90: E501 line too long (92 > 89 characters)
Line 667:90: E501 line too long (90 > 89 characters)
Line 669:90: E501 line too long (92 > 89 characters)
Line 676:90: E501 line too long (92 > 89 characters)
Line 679:90: E501 line too long (94 > 89 characters)
Line 680:90: E501 line too long (92 > 89 characters)
Line 681:90: E501 line too long (96 > 89 characters)
Line 684:90: E501 line too long (90 > 89 characters)
Line 686:90: E501 line too long (98 > 89 characters)
Line 687:90: E501 line too long (96 > 89 characters)
Line 688:90: E501 line too long (100 > 89 characters)
Line 896:90: E501 line too long (90 > 89 characters)
Line 898:90: E501 line too long (92 > 89 characters)
Line 910:90: E501 line too long (90 > 89 characters)
Line 912:90: E501 line too long (92 > 89 characters)
Line 919:90: E501 line too long (92 > 89 characters)
Line 922:90: E501 line too long (94 > 89 characters)
Line 923:90: E501 line too long (92 > 89 characters)
Line 924:90: E501 line too long (96 > 89 characters)
Line 927:90: E501 line too long (90 > 89 characters)
Line 929:90: E501 line too long (98 > 89 characters)
Line 930:90: E501 line too long (96 > 89 characters)
Line 931:90: E501 line too long (100 > 89 characters)
Line 1006:90: E501 line too long (90 > 89 characters)
Line 1008:90: E501 line too long (98 > 89 characters)
Line 1009:90: E501 line too long (96 > 89 characters)
Line 1010:90: E501 line too long (100 > 89 characters)
Line 1012:90: E501 line too long (93 > 89 characters)
Line 1013:90: E501 line too long (94 > 89 characters)
Line 1015:90: E501 line too long (102 > 89 characters)
Line 1016:90: E501 line too long (100 > 89 characters)
Line 1017:90: E501 line too long (104 > 89 characters)
Line 1412:90: E501 line too long (718 > 89 characters)
Line 1471:90: E501 line too long (251 > 89 characters)
Line 1516:90: E501 line too long (90 > 89 characters)
Line 1518:90: E501 line too long (92 > 89 characters)
Line 1524:90: E501 line too long (90 > 89 characters)
Line 1526:90: E501 line too long (98 > 89 characters)
Line 1527:90: E501 line too long (96 > 89 characters)
Line 1528:90: E501 line too long (100 > 89 characters)
Line 1537:90: E501 line too long (94 > 89 characters)
Line 1539:90: E501 line too long (102 > 89 characters)
Line 1540:90: E501 line too long (100 > 89 characters)
Line 1541:90: E501 line too long (104 > 89 characters)
Line 1545:90: E501 line too long (113 > 89 characters)
Line 1572:90: E501 line too long (90 > 89 characters)
Line 1574:90: E501 line too long (92 > 89 characters)
Line 1580:90: E501 line too long (90 > 89 characters)
Line 1582:90: E501 line too long (98 > 89 characters)
Line 1583:90: E501 line too long (96 > 89 characters)
Line 1584:90: E501 line too long (100 > 89 characters)
Line 1593:90: E501 line too long (94 > 89 characters)
Line 1595:90: E501 line too long (102 > 89 characters)
Line 1596:90: E501 line too long (100 > 89 characters)
Line 1597:90: E501 line too long (104 > 89 characters)
Line 1601:90: E501 line too long (113 > 89 characters)
Line 1796:90: E501 line too long (377 > 89 characters)
Line 1908:90: E501 line too long (441 > 89 characters)

Copy link

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

New Test File
A new test file 'repr_eq_test.py' has been added with extensive tests for repr and eq methods. This file needs thorough review to ensure all test cases are appropriate and cover all necessary scenarios.

Code Refactoring
Significant refactoring in the geometry.py file, including changes to class structures, method implementations, and docstring updates. These changes need careful review to ensure they maintain or improve existing functionality.

Type Annotations
Several type annotations have been added or modified throughout the geometry.py file. These should be reviewed for correctness and consistency with the rest of the codebase.

Copy link

what-the-diff bot commented Oct 4, 2024

PR Summary

  • Updated Python Version Support in CI
    Now, our Continuous Integration (CI) environment will also test the software with the '3.14-dev' version of Python, making our software more future-proof and compatible with upcoming Python releases.

  • Enhanced Dependencies Installation
    We refined the command used to install software dependencies, to include packages required for local testing and development.

  • Type Checking Includes Test Directory
    To make sure our tests have no type inconsistencies, our tool for type checking, mypy, now also includes the 'tests' directory.

  • Upgraded Pre-commit Hook Dependencies
    Several tools used for automated checks before committing the code have been upgraded to their newer versions, offering us updated features, improved performances, and fixed bugs.

  • New Pre-commit Hook for Typos
    To avoid spelling mistakes in our code, a new automated check specifically for typos has been added.

  • Typo Correction in README file
    Our README file, which supports new contributors to understand the project, had typographical errors that are now fixed.

  • Added Word Definitions
    A '_typos.toml' file has been created to list specific words that our newly added typo-checking tool should consider as correct.

  • Version Number Advance
    The version number of our software has been updated in response to these changes.

  • Docstring Improvement in atom.py
    There has been an increase in the clarity and richness of the descriptions for different parts of our code in the 'atom.py' file.

  • Added Parameters Description in Link and _Person classes
    To help understand the usage of the Link and _Person classes, more detailed descriptions of their parameters have been added.

  • Improvements to _XMLObject Class and containers.py File
    Changes in names and structuring have been made for better understanding of the _XMLObject class functions, plus a boost in the documentation quality of several parts of the containers.py file.

  • Documentation, Comments and Representation Updates Across classes
    Several classes' and methods' documentation has been made more clear, useful comments have been added, the way data objects are represented for humans has been made more understandable and standardized.

  • Improvements in In-code Comments and Docstrings
    Apart from typo corrections and clarity improvements, type hints have also been added to suppress possible linting errors.

  • Updates to pyproject.toml Configurations
    Updates have been made to define how linters should ignore specific files and patterns, providing a smoother development experience.

  • Tests
    A number of changes have been made in our tests, including typo corrections, updated import statements, better readability, adjusted assertions, expansion of KML parsing tests, updated handling of style icons and more.

Copy link

github-actions bot commented Oct 4, 2024

Preparing review...

1 similar comment
Copy link

github-actions bot commented Oct 4, 2024

Preparing review...

Copy link

github-actions bot commented Oct 4, 2024

Failed to generate code suggestions for PR

Copy link

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Score
Maintainability
Use constants for namespace URLs to improve maintainability and reduce redundancy

Consider using a constant or configuration file for the namespace URLs instead of
repeating them throughout the code. This would make it easier to update if the URLs
change and reduce the risk of typos.

tests/repr_eq_test.py [46-51]

-ns="{http://www.opengis.net/kml/2.2}",
-name_spaces={
-    "kml": "{http://www.opengis.net/kml/2.2}",
-    "atom": "{http://www.w3.org/2005/Atom}",
-    "gx": "{http://www.google.com/kml/ext/2.2}",
-},
+ns=KML_NAMESPACE,
+name_spaces=KML_NAMESPACES,
  • Apply this suggestion
Suggestion importance[1-10]: 7

Why:

7
Use constants or enums instead of magic numbers for coordinate dimensions

The coordinates_subelement function uses magic numbers (2 and 3) to check the length
of coordinates. Consider using constants or an enum to make the code more readable
and maintainable. This will also make it easier to add support for other coordinate
dimensions in the future if needed.

fastkml/geometry.py [162-165]

-if len(coords[0]) == 2:  # noqa: PLR2004
+from enum import IntEnum
+
+class CoordinateDimension(IntEnum):
+    TWO_D = 2
+    THREE_D = 3
+
+if len(coords[0]) == CoordinateDimension.TWO_D:
     tuples = (f"{c[0]:.{p}f},{c[1]:.{p}f}" for c in coords)
-elif len(coords[0]) == 3:  # noqa: PLR2004
+elif len(coords[0]) == CoordinateDimension.THREE_D:
     tuples = (f"{c[0]:.{p}f},{c[1]:.{p}f},{c[2]:.{p}f}" for c in coords)
  • Apply this suggestion
Suggestion importance[1-10]: 7

Why:

7
Enhancement
Use a builder pattern for creating complex KML objects to improve code readability and maintainability

Consider using a factory method or a builder pattern to create complex objects like
KML, Document, and Placemark. This would make the code more readable and easier to
maintain.

tests/repr_eq_test.py [45-119]

-clean_doc: Final = fastkml.kml.KML(
-    ns="{http://www.opengis.net/kml/2.2}",
-    name_spaces={
-        "kml": "{http://www.opengis.net/kml/2.2}",
-        "atom": "{http://www.w3.org/2005/Atom}",
-        "gx": "{http://www.google.com/kml/ext/2.2}",
-    },
-    features=[
-        fastkml.containers.Document(
-            ns="{http://www.opengis.net/kml/2.2}",
-            name_spaces={
-                "kml": "{http://www.opengis.net/kml/2.2}",
-                "atom": "{http://www.w3.org/2005/Atom}",
-                "gx": "{http://www.google.com/kml/ext/2.2}",
-            },
-            id="doc-001",
-            target_id="",
-            name="Vestibulum eleifend lobortis lorem.",
-            visibility=None,
-            isopen=None,
-            atom_link=None,
-            atom_author=None,
-            address=None,
-            phone_number=None,
-            snippet=None,
-            description=None,
-            view=None,
-            times=None,
-            style_url=None,
-            styles=[
-                fastkml.styles.Style(
-                    ns="{http://www.opengis.net/kml/2.2}",
-                    name_spaces={
-                        "kml": "{http://www.opengis.net/kml/2.2}",
-                        "atom": "{http://www.w3.org/2005/Atom}",
-                        "gx": "{http://www.google.com/kml/ext/2.2}",
-                    },
-                    id="style-001",
-                    target_id="",
-                    styles=[
-                        fastkml.styles.IconStyle(
-                            ns="{http://www.opengis.net/kml/2.2}",
-                            name_spaces={
-                                "kml": "{http://www.opengis.net/kml/2.2}",
-                                "atom": "{http://www.w3.org/2005/Atom}",
-                                "gx": "{http://www.google.com/kml/ext/2.2}",
-                            },
-                            id="",
-                            target_id="",
-                            color=None,
-                            color_mode=None,
-                            scale=None,
-                            heading=None,
-                            icon=fastkml.links.Icon(
-                                ns="{http://www.opengis.net/kml/2.2}",
-                                name_spaces={
-                                    "kml": "{http://www.opengis.net/kml/2.2}",
-                                    "atom": "{http://www.w3.org/2005/Atom}",
-                                    "gx": "{http://www.google.com/kml/ext/2.2}",
-                                },
-                                id="",
-                                target_id="",
-                                href="http://barcelona.galdos.local/svn1/sqa/ets-kml/main/test/data/ogc-kml/images/red-stars.png",
-                                refresh_mode=None,
-                                refresh_interval=None,
-                                view_refresh_mode=None,
-                                view_refresh_time=None,
-                                view_bound_scale=None,
-                                view_format=None,
-                                http_query=None,
-                            ),
-                            hot_spot=None,
-                        ),
-                    ],
-                ),
+clean_doc: Final = KMLBuilder.create_kml()
+    .add_document(
+        id="doc-001",
+        name="Vestibulum eleifend lobortis lorem.",
+        styles=[
+            StyleBuilder.create_style("style-001")
+                .add_icon_style(
+                    icon=IconBuilder.create_icon(
+                        href="http://barcelona.galdos.local/svn1/sqa/ets-kml/main/test/data/ogc-kml/images/red-stars.png"
+                    )
+                )
+                .build()
+        ]
+    )
+    .build()
  • Apply this suggestion
Suggestion importance[1-10]: 7

Why:

7
Use dataclasses to simplify KML-related class definitions and reduce boilerplate code

Consider using dataclasses or attrs library for creating the KML-related classes.
This would reduce boilerplate code and make the class definitions more concise and
less error-prone.

tests/repr_eq_test.py [44-75]

+@dataclass
+class KML:
+    ns: str
+    name_spaces: Dict[str, str]
+    features: List[Document]
+
+@dataclass
+class Document:
+    ns: str
+    name_spaces: Dict[str, str]
+    id: str
+    target_id: str
+    name: str
+    visibility: Optional[bool] = None
+    isopen: Optional[bool] = None
+    atom_link: Optional[str] = None
+    atom_author: Optional[str] = None
+    address: Optional[str] = None
+    phone_number: Optional[str] = None
+    snippet: Optional[str] = None
+    description: Optional[str] = None
+    view: Optional[Any] = None
+    times: Optional[Any] = None
+    style_url: Optional[str] = None
+    styles: List[Style] = field(default_factory=list)
+
 class TestRepr(StdLibrary):
-    clean_doc: Final = fastkml.kml.KML(
+    clean_doc: Final = KML(
         ns="{http://www.opengis.net/kml/2.2}",
         name_spaces={
             "kml": "{http://www.opengis.net/kml/2.2}",
             "atom": "{http://www.w3.org/2005/Atom}",
             "gx": "{http://www.google.com/kml/ext/2.2}",
         },
         features=[
-            fastkml.containers.Document(
+            Document(
                 ns="{http://www.opengis.net/kml/2.2}",
                 name_spaces={
                     "kml": "{http://www.opengis.net/kml/2.2}",
                     "atom": "{http://www.w3.org/2005/Atom}",
                     "gx": "{http://www.google.com/kml/ext/2.2}",
                 },
                 id="doc-001",
                 target_id="",
                 name="Vestibulum eleifend lobortis lorem.",
-                visibility=None,
-                isopen=None,
-                atom_link=None,
-                atom_author=None,
-                address=None,
-                phone_number=None,
-                snippet=None,
-                description=None,
-                view=None,
-                times=None,
-                style_url=None,
                 styles=[
  • Apply this suggestion
Suggestion importance[1-10]: 7

Why:

7
Use a more specific exception type for better error handling and clarity

Consider using a more specific exception type instead of Exception in the
handle_invalid_geometry_error function. This will make it easier to catch and handle
specific error cases. For example, you could create a custom exception like
InvalidGeometryError or use a built-in exception that better describes the error
condition.

fastkml/geometry.py [103-106]

+class InvalidGeometryError(Exception):
+    pass
+
 def handle_invalid_geometry_error(
-    error: Exception,
+    error: InvalidGeometryError,
     element: Element,
     strict: bool,
 ) -> None:
  • Apply this suggestion
Suggestion importance[1-10]: 7

Why:

7
Use a more descriptive name for the geometry property in the Polygon class

In the Polygon class, consider using a more descriptive name for the geometry
property. The current name might be confusing as it's not immediately clear what
type of geometry it represents. A more specific name like polygon_geometry or
as_shapely_polygon would make the intent clearer.

fastkml/geometry.py [1126]

 @property
-def geometry(self) -> Optional[geo.Polygon]:
+def as_shapely_polygon(self) -> Optional[geo.Polygon]:
  • Apply this suggestion
Suggestion importance[1-10]: 7

Why:

7
Use a type alias for the list of geometries in the MultiGeometry class

In the MultiGeometry class, consider using a type alias for the list of geometries
to improve readability and maintainability. This will make it easier to update the
allowed geometry types in the future and provide better type hints.

fastkml/geometry.py [1300]

-kml_geometries: List[Union[Point, LineString, Polygon, LinearRing, Self]]
+from typing import Union, List, TypeAlias
 
+KMLGeometry: TypeAlias = Union[Point, LineString, Polygon, LinearRing, 'MultiGeometry']
+
+class MultiGeometry(_Geometry):
+    kml_geometries: List[KMLGeometry]
+
  • Apply this suggestion
Suggestion importance[1-10]: 7

Why:

7
Use a more descriptive variable name for additional arguments in __init__ methods

**Consider using a more descriptive variable name instead of **kwargs in the init
methods. For example, you could use **additional_properties or extra_attributes to
better convey the purpose of these additional arguments.

fastkml/styles.py [205-207]

 def __init__(
     self,
     ns: Optional[str] = None,
     name_spaces: Optional[Dict[str, str]] = None,
     id: Optional[str] = None,
     target_id: Optional[str] = None,
     color: Optional[str] = None,
     color_mode: Optional[ColorMode] = None,
-    **kwargs: Any,
+    **additional_properties: Any,
 ) -> None:
  • Apply this suggestion
Suggestion importance[1-10]: 7

Why:

7
Simplify boolean checks using any() with a generator expression

In the bool methods, consider using the any() function with a generator
expression instead of explicitly checking each attribute. This can make the code
more concise and easier to maintain.

fastkml/styles.py [630-643]

 def __bool__(self) -> bool:
     """
-    Check if the style has a width defined.
+    Check if the style has any non-None attributes.
 
     Returns
     -------
-        bool: True if the width is not None, False otherwise.
+        bool: True if any of width, color, or color_mode is not None, False otherwise.
 
     """
-    return (
-        self.width is not None
-        or self.color is not None
-        or self.color_mode is not None
-    )
+    return any(attr is not None for attr in (self.width, self.color, self.color_mode))
  • Apply this suggestion
Suggestion importance[1-10]: 7

Why:

7
Add type hints for class attributes to improve type checking and self-documentation

In the StyleMap class, consider adding type hints for the pairs attribute in the
class definition. This will improve type checking and make the code more
self-documenting.

fastkml/styles.py [1278-1284]

 class StyleMap(_StyleSelector):
     """
     A <StyleMap> maps between two different Styles.
 
     Typically a <StyleMap> element is used to provide separate normal and highlighted
     styles for a placemark, so that the highlighted version appears when
     the user mouses over the icon in Google Earth.
     """
+    pairs: List[Pair]
  • Apply this suggestion
Suggestion importance[1-10]: 7

Why:

7
Implement a __getitem__ method in the StyleMap class for easier style access

In the StyleMap class, consider implementing a getitem method to allow direct
access to styles by their key (normal or highlight). This would provide a more
intuitive way to access styles and improve the usability of the class.

fastkml/styles.py [1278-1284]

 class StyleMap(_StyleSelector):
     """
     A <StyleMap> maps between two different Styles.
 
     Typically a <StyleMap> element is used to provide separate normal and highlighted
     styles for a placemark, so that the highlighted version appears when
     the user mouses over the icon in Google Earth.
     """
 
+    def __getitem__(self, key: PairKey) -> Optional[Union[StyleUrl, Style]]:
+        """
+        Get a style by its key.
+
+        Args:
+            key (PairKey): The key of the style to retrieve (normal or highlight).
+
+        Returns:
+            Optional[Union[StyleUrl, Style]]: The style associated with the given key, or None if not found.
+        """
+        return next((pair.style for pair in self.pairs if pair.key == key), None)
+
  • Apply this suggestion
Suggestion importance[1-10]: 7

Why:

7

💡 Need additional feedback ? start a PR chat

Copy link
Contributor

@ellipsis-dev ellipsis-dev bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 Looks good to me! Reviewed everything up to 3ecc272 in 2 minutes and 7 seconds

More details
  • Looked at 8447 lines of code in 38 files
  • Skipped 0 files when reviewing.
  • Skipped posting 1 drafted comments based on config settings.
1. tests/styles_test.py:416
  • Draft comment:
    The order of styles in the assertion does not match the serialized order. Ensure the order of assertions matches the order in the serialized XML.
  • Reason this comment was not posted:
    Comment did not seem useful.

Workflow ID: wflow_qrRBxMdS7MUFfZNQ


You can customize Ellipsis with 👍 / 👎 feedback, review rules, user-specific overrides, quiet mode, and more.

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @cleder - I've reviewed your changes and they look great!

Here's what I looked at during the review
  • 🟢 General issues: all looks good
  • 🟢 Security: all looks good
  • 🟡 Testing: 5 issues found
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines 182 to +185
assert not polygon.geometry
assert polygon.outer_boundary_is is not None
assert polygon.outer_boundary is not None
assert isinstance(polygon.outer_boundary, OuterBoundaryIs)
assert len(polygon.inner_boundaries) == 0
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (testing): Update assertions to match new Polygon structure

The test has been updated to check the new structure of the Polygon class. It now asserts that outer_boundary is not None and is an instance of OuterBoundaryIs, and that inner_boundaries is an empty list. This change reflects the new implementation of the Polygon class.

Suggested change
assert not polygon.geometry
assert polygon.outer_boundary_is is not None
assert polygon.outer_boundary is not None
assert isinstance(polygon.outer_boundary, OuterBoundaryIs)
assert len(polygon.inner_boundaries) == 0
assert polygon.outer_boundary is not None
assert isinstance(polygon.outer_boundary, OuterBoundaryIs)
assert polygon.inner_boundaries == []

assert polygon.outer_boundary_is is not None
assert polygon.outer_boundary is not None
assert isinstance(polygon.outer_boundary, OuterBoundaryIs)
assert len(polygon.inner_boundaries) == 0
assert "tessellate>1</" in polygon.to_string()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (testing): Add test for new Polygon attributes

Consider adding assertions to check other attributes of the Polygon class, such as extrude, tessellate, and altitude_mode. This would provide more comprehensive coverage of the Polygon class's structure.

import pygeoif.geometry as geo

from fastkml.geometry import OuterBoundaryIs, Polygon
from tests.base import Lxml, StdLibrary

polygon = Polygon.class_from_string(doc)

assert not polygon.geometry
assert polygon.outer_boundary is not None
assert isinstance(polygon.outer_boundary, OuterBoundaryIs)
assert len(polygon.inner_boundaries) == 0
assert "tessellate>1</" in polygon.to_string()
assert polygon.extrude == 0
assert polygon.altitude_mode == "clampToGround"

Comment on lines +1936 to +1941
def test_repr(self) -> None:
"""Test the __repr__ method."""
new_doc = eval(repr(self.clean_doc), {}, eval_locals) # noqa: S307

assert new_doc == self.clean_doc
assert repr(new_doc) == repr(self.clean_doc)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (testing): Add more specific assertions for repr test

The test_repr method could be more thorough. Consider adding assertions to check specific attributes or structures within the repr output, not just equality of the entire repr.

Suggested change
def test_repr(self) -> None:
"""Test the __repr__ method."""
new_doc = eval(repr(self.clean_doc), {}, eval_locals) # noqa: S307
assert new_doc == self.clean_doc
assert repr(new_doc) == repr(self.clean_doc)
def test_repr(self) -> None:
"""Test the __repr__ method."""
new_doc = eval(repr(self.clean_doc), {}, eval_locals) # noqa: S307
assert new_doc == self.clean_doc
assert repr(new_doc) == repr(self.clean_doc)
assert isinstance(new_doc, type(self.clean_doc))
assert new_doc.text == self.clean_doc.text
assert new_doc.metadata == self.clean_doc.metadata

Comment on lines +1947 to +1953
def test_eq_str_round_trip(self) -> None:
"""Test the equality of the original and the round-tripped document."""
new_doc = fastkml.KML.class_from_string(self.clean_doc.to_string(precision=15))

assert str(self.clean_doc) == str(new_doc)
assert repr(new_doc) == repr(self.clean_doc)
# srict equality is not a given new_doc == self.clean_doc
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (testing): Incomplete equality test in round-trip conversion

The test_eq_str_round_trip method doesn't actually test for equality between new_doc and self.clean_doc. Consider adding an assertion to check for equality, or explain why strict equality is not expected.

Comment on lines +1956 to +1957
class TestReprLxml(Lxml, TestRepr):
"""Test the __repr__ and __str__ methods of the KML document with lxml."""
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (testing): Consider adding specific lxml tests

The TestReprLxml class doesn't contain any lxml-specific tests. Consider adding tests that specifically check lxml functionality or behavior differences compared to the standard library implementation.

Suggested change
class TestReprLxml(Lxml, TestRepr):
"""Test the __repr__ and __str__ methods of the KML document with lxml."""
class TestReprLxml(Lxml, TestRepr):
"""Test the __repr__ and __str__ methods of the KML document with lxml."""
def test_lxml_specific_repr(self):
doc = self.kml.Document()
self.assertIn('lxml.etree', repr(doc))
def test_lxml_specific_str(self):
doc = self.kml.Document()
self.assertIn('<?xml', str(doc))

import fastkml
from fastkml.enums import AltitudeMode
from fastkml.enums import PairKey
from tests.base import Lxml
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (code-quality): Don't import test modules. (dont-import-test-modules)

ExplanationDon't import test modules.

Tests should be self-contained and don't depend on each other.

If a helper function is used by multiple tests,
define it in a helper module,
instead of importing one test from the other.

from fastkml.enums import AltitudeMode
from fastkml.enums import PairKey
from tests.base import Lxml
from tests.base import StdLibrary
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (code-quality): Don't import test modules. (dont-import-test-modules)

ExplanationDon't import test modules.

Tests should be self-contained and don't depend on each other.

If a helper function is used by multiple tests,
define it in a helper module,
instead of importing one test from the other.

@cleder cleder merged commit 3558f3e into main Oct 4, 2024
86 of 91 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants