Skip to content

Commit

Permalink
style: refactor code formatting in Makefile and add ruff.toml for lin…
Browse files Browse the repository at this point in the history
…ting configuration.
  • Loading branch information
liblaf committed May 11, 2024
1 parent c494eae commit 86ed400
Show file tree
Hide file tree
Showing 14 changed files with 113 additions and 68 deletions.
10 changes: 5 additions & 5 deletions .cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,24 @@
"acked",
"bidi",
"commitizen",
"ehdmg",
"eifinger",
"httpx",
"kpgrtw",
"levelno",
"liblaf",
"oqmr",
"pycache",
"pydantic",
"pydocstyle",
"pylint",
"pypa",
"pypi",
"pyproject",
"pyright",
"taplo",
"tiktoken",
"typer",
"useh",
"venv",
"ztrp"
"uoyfi",
"venv"
],
"ignorePaths": ["**/*-lock.*", "**/*.lock*", "**/.cspell.json"],
"allowCompoundWords": true
Expand Down
45 changes: 21 additions & 24 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,24 @@ on:
push:

jobs:
build:
name: Build
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Rye
uses: eifinger/setup-rye@v3
- name: Install Dependencies
run: rye sync
- name: Build Package
run: rye build
- name: Upload Artifacts
uses: actions/upload-artifact@v4
with:
name: dist
path: dist

release-please:
name: Release Please
permissions:
Expand All @@ -13,6 +31,7 @@ jobs:
runs-on: ubuntu-latest
outputs:
created: ${{ steps.release.outputs.releases_created }}
pr: ${{ steps.release.outputs.pr }}
tag: ${{ steps.release.outputs.tag_name }}
steps:
- name: Checkout
Expand All @@ -24,24 +43,6 @@ jobs:
config-file: .github/release-please/config.json
manifest-file: .github/release-please/.manifest.json

build:
name: Build
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Rye
uses: eifinger/setup-rye@v3
- name: Install Dependencies
run: rye sync
- name: Build Package
run: rye build
- name: Upload Artifacts
uses: actions/upload-artifact@v4
with:
name: dist
path: dist

pre-release:
name: Pre-release
permissions:
Expand All @@ -54,8 +55,6 @@ jobs:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Download Artifacts
uses: actions/download-artifact@v4
with:
Expand All @@ -74,8 +73,8 @@ jobs:
permissions:
id-token: write
needs:
- release-please
- build
- release-please
if: needs.release-please.outputs.created == 'true'
runs-on: ubuntu-latest
steps:
Expand All @@ -92,13 +91,11 @@ jobs:
permissions:
contents: write
needs:
- release-please
- build
- release-please
if: needs.release-please.outputs.created == 'true'
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Download Artifacts
uses: actions/download-artifact@v4
with:
Expand Down
18 changes: 10 additions & 8 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
NAME := aic
default: check format toml-sort

default: fmt
check:
- ruff check

dist:
rye build --clean
format:
ruff format

fmt: fmt-toml/pyproject.toml
toml-sort: toml-sort\:pyproject.toml
toml-sort: toml-sort\:ruff.toml

fmt-toml/%:
toml-sort --in-place --all "$*"
taplo format "$*"
toml-sort\:%: %
toml-sort --in-place --all "$<"
taplo format "$<"
40 changes: 40 additions & 0 deletions ruff.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
fix = true
show-fixes = true
target-version = "py311"

[format]
docstring-code-format = true

[lint]
ignore = [
"ANN101",
"ANN102",
"ANN401",
"ARG002",
"BLE001",
"COM812",
"D100",
"D101",
"D102",
"D103",
"D104",
"D105",
"D106",
"D107",
"FIX002",
"S101",
"S603",
"S607",
"T201",
"TD002",
"TD003",
"TD004",
"TD005",
]
select = ["ALL"]

[lint.pydocstyle]
convention = "google"

[lint.pylint]
max-args = 7
7 changes: 4 additions & 3 deletions src/aic/api/openrouter.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,10 @@ def get_models() -> list[Model]:


@functools.lru_cache
def get_model(id: str) -> Model:
def get_model(model_id: str) -> Model:
models: list[Model] = get_models()
for model in models:
if model.id == id:
if model.id == model_id:
return model
raise ValueError(f"Model not found: {id}")
msg: str = f"Model not found: {id}"
raise ValueError(msg)
8 changes: 4 additions & 4 deletions src/aic/cli/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Annotated, Optional
from typing import Annotated

import typer

Expand All @@ -12,11 +12,11 @@

