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

Add precommit #9

Merged
merged 2 commits into from
Aug 5, 2024
Merged

Add precommit #9

merged 2 commits into from
Aug 5, 2024

Conversation

joostlek
Copy link
Collaborator

@joostlek joostlek commented Aug 5, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a configuration for managing pre-commit hooks to enhance code quality and consistency.
    • Added a new exception class, CameraConnectionError, for improved error handling in camera operations.
  • Style

    • Standardized string formatting from single quotes to double quotes across multiple files for consistency and readability.
  • Chores

    • Reformatted setup configuration for better clarity and maintainability.

Copy link

coderabbitai bot commented Aug 5, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The changes across the project enhance code readability and consistency by standardizing string delimiters from single quotes to double quotes. A new exception class improves error handling in camera operations, while the introduction of a configuration file for pre-commit hooks ensures better code quality through automated checks. Overall, these updates streamline the code, maintain functionality, and make it easier for developers to work collaboratively.

Changes

Files Change Summary
.pre-commit-config.yaml Introduced a configuration for pre-commit hooks, specifying repositories and hooks for code quality checks and commit message formatting.
setup.py Reformatted the setup() function call for improved readability, transitioning to a modern style without changing functionality.
tests/test_camera.py, tests/test_cli.py, tests/test_client.py, tests/test_store.py Standardized string literals from single to double quotes for consistency in multiple test files, maintaining original logic and functionality.
uvcclient/camera.py, uvcclient/nvr.py, uvcclient/main.py, uvcclient/store.py Updated string formatting to double quotes in various classes and methods, improving readability while preserving functionality. Added CameraConnectionError in nvr.py for better error handling.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Camera
    participant ErrorHandler

    User->>Camera: Request Snapshot
    Camera-->>User: Provide Snapshot
    User->>Camera: Request Reboot
    Camera-->>ErrorHandler: Handle Reboot Error
    ErrorHandler-->>User: Notify Error
Loading

In the code’s dance, with quotes aligned,
A rabbit hops forth, with joy intertwined.
From single to double, a change so neat,
Errors caught swiftly, no more defeat!
With hooks in place, our code shines bright,
Let’s celebrate this coding delight! 🐇✨


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 6

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 40c534a and d6496a4.

Files selected for processing (10)
  • .pre-commit-config.yaml (1 hunks)
  • setup.py (1 hunks)
  • tests/test_camera.py (2 hunks)
  • tests/test_cli.py (1 hunks)
  • tests/test_client.py (1 hunks)
  • tests/test_store.py (1 hunks)
  • uvcclient/camera.py (1 hunks)
  • uvcclient/main.py (3 hunks)
  • uvcclient/nvr.py (7 hunks)
  • uvcclient/store.py (1 hunks)
Files skipped from review due to trivial changes (6)
  • setup.py
  • tests/test_camera.py
  • tests/test_cli.py
  • tests/test_client.py
  • tests/test_store.py
  • uvcclient/main.py
Additional context used
Ruff
uvcclient/store.py

30-30: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


39-39: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

uvcclient/camera.py

55-55: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


57-57: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

uvcclient/nvr.py

101-101: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


103-103: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


109-109: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


111-111: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


209-212: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

Additional comments not posted (36)
.pre-commit-config.yaml (4)

1-4: LGTM!

The initial comments provide useful links, and the exclude settings are appropriate.


6-10: LGTM!

The CI settings are appropriate and provide useful configurations for pre-commit CI.


11-16: LGTM!

The commitizen hook configuration is appropriate and ensures commit message consistency.


17-34: LGTM!

The pre-commit hooks configuration is comprehensive and ensures code quality.

uvcclient/store.py (3)

17-17: LGTM!

The string delimiter changes in the __init__ method improve consistency.


42-42: LGTM!

The string delimiter changes in the get_camera_passwords method improve consistency.


48-50: LGTM!

The string delimiter changes in the set_camera_password method improve consistency.

uvcclient/camera.py (11)

46-46: LGTM!

The string delimiter changes in the __init__ method improve consistency.


60-87: LGTM!

The string delimiter changes in the login method improve consistency.


90-96: LGTM!

The string delimiter changes in the _cfgwrite method improve consistency.


100-100: LGTM!

The string delimiter changes in the set_led method improve consistency.


104-104: LGTM!

The string delimiter changes in the snapshot_url property improve consistency.


108-108: LGTM!

