From 12134c2c9511ecf5fe5c683b50f5fa4b7459f274 Mon Sep 17 00:00:00 2001 From: Farkhod Sadykov Date: Sat, 15 Apr 2023 01:22:23 +0200 Subject: [PATCH] Migrating to TOML new linting and stricted typing (#165) * pyproject.toml * sdist and bdist specific files. * CONTRIBUITNG.md. * New linters and CI/CD. * Mypy stricted types. * Shell scripts to run linters and tests. --- .github/workflows/lint_test.yml | 32 +++---- CONTRIBUITNG.md | 37 ++++++++ Dockerfile | 1 - pre-push.sh | 59 ------------ pyproject.toml | 95 +++++++++++++++++++ requirements.txt | 6 -- scripts/format.sh | 6 ++ scripts/lint.sh | 9 ++ scripts/test.sh | 7 ++ setup.py | 29 ------ sgpt/__init__.py | 6 +- sgpt/app.py | 24 ++--- sgpt/cache.py | 11 ++- sgpt/client.py | 26 +++-- sgpt/config.py | 14 +-- sgpt/handlers/chat_handler.py | 44 ++++----- sgpt/handlers/default_handler.py | 9 +- sgpt/handlers/handler.py | 15 ++- sgpt/handlers/repl_handler.py | 9 +- sgpt/make_prompt.py | 2 +- sgpt/utils.py | 6 +- tests/__init__.py | 0 ...tegration_tests.py => test_integration.py} | 21 ++-- tests/{unittests.py => test_unit.py} | 5 +- 24 files changed, 261 insertions(+), 212 deletions(-) create mode 100644 CONTRIBUITNG.md delete mode 100755 pre-push.sh create mode 100644 pyproject.toml delete mode 100644 requirements.txt create mode 100644 scripts/format.sh create mode 100644 scripts/lint.sh create mode 100644 scripts/test.sh delete mode 100644 setup.py create mode 100644 tests/__init__.py rename tests/{integration_tests.py => test_integration.py} (97%) rename tests/{unittests.py => test_unit.py} (96%) diff --git a/.github/workflows/lint_test.yml b/.github/workflows/lint_test.yml index 56c115c..79fe7ed 100644 --- a/.github/workflows/lint_test.yml +++ b/.github/workflows/lint_test.yml @@ -23,26 +23,16 @@ jobs: - name: Install dependencies run: | python -m pip install --upgrade pip - pip install pylint - pip install black - pip install requests_mock - pip install -r requirements.txt - - name: Analysing the code with pylint - run: | - pylint \ - ./sgpt \ - ./tests \ - --disable=fixme \ - --disable=cyclic-import \ - --disable=useless-import-alias \ - --disable=missing-function-docstring \ - --disable=missing-module-docstring \ - --disable=missing-class-docstring \ - --disable=too-many-function-args \ - - - name: Analysing the code with black - run: black ./sgpt ./tests --check --target-version py310 - - name: Run unittests + pip install ."[dev,test]" + - name: black + run: black sgpt tests --check + - name: isort + run: isort sgpt tests scripts --check-only + - name: ruff + run: ruff sgpt tests scripts + - name: mypy + run: mypy sgpt + - name: unittests run: | export OPENAI_API_KEY=test_api_key - python -m unittest tests/unittests.py + pytest tests/test_unit.py diff --git a/CONTRIBUITNG.md b/CONTRIBUITNG.md new file mode 100644 index 0000000..117ca3b --- /dev/null +++ b/CONTRIBUITNG.md @@ -0,0 +1,37 @@ +# Contributing to ShellGPT +Thank you for considering contributing to ShellGPT (sgpt)! In order to ensure a smooth and enjoyable experience for everyone, please follow the steps outlined below. + +## Find an issue to work on +* First, browse the existing issues to find one that interests you. If you find an issue you would like to work on, assign it to yourself and leave a comment expressing your interest in working on it soon. +* If you have a new feature in mind that doesn't have an existing issue, kindly create a discussion in the "ideas" category using GitHub Discussions. Gather feedback from the community, and if you receive approval from at least a couple of people, create an issue and assign it to yourself. +* If there is an urgent issue, such as a critical bug causing the app to crash, create a pull request right away. + +## Developing +> ShellGPT is written using strict types, which means you will need to define types. The project utilizes several linting and testing tools: ruff, mypy, isort, black, and pytest. + +### Virtual environment +Create a virtual environment using Python venv and activate it: + +```shell +python -m venv env && source ./env/bin/activate +``` + +### Install dependencies +Install the necessary dependencies, in this case you will need to install the development and test dependencies: + +```shell +pip install -e ."[dev,test]" +``` +### Start coding +With your environment set up and the issue assigned, you can begin working on your solution. Familiarize yourself with the existing codebase, and follow the project's coding style and conventions. Remember to write clean, modular, and maintainable code, which will make it easier for others to understand and review. As you make progress, commit your changes frequently to keep track of your work. + +### Testing +This is very important step. Every changes that implements a new feature or modifies the logic of existing features should include "integration" tests. These are tests that call `sgpt` with defined arguments, capture the output, and verify that the feature works as expected. See `test_integration.py` for examples. The tests should be easy to read and understand. + +### Pull request +Before creating a pull request, ensure that you run `scripts/lint.sh` and `scripts/tests.sh`. All linters and tests should pass. In the pull request, provide a high-level description of your changes and step-by-step instructions on how to test them. Include any necessary commands. + +### Code review +Once you've submitted your pull request, it's time for code review. Be patient and open to feedback from the reviewers. Address any concerns they may have and work collaboratively to improve the code. Together, we can make ShellGPT an even better project. + +Thank you once again for your contribution! We're excited to have you on board. \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index 31d1228..af47add 100644 --- a/Dockerfile +++ b/Dockerfile @@ -17,4 +17,3 @@ USER app VOLUME /tmp/shell_gpt ENTRYPOINT ["sgpt"] - diff --git a/pre-push.sh b/pre-push.sh deleted file mode 100755 index ad882fb..0000000 --- a/pre-push.sh +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/env bash - -chmod +x "$PWD/pre-push.sh" -ln -sf "$PWD/pre-push.sh" .git/hooks/pre-push - -# Check if pylint is installed -if ! command -v pylint > /dev/null; then - echo "pylint is not installed. Install it with 'pip install pylint'" - exit 1 -fi - -# Check if black is installed -if ! command -v black > /dev/null; then - echo "black is not installed. Install it with 'pip install black'" - exit 1 -fi - -echo 'Executing pre-push hook.' - -if [ -f "$PWD/venv/bin/activate" ]; then - source $PWD/venv/bin/activate -fi - -if black ./sgpt ./tests --check --target-version py310 -then - echo 'Black passed ✅' -else - echo 'Black failed ❌' - echo 'RUN: black ./sgpt ./tests --target-version py310' - exit 1 -fi - -if pylint \ - ./sgpt \ - ./tests \ - --disable=fixme \ - --disable=cyclic-import \ - --disable=useless-import-alias \ - --disable=missing-function-docstring \ - --disable=missing-module-docstring \ - --disable=missing-class-docstring \ - --disable=too-many-function-args \ - --ignore=venv -then - echo 'Pylint passed ✅' -else - echo 'Pylint failed ❌' - exit 1 -fi - -if python -m unittest tests/unittests.py -then - echo 'Unittests passed ✅' -else - echo 'Unittests failed ❌' - exit 1 -fi - -echo 'Well done.' diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..5d68c88 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,95 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "shell_gpt" +description = "A command-line productivity tool powered by OpenAI GPT models, will help you accomplish your tasks faster and more efficiently." +keywords = ["shell", "gpt", "openai", "cli", "productivity", "cheet-sheet"] +readme = "README.md" +license = "MIT" +requires-python = ">=3.6" +authors = [{ name = "Farkhod Sadykov", email = "farkhod@sadykov.dev" }] +dynamic = ["version"] +classifiers = [ + "Operating System :: OS Independent", + "Topic :: Software Development", + "License :: OSI Approved :: MIT License", + "Intended Audience :: Information Technology", + "Intended Audience :: System Administrators", + "Intended Audience :: Developers", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.6", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", +] +dependencies = [ + "requests >= 2.28.2, < 3.0.0", + "typer >= 0.7.0, < 1.0.0", + "click >= 7.1.1, < 9.0.0", + "rich >= 10.11.0, < 13.0.0", + "distro >= 1.8.0, < 2.0.0", + 'pyreadline3 >= 3.4.1, < 4.0.0; sys_platform == "win32"', +] + +[project.scripts] +sgpt = "sgpt:cli" + +[project.urls] +homepage = "https://github.com/ther1d/shell_gpt" +repository = "https://github.com/ther1d/shell_gpt" +documentation = "https://github.com/TheR1D/shell_gpt/blob/main/README.md" + +[project.optional-dependencies] +test = [ + "pytest >= 7.2.2, < 8.0.0", + "requests-mock[fixture] >= 1.10.0, < 2.0.0", + "isort >= 5.12.0, < 6.0.0", + "black == 23.1.0", + "mypy == 1.1.1", + "types-requests == 2.28.11.17", +] +dev = [ + "ruff == 0.0.256", + "pre-commit >= 3.1.1, < 4.0.0", +] + +[tool.hatch.version] +path = "sgpt/__init__.py" + +[tool.hatch.build.targets.wheel] +only-include = ["sgpt"] + +[tool.hatch.build.targets.sdist] +only-include = [ + "sgpt", + "tests", + "README.md", + "LICENSE", + "pyproject.toml", +] + +[tool.isort] +profile = "black" +skip = "__init__.py" + +[tool.mypy] +strict = true + +[tool.ruff] +select = [ + "E", # pycodestyle errors. + "W", # pycodestyle warnings. + "F", # pyflakes. + "C", # flake8-comprehensions. + "B", # flake8-bugbear. +] +ignore = [ + "E501", # line too long, handled by black. + "C901", # too complex. + "B008", # do not perform function calls in argument defaults. +] diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index 27fdd16..0000000 --- a/requirements.txt +++ /dev/null @@ -1,6 +0,0 @@ -typer~=0.7.0 -requests~=2.28.2 -rich==13.3.1 -click~=8.1.3 -distro~=1.8.0 -setuptools==67.6.0 diff --git a/scripts/format.sh b/scripts/format.sh new file mode 100644 index 0000000..10a6e22 --- /dev/null +++ b/scripts/format.sh @@ -0,0 +1,6 @@ +#!/bin/sh -e +set -x + +ruff sgpt tests scripts --fix +black sgpt tests scripts +isort sgpt tests scripts diff --git a/scripts/lint.sh b/scripts/lint.sh new file mode 100644 index 0000000..3bc697d --- /dev/null +++ b/scripts/lint.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash + +set -e +set -x + +mypy sgpt +ruff sgpt tests scripts +black sgpt tests --check +isort sgpt tests scripts --check-only diff --git a/scripts/test.sh b/scripts/test.sh new file mode 100644 index 0000000..c30bbb5 --- /dev/null +++ b/scripts/test.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash + +set -e +set -x + +# shellcheck disable=SC2068 +pytest tests ${@} diff --git a/setup.py b/setup.py deleted file mode 100644 index c9a9399..0000000 --- a/setup.py +++ /dev/null @@ -1,29 +0,0 @@ -from setuptools import setup, find_packages - -# pylint: disable=consider-using-with -setup( - name="shell_gpt", - version="0.8.8", - packages=find_packages(), - install_requires=[ - "typer~=0.7.0", - "requests~=2.28.2", - "rich==13.3.1", - "distro~=1.8.0", - ], - extras_require={ - ':sys_platform == "win32"': ["pyreadline3"] - }, - entry_points={ - "console_scripts": ["sgpt = sgpt:cli"], - }, - author="Farkhod Sadykov", - author_email="farkhod@sadykov.dev", - description=( - "A command-line productivity tool powered by ChatGPT, " - "will help you accomplish your tasks faster and more efficiently." - ), - long_description=open("README.md").read(), - long_description_content_type="text/markdown", - url="https://github.com/ther1d/shell_gpt", -) diff --git a/sgpt/__init__.py b/sgpt/__init__.py index 2260890..3b35d9b 100644 --- a/sgpt/__init__.py +++ b/sgpt/__init__.py @@ -1,4 +1,4 @@ -from .config import config as config +from .config import cfg as cfg from .cache import Cache as Cache from .client import OpenAIClient as OpenAIClient from .handlers.chat_handler import ChatHandler as ChatHandler @@ -6,5 +6,7 @@ from .handlers.default_handler import DefaultHandler as DefaultHandler from .handlers.repl_handler import ReplHandler as ReplHandler from . import utils as utils from .app import main as main -from .app import entry_point as cli +from .app import entry_point as cli # noqa: F401 from . import make_prompt as make_prompt + +__version__ = "0.8.9" diff --git a/sgpt/app.py b/sgpt/app.py index a0e3c41..a367103 100644 --- a/sgpt/app.py +++ b/sgpt/app.py @@ -9,27 +9,27 @@ shell commands directly from the interface. API Key is stored locally for easy use in future runs. """ -import sys - # To allow users to use arrow keys in the REPL. -import readline # pylint: disable=unused-import +import readline # noqa: F401 +import sys import typer # Click is part of typer. -from click import MissingParameter, BadArgumentUsage -from sgpt import ChatHandler, DefaultHandler, ReplHandler, OpenAIClient, config -from sgpt.utils import get_edited_prompt, run_command, ModelOptions +from click import BadArgumentUsage, MissingParameter + +from sgpt import ChatHandler, DefaultHandler, OpenAIClient, ReplHandler, cfg +from sgpt.utils import ModelOptions, get_edited_prompt, run_command -def main( # pylint: disable=too-many-arguments,too-many-locals +def main( prompt: str = typer.Argument( None, show_default=False, help="The prompt to generate completions for.", ), model: ModelOptions = typer.Option( - ModelOptions(config.get("DEFAULT_MODEL")).value, + ModelOptions(cfg.get("DEFAULT_MODEL")).value, help="OpenAI GPT model to use.", ), temperature: float = typer.Option( @@ -74,13 +74,13 @@ def main( # pylint: disable=too-many-arguments,too-many-locals help="Start a REPL (Read–eval–print loop) session.", rich_help_panel="Chat Options", ), - show_chat: str = typer.Option( # pylint: disable=W0613 + show_chat: str = typer.Option( None, help="Show all messages from provided chat id.", callback=ChatHandler.show_messages_callback, rich_help_panel="Chat Options", ), - list_chat: bool = typer.Option( # pylint: disable=W0613 + list_chat: bool = typer.Option( False, help="List all existing chat ids.", callback=ChatHandler.list_ids, @@ -107,8 +107,8 @@ def main( # pylint: disable=too-many-arguments,too-many-locals if editor: prompt = get_edited_prompt() - api_host = config.get("OPENAI_API_HOST") - api_key = config.get("OPENAI_API_KEY") + api_host = cfg.get("OPENAI_API_HOST") + api_key = cfg.get("OPENAI_API_KEY") client = OpenAIClient(api_host, api_key) if repl: diff --git a/sgpt/cache.py b/sgpt/cache.py index 699b755..55c07e9 100644 --- a/sgpt/cache.py +++ b/sgpt/cache.py @@ -1,10 +1,10 @@ import json from hashlib import md5 from pathlib import Path -from typing import Callable +from typing import Any, Callable, Generator, no_type_check -class Cache: # pylint: disable=too-few-public-methods +class Cache: """ Decorator class that adds caching functionality to a function. """ @@ -19,7 +19,7 @@ class Cache: # pylint: disable=too-few-public-methods self.cache_path = cache_path self.cache_path.mkdir(parents=True, exist_ok=True) - def __call__(self, func: Callable) -> Callable: + def __call__(self, func: Callable[..., Any]) -> Callable[..., Any]: """ The Cache decorator. @@ -27,7 +27,7 @@ class Cache: # pylint: disable=too-few-public-methods :return: Wrapped function with caching. """ - def wrapper(*args, **kwargs): + def wrapper(*args: Any, **kwargs: Any) -> Generator[str, None, None]: # Exclude self instance from hashing. cache_key = md5(json.dumps((args[1:], kwargs)).encode("utf-8")).hexdigest() cache_file = self.cache_path / cache_key @@ -40,10 +40,11 @@ class Cache: # pylint: disable=too-few-public-methods result += i yield i cache_file.write_text(result) - self._delete_oldest_files(self.length) + self._delete_oldest_files(self.length) # type: ignore return wrapper + @no_type_check def _delete_oldest_files(self, max_files: int) -> None: """ Class method to delete the oldest cached files in the CACHE_DIR folder. diff --git a/sgpt/client.py b/sgpt/client.py index 6d39727..90220f5 100644 --- a/sgpt/client.py +++ b/sgpt/client.py @@ -1,16 +1,14 @@ import json from pathlib import Path -from typing import List, Dict, Mapping +from typing import Dict, Generator, List import requests -from sgpt import config, Cache +from sgpt import Cache, cfg - -# pylint: skip-file -CACHE_LENGTH = int(config.get("CACHE_LENGTH")) -CACHE_PATH = Path(config.get("CACHE_PATH")) -REQUEST_TIMEOUT = int(config.get("REQUEST_TIMEOUT")) +CACHE_LENGTH = int(cfg.get("CACHE_LENGTH")) +CACHE_PATH = Path(cfg.get("CACHE_PATH")) +REQUEST_TIMEOUT = int(cfg.get("REQUEST_TIMEOUT")) class OpenAIClient: @@ -23,11 +21,11 @@ class OpenAIClient: @cache def _request( self, - messages: List[Mapping[str, str]], + messages: List[Dict[str, str]], model: str = "gpt-3.5-turbo", temperature: float = 1, top_probability: float = 1, - ) -> Dict: + ) -> Generator[str, None, None]: """ Make request to OpenAI ChatGPT API, read more: https://platform.openai.com/docs/api-reference/chat @@ -58,24 +56,24 @@ class OpenAIClient: # https://github.com/openai/openai-python/blob/237448dc072a2c062698da3f9f512fae38300c1c/openai/api_requestor.py#L98 for line in response.iter_lines(): data = line.lstrip(b"data: ").decode("utf-8") - if data == "[DONE]": + if data == "[DONE]": # type: ignore break if not data: continue - data = json.loads(data) - delta = data["choices"][0]["delta"] + data = json.loads(data) # type: ignore + delta = data["choices"][0]["delta"] # type: ignore if "content" not in delta: continue yield delta["content"] def get_completion( self, - messages: List[Mapping[str, str]], + messages: List[Dict[str, str]], model: str = "gpt-3.5-turbo", temperature: float = 1, top_probability: float = 1, caching: bool = True, - ) -> str: + ) -> Generator[str, None, None]: """ Generates single completion for prompt (message). diff --git a/sgpt/config.py b/sgpt/config.py index 1e95af9..0fb8556 100644 --- a/sgpt/config.py +++ b/sgpt/config.py @@ -1,8 +1,8 @@ import os -from pathlib import Path from getpass import getpass +from pathlib import Path from tempfile import gettempdir -from typing import Any, Optional +from typing import Any from click import UsageError @@ -30,7 +30,7 @@ DEFAULT_CONFIG = { } -class Config(dict): +class Config(dict): # type: ignore def __init__(self, config_path: Path, **defaults: Any): self.config_path = config_path @@ -56,20 +56,20 @@ class Config(dict): def _exists(self) -> bool: return self.config_path.exists() - def _write(self): + def _write(self) -> None: with open(self.config_path, "w", encoding="utf-8") as file: string_config = "" for key, value in self.items(): string_config += f"{key}={value}\n" file.write(string_config) - def _read(self): + def _read(self) -> None: with open(self.config_path, "r", encoding="utf-8") as file: for line in file: key, value = line.strip().split("=") self[key] = value - def get(self, key: str) -> Optional[str]: + def get(self, key: str) -> str: # type: ignore # Prioritize environment variables over config file. value = os.getenv(key) or super().get(key) if not value: @@ -77,4 +77,4 @@ class Config(dict): return value -config = Config(CONFIG_PATH, **DEFAULT_CONFIG) +cfg = Config(CONFIG_PATH, **DEFAULT_CONFIG) diff --git a/sgpt/handlers/chat_handler.py b/sgpt/handlers/chat_handler.py index 8be5ebb..fe99efe 100644 --- a/sgpt/handlers/chat_handler.py +++ b/sgpt/handlers/chat_handler.py @@ -1,16 +1,16 @@ import json from pathlib import Path -from typing import List, Dict, Optional, Callable, Generator +from typing import Any, Callable, Dict, Generator, List, Optional import typer from click import BadArgumentUsage -from sgpt import OpenAIClient, config, make_prompt -from sgpt.utils import CompletionModes +from sgpt import OpenAIClient, cfg, make_prompt from sgpt.handlers.handler import Handler +from sgpt.utils import CompletionModes -CHAT_CACHE_LENGTH = int(config.get("CHAT_CACHE_LENGTH")) -CHAT_CACHE_PATH = Path(config.get("CHAT_CACHE_PATH")) +CHAT_CACHE_LENGTH = int(cfg.get("CHAT_CACHE_LENGTH")) +CHAT_CACHE_PATH = Path(cfg.get("CHAT_CACHE_PATH")) class ChatSession: @@ -31,7 +31,7 @@ class ChatSession: self.storage_path = storage_path self.storage_path.mkdir(parents=True, exist_ok=True) - def __call__(self, func: Callable) -> Callable: + def __call__(self, func: Callable[..., Any]) -> Callable[..., Any]: """ The Cache decorator. @@ -39,7 +39,7 @@ class ChatSession: :return: Wrapped function with chat caching. """ - def wrapper(*args, **kwargs): + def wrapper(*args: Any, **kwargs: Any) -> Generator[str, None, None]: chat_id = kwargs.pop("chat_id", None) messages = kwargs["messages"] if not chat_id: @@ -58,29 +58,29 @@ class ChatSession: return wrapper - def _read(self, chat_id: str) -> List[Dict]: + def _read(self, chat_id: str) -> List[Dict[str, str]]: file_path = self.storage_path / chat_id if not file_path.exists(): return [] parsed_cache = json.loads(file_path.read_text()) return parsed_cache if isinstance(parsed_cache, list) else [] - def _write(self, messages: List[Dict], chat_id: str): + def _write(self, messages: List[Dict[str, str]], chat_id: str) -> None: file_path = self.storage_path / chat_id json.dump(messages[-self.length :], file_path.open("w")) - def invalidate(self, chat_id: str): + def invalidate(self, chat_id: str) -> None: file_path = self.storage_path / chat_id file_path.unlink(missing_ok=True) - def get_messages(self, chat_id): + def get_messages(self, chat_id: str) -> List[str]: messages = self._read(chat_id) return [f"{message['role']}: {message['content']}" for message in messages] def exists(self, chat_id: Optional[str]) -> bool: - return chat_id and bool(self._read(chat_id)) + return bool(chat_id and bool(self._read(chat_id))) - def list(self): + def list(self) -> List[Path]: # Get all files in the folder. files = self.storage_path.glob("*") # Sort files by last modification time in ascending order. @@ -90,7 +90,7 @@ class ChatSession: class ChatHandler(Handler): chat_session = ChatSession(CHAT_CACHE_LENGTH, CHAT_CACHE_PATH) - def __init__( # pylint: disable=too-many-arguments + def __init__( self, client: OpenAIClient, chat_id: str, @@ -111,7 +111,7 @@ class ChatHandler(Handler): self.validate() @classmethod - def list_ids(cls, value) -> None: + def list_ids(cls, value: str) -> None: if not value: return # Prints all existing chat IDs to the console. @@ -127,20 +127,20 @@ class ChatHandler(Handler): def is_shell_chat(self) -> bool: # TODO: Should be optimized for REPL mode. chat_history = self.chat_session.get_messages(self.chat_id) - return chat_history and chat_history[0].endswith("###\nCommand:") + return bool(chat_history and chat_history[0].endswith("###\nCommand:")) @property def is_code_chat(self) -> bool: chat_history = self.chat_session.get_messages(self.chat_id) - return chat_history and chat_history[0].endswith("###\nCode:") + return bool(chat_history and chat_history[0].endswith("###\nCode:")) @property def is_default_chat(self) -> bool: chat_history = self.chat_session.get_messages(self.chat_id) - return chat_history and chat_history[0].endswith("###") + return bool(chat_history and chat_history[0].endswith("###")) @classmethod - def show_messages_callback(cls, chat_id) -> None: + def show_messages_callback(cls, chat_id: str) -> None: if not chat_id: return cls.show_messages(chat_id) @@ -193,8 +193,8 @@ class ChatHandler(Handler): ) @chat_session - def get_completion( # pylint: disable=arguments-differ + def get_completion( self, - **kwargs, - ) -> Generator: + **kwargs: Any, + ) -> Generator[str, None, None]: yield from super().get_completion(**kwargs) diff --git a/sgpt/handlers/default_handler.py b/sgpt/handlers/default_handler.py index 77a89a8..cb0b7f8 100644 --- a/sgpt/handlers/default_handler.py +++ b/sgpt/handlers/default_handler.py @@ -1,11 +1,12 @@ from pathlib import Path -from sgpt import OpenAIClient, config, make_prompt +from sgpt import OpenAIClient, cfg, make_prompt from sgpt.utils import CompletionModes + from .handler import Handler -CHAT_CACHE_LENGTH = int(config.get("CHAT_CACHE_LENGTH")) -CHAT_CACHE_PATH = Path(config.get("CHAT_CACHE_PATH")) +CHAT_CACHE_LENGTH = int(cfg.get("CHAT_CACHE_LENGTH")) +CHAT_CACHE_PATH = Path(cfg.get("CHAT_CACHE_PATH")) class DefaultHandler(Handler): @@ -21,7 +22,7 @@ class DefaultHandler(Handler): self.mode = CompletionModes.get_mode(shell, code) self.model = model - def make_prompt(self, prompt) -> str: + def make_prompt(self, prompt: str) -> str: prompt = prompt.strip() return make_prompt.initial( prompt, diff --git a/sgpt/handlers/handler.py b/sgpt/handlers/handler.py index 2ad956d..259cd84 100644 --- a/sgpt/handlers/handler.py +++ b/sgpt/handlers/handler.py @@ -1,27 +1,26 @@ -from typing import List, Dict, Generator +from typing import Any, Dict, Generator, List import typer -from sgpt import OpenAIClient -from sgpt import config +from sgpt import OpenAIClient, cfg class Handler: def __init__(self, client: OpenAIClient) -> None: self.client = client - self.color = config.get("DEFAULT_COLOR") + self.color = cfg.get("DEFAULT_COLOR") - def make_prompt(self, prompt) -> str: + def make_prompt(self, prompt: str) -> str: raise NotImplementedError - def get_completion( # pylint: disable=too-many-arguments + def get_completion( self, messages: List[Dict[str, str]], model: str = "gpt-3.5-turbo", temperature: float = 1, top_probability: float = 1, caching: bool = True, - ) -> Generator: + ) -> Generator[str, None, None]: yield from self.client.get_completion( messages, model, @@ -30,7 +29,7 @@ class Handler: caching=caching, ) - def handle(self, prompt: str, **kwargs) -> str: + def handle(self, prompt: str, **kwargs: Any) -> str: prompt = self.make_prompt(prompt) messages = [{"role": "user", "content": prompt}] full_completion = "" diff --git a/sgpt/handlers/repl_handler.py b/sgpt/handlers/repl_handler.py index 5898bdd..f6c7ce3 100644 --- a/sgpt/handlers/repl_handler.py +++ b/sgpt/handlers/repl_handler.py @@ -1,15 +1,16 @@ -import typer +from typing import Any +import typer from rich import print as rich_print from rich.rule import Rule -from sgpt.handlers.chat_handler import ChatHandler from sgpt.client import OpenAIClient +from sgpt.handlers.chat_handler import ChatHandler from sgpt.utils import CompletionModes, run_command class ReplHandler(ChatHandler): - def __init__( # pylint: disable=useless-parent-delegation,too-many-arguments + def __init__( self, client: OpenAIClient, chat_id: str, @@ -19,7 +20,7 @@ class ReplHandler(ChatHandler): ): super().__init__(client, chat_id, shell, code, model) - def handle(self, prompt: str, **kwargs) -> None: + def handle(self, prompt: str, **kwargs: Any) -> None: # type: ignore if self.initiated: rich_print(Rule(title="Chat History", style="bold magenta")) self.show_messages(self.chat_id) diff --git a/sgpt/make_prompt.py b/sgpt/make_prompt.py index 8a73596..aaa8f0f 100644 --- a/sgpt/make_prompt.py +++ b/sgpt/make_prompt.py @@ -1,8 +1,8 @@ import platform from os import getenv, pathsep from os.path import basename -from distro import name as distro_name +from distro import name as distro_name SHELL_PROMPT = """### Provide only {shell} commands for {os} without any description. diff --git a/sgpt/utils.py b/sgpt/utils.py index fb59c5a..02a5a7c 100644 --- a/sgpt/utils.py +++ b/sgpt/utils.py @@ -1,11 +1,9 @@ import os +import platform import shlex - from enum import Enum from tempfile import NamedTemporaryFile -import platform - from click import BadParameter @@ -21,7 +19,7 @@ class CompletionModes(Enum): CODE = "code" @classmethod - def get_mode(cls, shell, code) -> "CompletionModes": + def get_mode(cls, shell: bool, code: bool) -> "CompletionModes": if shell: return CompletionModes.SHELL if code: diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/integration_tests.py b/tests/test_integration.py similarity index 97% rename from tests/integration_tests.py rename to tests/test_integration.py index 2479d22..a270010 100644 --- a/tests/integration_tests.py +++ b/tests/test_integration.py @@ -1,26 +1,25 @@ """ This test module will execute real commands using shell. This means it will call sgpt.py with command line arguments. -Make sure you have your API key in place ~/.config/shell_gpt/.sgptrc +Make sure you have your API key in place ~/.cfg/shell_gpt/.sgptrc or ENV variable OPENAI_API_KEY. It is useful for quick tests, saves a bit time. """ import json -import subprocess import os - -from time import sleep +import subprocess from pathlib import Path -from unittest import TestCase -from unittest.mock import patch, ANY from tempfile import NamedTemporaryFile +from time import sleep +from unittest import TestCase +from unittest.mock import ANY, patch from uuid import uuid4 import typer from typer.testing import CliRunner -from sgpt import main, config, OpenAIClient +from sgpt import OpenAIClient, cfg, main from sgpt.handlers.handler import Handler runner = CliRunner() @@ -86,7 +85,7 @@ class TestShellGpt(TestCase): try: compile(result.output, file.name, "exec") except SyntaxError: - assert False, "The output is not valid Python code." + assert False, "The output is not valid Python code." # noqa: B011 file.seek(0) file.truncate() file.write(result.output) @@ -231,7 +230,7 @@ class TestShellGpt(TestCase): assert ">>> Sort by name" in result.stdout assert "ls" in result.stdout assert "ls | sort" in result.stdout - chat_storage = config.get("CHAT_CACHE_PATH") + chat_storage = cfg.get("CHAT_CACHE_PATH") tmp_chat = Path(chat_storage) / "temp" chat_messages = json.loads(tmp_chat.read_text()) # TODO: Implement same check in chat mode tests. @@ -262,7 +261,7 @@ class TestShellGpt(TestCase): assert f">>> {inputs[1]}" in result.stdout assert "localhost:443" in result.stdout - chat_storage = config.get("CHAT_CACHE_PATH") + chat_storage = cfg.get("CHAT_CACHE_PATH") tmp_chat = Path(chat_storage) / dict_arguments["--repl"] chat_messages = json.loads(tmp_chat.read_text()) assert chat_messages[0]["content"].startswith("###") @@ -313,7 +312,7 @@ class TestShellGpt(TestCase): assert result.exit_code == 0 def test_color_output(self): - color = config.get("DEFAULT_COLOR") + color = cfg.get("DEFAULT_COLOR") handler = Handler(OpenAIClient("test", "test")) assert handler.color == color os.environ["DEFAULT_COLOR"] = "red" diff --git a/tests/unittests.py b/tests/test_unit.py similarity index 96% rename from tests/unittests.py rename to tests/test_unit.py index cf62186..462acc5 100644 --- a/tests/unittests.py +++ b/tests/test_unit.py @@ -1,12 +1,13 @@ import os import unittest -import requests_mock + import requests +import requests_mock from sgpt import OpenAIClient -class TestMain(unittest.TestCase): # pylint: disable=too-many-instance-attributes +class TestMain(unittest.TestCase): API_HOST = os.getenv("OPENAI_HOST", "https://api.openai.com") API_URL = f"{API_HOST}/v1/chat/completions" # TODO: Fix tests.