@app.command()
def main(
pathspec: Annotated[Optional[list[str]], typer.Argument()] = None,
pathspec: Annotated[list[str] | None, typer.Argument()] = None,
*,
list_models: Annotated[bool, typer.Option()] = False,
api_key: Annotated[Optional[str], typer.Option(envvar="OPENAI_API_KEY")] = None,
base_url: Annotated[Optional[str], typer.Option(envvar="OPENAI_BASE_URL")] = None,
api_key: Annotated[str | None, typer.Option(envvar="OPENAI_API_KEY")] = None,
base_url: Annotated[str | None, typer.Option(envvar="OPENAI_BASE_URL")] = None,
model: Annotated[str, typer.Option()] = "gpt-3.5-turbo",
max_tokens: Annotated[int, typer.Option()] = 500,
verify: Annotated[bool, typer.Option()] = True,
Expand Down
24 changes: 13 additions & 11 deletions src/aic/cli/main.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from typing import TYPE_CHECKING

import openai
from openai.types.chat import ChatCompletionChunk, ChatCompletionMessageParam
from rich.console import Group
from rich.live import Live
from rich.markdown import Markdown
Expand All @@ -12,6 +13,9 @@
from aic import token as _token
from aic.api import openrouter as _openrouter

if TYPE_CHECKING:
from openai.types.chat import ChatCompletionChunk, ChatCompletionMessageParam


def main(
*pathspec: str,
Expand Down Expand Up @@ -63,11 +67,10 @@ def main(

def format_tokens(prompt_tokens: int, completion_tokens: int) -> str:
total_tokens: int = prompt_tokens + completion_tokens
return "Tokens: {} = {} (Prompt) + {} (Completion)".format(
_pretty.format_int(total_tokens),
_pretty.format_int(prompt_tokens),
_pretty.format_int(completion_tokens),
)
total: str = _pretty.format_int(total_tokens)
prompt: str = _pretty.format_int(prompt_tokens)
completion: str = _pretty.format_int(completion_tokens)
return f"Tokens: {total} = {prompt} (Prompt) + {completion} (Completion)"


def format_cost(
Expand All @@ -76,8 +79,7 @@ def format_cost(
prompt_cost: float = prompt_tokens * pricing.prompt
completion_cost: float = completion_tokens * pricing.completion
total_cost: float = prompt_cost + completion_cost
return "Cost: {} = {} (Prompt) + {} (Completion)".format(
_pretty.format_currency(total_cost),
_pretty.format_currency(prompt_cost),
_pretty.format_currency(completion_cost),
)
total: str = _pretty.format_currency(total_cost)
prompt: str = _pretty.format_currency(prompt_cost)
completion: str = _pretty.format_currency(completion_cost)
return f"Cost: {total} = {prompt} (Prompt) + {completion} (Completion)"
12 changes: 7 additions & 5 deletions src/aic/commit_lint.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import re
from collections.abc import Sequence
from typing import Optional
from typing import TYPE_CHECKING

if TYPE_CHECKING:
from collections.abc import Sequence

PATTERN: re.Pattern[str] = re.compile(
r"(?P<type>\w+)(?:\((?P<scope>[^\)]+)\))?(?P<breaking>!)?: (?P<description>.+)"
Expand All @@ -16,12 +18,12 @@ def sanitize(msg: str) -> str:


def sanitize_line(line: str) -> str:
matches: Optional[re.Match[str]] = PATTERN.fullmatch(line)
matches: re.Match[str] | None = PATTERN.fullmatch(line)
if matches is None:
return line
type_: str = matches.group("type")
scope: Optional[str] = matches.group("scope")
breaking: Optional[str] = matches.group("breaking")
scope: str | None = matches.group("scope")
breaking: str | None = matches.group("breaking")
description: str = matches.group("description")
type_ = type_.strip().lower()
line = type_
Expand Down
5 changes: 2 additions & 3 deletions src/aic/config.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import pathlib
import tomllib

import pydantic
import tomllib
import typer


Expand All @@ -14,6 +14,5 @@ def load() -> Config:
config_file: pathlib.Path = app_dir / "config.toml"
if config_file.exists():
with config_file.open("rb") as fp:
config = Config(**tomllib.load(fp))
return config
return Config(**tomllib.load(fp))
return Config()
2 changes: 1 addition & 1 deletion src/aic/git.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ def commit(message: str, *, verify: bool = True) -> None:
"--verify" if verify else "--no-verify",
]
logger.debug(args)
proc: subprocess.CompletedProcess[bytes] = subprocess.run(args)
proc: subprocess.CompletedProcess[bytes] = subprocess.run(args, check=False)
if proc.returncode != 0:
raise typer.Exit(proc.returncode)

Expand Down
3 changes: 1 addition & 2 deletions src/aic/prompt/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,7 @@ def ask_breaking_change(self) -> str | None:
).unsafe_ask()
except KeyboardInterrupt:
self.breaking_change = None
finally:
return self.breaking_change
return self.breaking_change

def build(self, diff: str, model: _openrouter.Model, max_tokens: int) -> str:
_: Any
Expand Down
3 changes: 2 additions & 1 deletion src/aic/prompt/_type.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
# ruff: noqa: E501
import enum


class CommitType(enum.StrEnum):
"""https://github.com/commitizen/conventional-commit-types/blob/master/index.json"""
"""https://github.com/commitizen/conventional-commit-types/blob/master/index.json."""

FEAT = "feat"
FIX = "fix"
Expand Down
1 change: 1 addition & 0 deletions src/aic/prompt/template.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# ruff: noqa: E501
from aic.prompt import _type


Expand Down
3 changes: 2 additions & 1 deletion src/aic/token.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
def num_tokens_from_string(string: str, model: str) -> int:
"""Returns the number of tokens in a text string.
https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken"""
https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken
"""
encoding: tiktoken.Encoding = tiktoken.encoding_for_model(model)
num_tokens: int = len(encoding.encode(string))
return num_tokens
Expand Down

0 comments on commit 86ed400

Please sign in to comment.