The string delimiter changes in the reboot_url property improve consistency.


112-112: LGTM!

The string delimiter changes in the status_url property improve consistency.


115-120: LGTM!

The string delimiter changes in the get_snapshot method improve consistency.


124-129: LGTM!

The string delimiter changes in the reboot method improve consistency.


132-137: LGTM!

The string delimiter changes in the get_status method improve consistency.


147-156: LGTM!

The string delimiter changes in the login method improve consistency.

uvcclient/nvr.py (18)

49-50: LGTM!

The CameraConnectionError class is a simple and appropriate addition for handling specific camera connection errors.


58-69: LGTM!

The constructor's string formatting changes improve consistency and readability. The logic remains unchanged.


Line range hint 73-81:
LGTM!

The server_version property's string formatting changes improve consistency. The logic remains unchanged.


85-87: LGTM!

The camera_identifier property's logic remains unchanged and is appropriate.


Line range hint 91-93:
LGTM!

The _get_http_connection method's logic remains unchanged and is appropriate.


113-145: LGTM!

The _uvc_request_safe method's string formatting changes improve consistency. The logic remains unchanged.


146-146: LGTM!

The _get_bootstrap method's logic remains unchanged and is appropriate.


150-151: LGTM!

The dump method's string formatting changes improve consistency. The logic remains unchanged.


162-179: LGTM!

The set_recordmode method's string formatting changes improve consistency. The logic remains unchanged.


186-194: LGTM!

The get_recordmode method's string formatting changes improve consistency. The logic remains unchanged.


197-199: LGTM!

The get_picture_settings method's string formatting changes improve consistency. The logic remains unchanged.


217-220: LGTM!

The prune_zones method's string formatting changes improve consistency. The logic remains unchanged.


223-225: LGTM!

The list_zones method's string formatting changes improve consistency. The logic remains unchanged.


232-243: LGTM!

The index method's string formatting changes improve consistency. The logic remains unchanged.


254-256: LGTM!

The name_to_uuid method's string formatting changes improve consistency. The logic remains unchanged.


260-260: LGTM!

The get_camera method's string formatting changes improve consistency. The logic remains unchanged.


263-267: LGTM!

The get_snapshot method's string formatting changes improve consistency. The logic remains unchanged.


287-303: LGTM!

The get_auth_from_env function's string formatting changes improve consistency. The logic remains unchanged.

Comment on lines +34 to +39
with open(self._path, "w") as f:
f.write(base64.b64encode(json.dumps(self._data).encode()).decode())
os.chmod(self._path, 0o600)
except (OSError, IOError) as ex:
LOG.error('Unable to write store: %s', str(ex))
raise UnableToManageStore('Unable to write to store')
LOG.error("Unable to write store: %s", str(ex))
raise UnableToManageStore("Unable to write to store")
Copy link

Choose a reason for hiding this comment

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

Improve exception handling.

The string delimiter changes are approved. However, improve the exception handling by using raise ... from None.

-    except (OSError, IOError) as ex:
-        LOG.error("Unable to write store: %s", str(ex))
-        raise UnableToManageStore("Unable to write to store")
+    except (OSError, IOError) as ex:
+        LOG.error("Unable to write store: %s", str(ex))
+        raise UnableToManageStore("Unable to write to store") from None
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
with open(self._path, "w") as f:
f.write(base64.b64encode(json.dumps(self._data).encode()).decode())
os.chmod(self._path, 0o600)
except (OSError, IOError) as ex:
LOG.error('Unable to write store: %s', str(ex))
raise UnableToManageStore('Unable to write to store')
LOG.error("Unable to write store: %s", str(ex))
raise UnableToManageStore("Unable to write to store")
with open(self._path, "w") as f:
f.write(base64.b64encode(json.dumps(self._data).encode()).decode())
os.chmod(self._path, 0o600)
except (OSError, IOError) as ex:
LOG.error("Unable to write store: %s", str(ex))
raise UnableToManageStore("Unable to write to store") from None
Tools
Ruff

39-39: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

Comment on lines +23 to +30
with open(self._path, "r") as f:
self._data = json.loads(base64.b64decode(f.read()).decode())
except (OSError, IOError):
LOG.debug('No info store')
LOG.debug("No info store")
self._data = {}
except Exception as ex:
LOG.error('Failed to read store data: %s', ex)
raise UnableToManageStore('Unable to write to store')
LOG.error("Failed to read store data: %s", ex)
raise UnableToManageStore("Unable to write to store")
Copy link

