Skip to content

Commit

Permalink
chore: Setup ruff (#217)
Browse files Browse the repository at this point in the history
* chore: Replace black and flake8 with Ruff

- Setup ruff, ran ruff scans and format
- Fixed all present issues
- Updated workflow to use ruff instead

* chore: Setup pre-commit with ruff hooks

* chore: Fix failing tests and moved conftest

* chore: modified conftest to aquire token if it is not present
  • Loading branch information
sean-sinclair authored Dec 11, 2024
1 parent a1d49be commit d6cee36
Show file tree
Hide file tree
Showing 14 changed files with 149 additions and 115 deletions.
2 changes: 0 additions & 2 deletions .flake8

This file was deleted.

48 changes: 18 additions & 30 deletions .github/workflows/linting.yml
Original file line number Diff line number Diff line change
@@ -1,40 +1,28 @@
name: linting
name: Check formatting and linting

on:
pull_request:
push: { branches: [main] }

jobs:
black:
ruff-check:
name: Run ruff lint and format checks
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.9"]
steps:
- uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- uses: psf/black@stable
with:
options: "--check --verbose --line-length 79"
src: "./src/sumo/wrapper"
flake8:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.9"]

steps:
- uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5

- uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install flake8
- name: Analysing the code with flake8
run: |
flake8 src/sumo/wrapper --config .flake8
python-version: '3.11'
cache: 'pip'

- name: Installing dependencies
run: pip install ruff

- name: Run ruff lint
run: ruff check .

- name: Run ruff format
run: ruff format . --check

3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ build
/src/testing.py
/docs/_build
/src/sumo/wrapper/version.py
*_version.py
*_version.py
.vscode/
16 changes: 16 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
repos:
- repo: local
hooks:
- id: lint
name: Ruff Lint
description: Linting using ruff
entry: bash -c 'ruff check .'
language: system
stages: ["pre-commit", "pre-push"]

- id: format
name: Ruff Format
description: Formatting using ruff
entry: bash -c 'ruff format . --check'
language: system
stages: ["pre-commit", "pre-push"]
1 change: 0 additions & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,3 @@
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["_static"]

34 changes: 30 additions & 4 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,6 @@ build-backend = "setuptools.build_meta"
[tool.setuptools_scm]
version_file = "src/sumo/wrapper/_version.py"


[tool.black]
line-length = 79

[project]
name = "sumo-wrapper-python"
description = "Python wrapper for the Sumo API"
Expand Down Expand Up @@ -39,6 +35,7 @@ docs = [
"sphinx-autodoc-typehints",
"sphinxcontrib-apidoc",
]
dev = ["ruff", "pre-commit"]

[project.urls]
Repository = "https://github.com/equinor/sumo-wrapper-python"
Expand All @@ -48,3 +45,32 @@ sumo_login = "sumo.wrapper.login:main"

[tool.setuptools.packages.find]
where = ["src"]

[tool.ruff]
exclude = [
".env",
".git",
".github",
".venv",
"venv",
]

line-length = 79

[tool.ruff.lint]
ignore = [
"E501",
]

extend-select = [
"C4", # Flake8-comprehensions
"I", # isort
"SIM", # Flake8-simplify
"TC", # Flake8-type-checking
"TID", # Flake8-tidy-imports
"N", # pep8-naming
]

[tool.ruff.lint.per-file-ignores]
"__init__.py" = ["F401"]

2 changes: 1 addition & 1 deletion src/sumo/wrapper/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from .sumo_client import SumoClient
from ._retry_strategy import RetryStrategy
from .sumo_client import SumoClient

try:
from ._version import version
Expand Down
30 changes: 14 additions & 16 deletions src/sumo/wrapper/_auth_provider.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import msal
import errno
import json
import os
from datetime import datetime, timedelta
import stat
import sys
import json
import jwt
import time
from azure.identity import ManagedIdentityCredential
import tenacity as tn
from ._retry_strategy import _log_retry_info, _return_last_value
from datetime import datetime, timedelta

import jwt
import msal
import tenacity as tn
from azure.identity import ManagedIdentityCredential
from msal_extensions.persistence import FilePersistence
from msal_extensions.token_cache import PersistedTokenCache
import errno

from ._retry_strategy import _log_retry_info, _return_last_value

if not sys.platform.startswith("linux"):
from msal_extensions import build_encrypted_persistence
Expand Down Expand Up @@ -422,14 +422,12 @@ def get_auth_provider(
return AuthProviderDeviceCode(client_id, authority, resource_id)
# ELSE
if all(
[
os.getenv(x)
for x in [
"AZURE_FEDERATED_TOKEN_FILE",
"AZURE_TENANT_ID",
"AZURE_CLIENT_ID",
"AZURE_AUTHORITY_HOST",
]
os.getenv(x)
for x in [
"AZURE_FEDERATED_TOKEN_FILE",
"AZURE_TENANT_ID",
"AZURE_CLIENT_ID",
"AZURE_AUTHORITY_HOST",
]
):
return AuthProviderManaged(resource_id)
13 changes: 9 additions & 4 deletions src/sumo/wrapper/_logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,19 @@


class LogHandlerSumo(logging.Handler):
def __init__(self, sumoClient):
def __init__(self, sumo_client):
logging.Handler.__init__(self)
self._sumoClient = sumoClient
self._sumoClient = sumo_client
return

def emit(self, record):
try:
dt = datetime.utcnow().replace(microsecond=0).isoformat() + "Z"
dt = (
datetime.now(datetime.timezone.utc)
.replace(microsecond=0)
.isoformat()
+ "Z"
)
json = {
"severity": record.levelname,
"message": record.getMessage(),
Expand All @@ -20,7 +25,7 @@ def emit(self, record):
"funcname": record.funcName,
"linenumber": record.lineno,
}
if "objectUuid" in record.__dict__.keys():
if "objectUuid" in record.__dict__:
json["objectUuid"] = record.__dict__.get("objectUuid")

self._sumoClient.post("/message-log/new", json=json)
Expand Down
2 changes: 1 addition & 1 deletion src/sumo/wrapper/_retry_strategy.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import tenacity as tn
import httpx
import tenacity as tn


def _log_retry_info(retry_state):
Expand Down
4 changes: 2 additions & 2 deletions src/sumo/wrapper/login.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import logging
import platform
from pathlib import Path
from argparse import ArgumentParser
from sumo.wrapper import SumoClient
from pathlib import Path

from sumo.wrapper import SumoClient

logger = logging.getLogger("sumo.wrapper")
logger.setLevel(level="CRITICAL")
Expand Down
20 changes: 9 additions & 11 deletions src/sumo/wrapper/sumo_client.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
import logging
import asyncio
import contextlib
import logging
import re

import httpx
import jwt
import re

from ._blob_client import BlobClient
from ._logging import LogHandlerSumo
from ._auth_provider import get_auth_provider
from .config import APP_REGISTRATION, TENANT_ID, AUTHORITY_HOST_URI

from ._blob_client import BlobClient
from ._decorators import (
raise_for_status,
raise_for_status_async,
)

from ._logging import LogHandlerSumo
from ._retry_strategy import RetryStrategy
from .config import APP_REGISTRATION, AUTHORITY_HOST_URI, TENANT_ID

logger = logging.getLogger("sumo.wrapper")

Expand Down Expand Up @@ -61,12 +61,10 @@ def __init__(
logger.debug("Token provided")

payload = None
try:
with contextlib.suppress(jwt.InvalidTokenError):
payload = jwt.decode(
token, options={"verify_signature": False}
)
except jwt.InvalidTokenError:
pass

if payload:
logger.debug(f"Token decoded as JWT, payload: {payload}")
Expand Down Expand Up @@ -380,7 +378,7 @@ def _delete():

return retryer(_delete)

def getLogger(self, name):
def get_logger(self, name):
"""Gets a logger object that sends log objects into the message_log
index for the Sumo instance.
Expand Down
5 changes: 5 additions & 0 deletions conftest.py → tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import os

from sumo.wrapper import SumoClient


def pytest_addoption(parser):
parser.addoption("--token", action="store", default="")
Expand All @@ -10,5 +12,8 @@ def pytest_generate_tests(metafunc):
token = os.environ.get("ACCESS_TOKEN")
token = token if token and len(token) > 0 else None

if token is None:
_ = SumoClient(env="dev", interactive=True)

if "token" in metafunc.fixturenames:
metafunc.parametrize("token", [token])
Loading

0 comments on commit d6cee36

Please sign in to comment.