Skip to content

Commit

Permalink
Add a pre-commit configuration (#210)
Browse files Browse the repository at this point in the history
* Add a pre-commit file based on InvenTree

Removed those hooks which had to with non-python scripts

* Isort all existing files, remove lines with white-space (according to flake8). Spellcheck words

Disable flake8 extras for now, as they are excessive
  • Loading branch information
miggland authored Nov 22, 2023
1 parent a2dabeb commit 52e6b6b
Show file tree
Hide file tree
Showing 28 changed files with 252 additions and 218 deletions.
24 changes: 24 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks

repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: mixed-line-ending
- repo: https://github.com/pycqa/flake8
rev: '6.1.0'
hooks:
- id: flake8
- repo: https://github.com/pycqa/isort
rev: '5.12.0'
hooks:
- id: isort
- repo: https://github.com/codespell-project/codespell
rev: v2.2.6
hooks:
- id: codespell
args: ['-L fo']
6 changes: 3 additions & 3 deletions ci/check_version_number.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import sys
import re
import os
import argparse
import os
import re
import sys

if __name__ == '__main__':

Expand Down
23 changes: 11 additions & 12 deletions inventree/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,14 @@
with the InvenTree database server.
"""

import requests
import os
import json
import logging
import os
from urllib.parse import urljoin, urlparse

import requests
from requests.auth import HTTPBasicAuth
from requests.exceptions import Timeout
from urllib.parse import urljoin, urlparse


logger = logging.getLogger('inventree')

Expand All @@ -39,7 +38,7 @@ def __init__(self, host=None, **kwargs):
Args:
base_url - Base URL for the InvenTree server, including port (if required)
e.g. "http://inventree.server.com:8000"
kwargs:
username - Login username
password - Login password
Expand Down Expand Up @@ -77,7 +76,7 @@ def __init__(self, host=None, **kwargs):

def setHostName(self, host):
"""Validate that the provided base URL is valid"""

if host is None:
raise AttributeError("InvenTreeAPI initialized without providing host address")

Expand All @@ -86,7 +85,7 @@ def setHostName(self, host):

if not url.scheme:
raise Exception(f"Host '{host}' supplied without valid scheme")

if not url.netloc or not url.hostname:
raise Exception(f"Host '{host}' supplied without valid hostname")

Expand Down Expand Up @@ -308,7 +307,7 @@ def request(self, api_url, **kwargs):
auth = None
else:
auth = self.auth

payload['headers'] = headers
payload['auth'] = auth
payload['proxies'] = proxies
Expand Down Expand Up @@ -359,13 +358,13 @@ def request(self, api_url, **kwargs):

if headers:
detail['headers'] = headers

if params:
detail['params'] = params

if files:
detail['files'] = files

if data:
detail['data'] = data

Expand Down Expand Up @@ -591,7 +590,7 @@ def downloadFile(self, url, destination, overwrite=False, params=None, proxies=d

if headers:
detail['headers'] = headers

raise requests.exceptions.HTTPError(detail)

headers = response.headers
Expand Down
53 changes: 26 additions & 27 deletions inventree/base.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
# -*- coding: utf-8 -*-

import os
import logging
import json
import logging
import os

from . import api as inventree_api


INVENTREE_PYTHON_VERSION = "0.13.0"


Expand All @@ -18,7 +17,7 @@ class InventreeObject(object):

# API URL (required) for the particular model type
URL = ""

# Minimum server version for the particular model type
REQUIRED_API_VERSION = None

Expand All @@ -45,13 +44,13 @@ def __init__(self, api, pk=None, data=None):
# extract it from the provided dataset
if pk is None and data:
pk = data.get('pk', None)

# Convert to integer
try:
pk = int(pk)
except Exception:
raise TypeError(f"Supplied <pk> value ({pk}) for {self.__class__} is invalid.")

if pk <= 0:
raise ValueError(f"Supplier <pk> value ({pk}) for {self.__class__} must be positive.")

Expand All @@ -70,7 +69,7 @@ def __init__(self, api, pk=None, data=None):
@classmethod
def checkApiVersion(cls, api):
"""Check if the API version supports this particular model.
Raises:
NotSupportedError if the server API version is too 'old'
"""
Expand Down Expand Up @@ -150,7 +149,7 @@ def pk(self):
val = int(val)
except ValueError:
pass

return val

@classmethod
Expand All @@ -164,7 +163,7 @@ def create(cls, api, data, **kwargs):
data.pop('pk')

response = api.post(cls.URL, data, **kwargs)

if response is None:
logger.error("Error creating new object")
return None
Expand Down Expand Up @@ -230,13 +229,13 @@ def save(self, data=None, files=None, method='PATCH'):
"""

self.checkApiVersion(self._api)

# If 'data' is not specified, then use *all* the data
if data is None:
data = self._data

if self._api:

# Default method used is PATCH (partial update)
if method.lower() == 'patch':
response = self._api.patch(self._url, data, files=files)
Expand All @@ -253,7 +252,7 @@ def save(self, data=None, files=None, method='PATCH'):
self.reload()

return response

def is_valid(self):
"""
Test if this object is 'valid' - it has received data from the server.
Expand All @@ -271,10 +270,10 @@ def is_valid(self):

if data is None:
return False

if len(data) == 0:
return False

return True

def reload(self):
Expand Down Expand Up @@ -342,7 +341,7 @@ def bulkDelete(cls, api: inventree_api.InvenTreeAPI, items=None, filters=None):
Returns:
API response object
Throws:
NotImplementError: The server API version is too old (requires v58)
ValueError: Neither items or filters are supplied
Expand All @@ -354,12 +353,12 @@ def bulkDelete(cls, api: inventree_api.InvenTreeAPI, items=None, filters=None):

if not items and not filters:
raise ValueError("Must supply either 'items' or 'filters' argument")

data = {}

if items:
data['items'] = items

if filters:
data['filters'] = filters

Expand All @@ -372,7 +371,7 @@ def bulkDelete(cls, api: inventree_api.InvenTreeAPI, items=None, filters=None):
class Attachment(BulkDeleteMixin, InventreeObject):
"""
Class representing a file attachment object
Multiple sub-classes exist, representing various types of attachment models in the database.
"""

Expand Down Expand Up @@ -414,7 +413,7 @@ def upload(cls, api, attachment, comment='', **kwargs):
'attachment': (os.path.basename(attachment), fo),
}
)

else:
# Assumes a StringIO or BytesIO like object
name = getattr(attachment, 'name', 'filename')
Expand All @@ -430,7 +429,7 @@ def upload(cls, api, attachment, comment='', **kwargs):
logger.info(f"File uploaded to {cls.URL}")
else:
logger.error(f"File upload failed at {cls.URL}")

return response

def download(self, destination, **kwargs):
Expand Down Expand Up @@ -473,7 +472,7 @@ def getMetadata(self):

def setMetadata(self, data, overwrite=False):
"""Write metadata to this particular model.
Arguments:
data: The data to be written. Must be a dict object
overwrite: If true, provided data replaces existing data. If false (default) data is merged with any existing data.
Expand Down Expand Up @@ -558,7 +557,7 @@ class StatusMixin:
- complete
- cancel
on supported items.
Other functions, such as
- ship
- finish
Expand Down Expand Up @@ -597,11 +596,11 @@ def _statusupdate(self, status: str, reload=True, data=None, **kwargs):
return response

def complete(self, **kwargs):

return self._statusupdate(status='complete', **kwargs)

def cancel(self, **kwargs):

return self._statusupdate(status='cancel', **kwargs)


Expand All @@ -614,14 +613,14 @@ class BarcodeMixin:
@classmethod
def barcodeModelType(cls):
"""Return the model type name required for barcode assignment.
Default value is the lower-case class name ()
"""
return cls.__name__.lower()

def assignBarcode(self, barcode_data: str, reload=True):
"""Assign an arbitrary barcode to this object (in the database).
Arguments:
barcode_data: A string containing arbitrary barcode data
"""
Expand Down
2 changes: 1 addition & 1 deletion inventree/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class Build(

def getAttachments(self):
return BuildAttachment.list(self._api, build=self.pk)

def uploadAttachment(self, attachment, comment=''):
return BuildAttachment.upload(
self._api,
Expand Down
1 change: 0 additions & 1 deletion inventree/company.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import inventree.base
import inventree.order


logger = logging.getLogger('inventree')


Expand Down
Loading

0 comments on commit 52e6b6b

Please sign in to comment.