Choose a reason for hiding this comment

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

Improve exception handling.

The string delimiter changes are approved. However, improve the exception handling by using raise ... from None.

-    except Exception as ex:
-        LOG.error("Failed to read store data: %s", ex)
-        raise UnableToManageStore("Unable to write to store")
+    except Exception as ex:
+        LOG.error("Failed to read store data: %s", ex)
+        raise UnableToManageStore("Unable to write to store") from None
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
with open(self._path, "r") as f:
self._data = json.loads(base64.b64decode(f.read()).decode())
except (OSError, IOError):
LOG.debug('No info store')
LOG.debug("No info store")
self._data = {}
except Exception as ex:
LOG.error('Failed to read store data: %s', ex)
raise UnableToManageStore('Unable to write to store')
LOG.error("Failed to read store data: %s", ex)
raise UnableToManageStore("Unable to write to store")
with open(self._path, "r") as f:
self._data = json.loads(base64.b64decode(f.read()).decode())
except (OSError, IOError):
LOG.debug("No info store")
self._data = {}
except Exception as ex:
LOG.error("Failed to read store data: %s", ex)
raise UnableToManageStore("Unable to write to store") from None
Tools
Ruff

30-30: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

Comment on lines +55 to +57
raise CameraConnectError("Unable to contact camera")
except httplib.HTTPException as ex:
raise CameraConnectError('Error connecting to camera: %s' % (
str(ex)))
raise CameraConnectError("Error connecting to camera: %s" % (str(ex)))
Copy link

Choose a reason for hiding this comment

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

Improve exception handling.

The string delimiter changes are approved. However, improve the exception handling by using raise ... from None.

-    except (socket.error, OSError):
-        raise CameraConnectError("Unable to contact camera")
-    except httplib.HTTPException as ex:
-        raise CameraConnectError("Error connecting to camera: %s" % (str(ex)))
+    except (socket.error, OSError):
+        raise CameraConnectError("Unable to contact camera") from None
+    except httplib.HTTPException as ex:
+        raise CameraConnectError("Error connecting to camera: %s" % (str(ex))) from None
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
raise CameraConnectError("Unable to contact camera")
except httplib.HTTPException as ex:
raise CameraConnectError('Error connecting to camera: %s' % (
str(ex)))
raise CameraConnectError("Error connecting to camera: %s" % (str(ex)))
raise CameraConnectError("Unable to contact camera") from None
except httplib.HTTPException as ex:
raise CameraConnectError("Error connecting to camera: %s" % (str(ex))) from None
Tools
Ruff

55-55: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


57-57: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

uvcclient/nvr.py Outdated
Comment on lines +97 to +103
conn = self._get_http_connection()
conn.request(*args, **kwargs)
return conn.getresponse()
except OSError:
raise CameraConnectionError('Unable to contact camera')
raise CameraConnectionError("Unable to contact camera")
except httplib.HTTPException as ex:
raise CameraConnectionError('Error connecting to camera: %s' % (
str(ex)))
raise CameraConnectionError("Error connecting to camera: %s" % (str(ex)))
Copy link

Choose a reason for hiding this comment

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

Improve error context in exception handling.

Use raise ... from err to provide better context for exceptions.

-  except OSError:
-      raise CameraConnectionError("Unable to contact camera")
-  except httplib.HTTPException as ex:
-      raise CameraConnectionError("Error connecting to camera: %s" % (str(ex)))
+  except OSError as err:
+      raise CameraConnectionError("Unable to contact camera") from err
+  except httplib.HTTPException as ex:
+      raise CameraConnectionError("Error connecting to camera: %s" % (str(ex))) from ex
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
conn = self._get_http_connection()
conn.request(*args, **kwargs)
return conn.getresponse()
except OSError:
raise CameraConnectionError('Unable to contact camera')
raise CameraConnectionError("Unable to contact camera")
except httplib.HTTPException as ex:
raise CameraConnectionError('Error connecting to camera: %s' % (
str(ex)))
raise CameraConnectionError("Error connecting to camera: %s" % (str(ex)))
conn = self._get_http_connection()
conn.request(*args, **kwargs)
return conn.getresponse()
except OSError as err:
raise CameraConnectionError("Unable to contact camera") from err
except httplib.HTTPException as ex:
raise CameraConnectionError("Error connecting to camera: %s" % (str(ex))) from ex
Tools
Ruff

101-101: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


103-103: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

uvcclient/nvr.py Outdated
Comment on lines +109 to +111
raise NvrError("Failed to contact NVR")
except httplib.HTTPException as ex:
raise NvrError('Error connecting to camera: %s' % str(ex))

def _uvc_request_safe(self, path, method='GET', data=None,
mimetype='application/json'):
conn = self._get_http_connection();
if '?' in path:
url = '%s&apiKey=%s' % (path, self._apikey)
raise NvrError("Error connecting to camera: %s" % str(ex))
Copy link

Choose a reason for hiding this comment

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

Improve error context in exception handling.

Use raise ... from err to provide better context for exceptions.

-  except OSError:
-      raise NvrError("Failed to contact NVR")
-  except httplib.HTTPException as ex:
-      raise NvrError("Error connecting to camera: %s" % str(ex))
+  except OSError as err:
+      raise NvrError("Failed to contact NVR") from err
+  except httplib.HTTPException as ex:
+      raise NvrError("Error connecting to camera: %s" % str(ex)) from ex
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
raise NvrError("Failed to contact NVR")
except httplib.HTTPException as ex:
raise NvrError('Error connecting to camera: %s' % str(ex))
def _uvc_request_safe(self, path, method='GET', data=None,
mimetype='application/json'):
conn = self._get_http_connection();
if '?' in path:
url = '%s&apiKey=%s' % (path, self._apikey)
raise NvrError("Error connecting to camera: %s" % str(ex))
raise NvrError("Failed to contact NVR") from err
except httplib.HTTPException as ex:
raise NvrError("Error connecting to camera: %s" % str(ex)) from ex
Tools
Ruff

109-109: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


111-111: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

uvcclient/nvr.py Outdated
Comment on lines +202 to +212
url = "/api/2.0/camera/%s" % uuid
data = self._uvc_request(url)
for key in settings:
dtype = type(data['data'][0]['ispSettings'][key])
dtype = type(data["data"][0]["ispSettings"][key])
try:
data['data'][0]['ispSettings'][key] = dtype(settings[key])
data["data"][0]["ispSettings"][key] = dtype(settings[key])
except ValueError:
raise Invalid('Setting `%s\' requires %s not %s' % (
key, dtype.__name__, type(settings[key]).__name__))
data = self._uvc_request(url, 'PUT', json.dumps(data['data'][0]))
return data['data'][0]['ispSettings']
raise Invalid(
"Setting `%s' requires %s not %s"
% (key, dtype.__name__, type(settings[key]).__name__)
)
Copy link

Choose a reason for hiding this comment

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

Improve error context in exception handling.

Use raise ... from err to provide better context for exceptions.

-  except ValueError:
-      raise Invalid(
-          "Setting `%s' requires %s not %s"
-          % (key, dtype.__name__, type(settings[key]).__name__)
-      )
+  except ValueError as err:
+      raise Invalid(
+          "Setting `%s' requires %s not %s"
+          % (key, dtype.__name__, type(settings[key]).__name__)
+      ) from err
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
url = "/api/2.0/camera/%s" % uuid
data = self._uvc_request(url)
for key in settings:
dtype = type(data['data'][0]['ispSettings'][key])
dtype = type(data["data"][0]["ispSettings"][key])
try:
data['data'][0]['ispSettings'][key] = dtype(settings[key])
data["data"][0]["ispSettings"][key] = dtype(settings[key])
except ValueError:
raise Invalid('Setting `%s\' requires %s not %s' % (
key, dtype.__name__, type(settings[key]).__name__))
data = self._uvc_request(url, 'PUT', json.dumps(data['data'][0]))
return data['data'][0]['ispSettings']
raise Invalid(
"Setting `%s' requires %s not %s"
% (key, dtype.__name__, type(settings[key]).__name__)
)
url = "/api/2.0/camera/%s" % uuid
data = self._uvc_request(url)
for key in settings:
dtype = type(data["data"][0]["ispSettings"][key])
try:
data["data"][0]["ispSettings"][key] = dtype(settings[key])
except ValueError as err:
raise Invalid(
"Setting `%s' requires %s not %s"
% (key, dtype.__name__, type(settings[key]).__name__)
) from err
Tools
Ruff

209-212: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

@joostlek joostlek merged commit f817033 into master Aug 5, 2024
1 check passed
@joostlek joostlek deleted the precommit branch August 5, 2024 12:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant