Skip to content

Commit

Permalink
Переезд на ruff и ruff format (#625)
Browse files Browse the repository at this point in the history
  • Loading branch information
MarshalX authored Nov 17, 2023
1 parent fecad89 commit 07b30cb
Show file tree
Hide file tree
Showing 130 changed files with 538 additions and 539 deletions.
25 changes: 0 additions & 25 deletions .github/workflows/black.yml

This file was deleted.

29 changes: 29 additions & 0 deletions .github/workflows/ruff.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
name: Linter and code style check

on: [ pull_request ]

permissions:
contents: read

jobs:
ruff:
runs-on: ubuntu-latest
steps:
- name: Checkout repository.
uses: actions/checkout@v4

- name: Setup Python.
uses: actions/setup-python@v4
with:
python-version: 3.7

- name: Run linter check.
uses: chartboost/ruff-action@v1
with:
version: 0.1.6

- name: Run code style check.
uses: chartboost/ruff-action@v1
with:
version: 0.1.6
args: format --check
14 changes: 7 additions & 7 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,17 +39,17 @@ PR'ы должны быть сделаны в `main` ветку. Определ

## Форматирование кода (стиль написания)

В проекте используется `black`. Не забывайте перед публикацией отформатировать код и проверить его на работоспособность. Используются одинарные кавычки. Запускайте `black` с конфигом из основной директории:
В проекте используется `ruff`. Не забывайте перед публикацией отформатировать код и проверить его на работоспособность. Используются одинарные кавычки.

Запуск линтера:
```shell
black --config=black.toml yandex_music
ruff .
```

или

Запуск форматера:
```shell
make black
```
ruff format .
````

## Создание новых моделей

Expand Down Expand Up @@ -94,4 +94,4 @@ _Используйте WSL если вы на Windows._
make all
```
Выполнит за вас black для основного модуля и тестов, сгенерирует асинхронную версию клиента, сгенерирует camel case псевдонимы.
Выполнит за вас ruff и ruff format, сгенерирует асинхронную версию клиента, сгенерирует camel case псевдонимы.
16 changes: 5 additions & 11 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
# makefile for Yandex Music project

black:
black --config=black.toml yandex_music
ruff:
ruff . --fix

black_test:
black --config=black.toml tests
ruff_format:
ruff format .

gen_async:
python generate_async_version.py
Expand All @@ -15,17 +15,11 @@ gen_alias:
gen:
make gen_async && make gen_alias

b:
make black

bt:
make black_test

g:
make gen

all:
make g && make b && make bt
make g && make ruff && make ruff_format

a:
make all
21 changes: 0 additions & 21 deletions black.toml

This file was deleted.

2 changes: 1 addition & 1 deletion docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@

myst_heading_anchors = 4
# https://myst-parser.readthedocs.io/en/latest/syntax/optional.html?highlight=header-anchors#code-fences-using-colons
myst_enable_extensions = ["colon_fence"]
myst_enable_extensions = ['colon_fence']
# TODO add substitution https://myst-parser.readthedocs.io/en/latest/syntax/optional.html?highlight=header-anchors#substitutions-with-jinja2

# -- Options for HTML output -------------------------------------------------
Expand Down
1 change: 0 additions & 1 deletion examples/chart.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

from yandex_music import Client


CHART_ID = 'world'
TOKEN = os.environ.get('TOKEN')

Expand Down
5 changes: 3 additions & 2 deletions examples/daily_playlist_updater.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import sys
import datetime
import sys

from yandex_music.client import Client

# Help text
Expand All @@ -19,7 +20,7 @@

# Check if we don't need to update it
if DailyPlaylist.play_counter.updated:
modifiedDate = datetime.datetime.strptime(DailyPlaylist.modified, "%Y-%m-%dT%H:%M:%S%z").date()
modifiedDate = datetime.datetime.strptime(DailyPlaylist.modified, '%Y-%m-%dT%H:%M:%S%z').date()
if datetime.datetime.now().date() == modifiedDate:
print('\x1b[6;30;43m' + 'Looks like it has been already updated today' + '\x1b[0m')
quit()
Expand Down
1 change: 0 additions & 1 deletion examples/like_and_dislike.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

from yandex_music import Client


TOKEN = os.environ.get('TOKEN')
ALBUM_ID = 2832563

Expand Down
1 change: 0 additions & 1 deletion examples/lyrics_playing_track.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from yandex_music import Client
from yandex_music.exceptions import NotFoundError


TOKEN = os.environ.get('TOKEN')

client = Client(TOKEN).init()
Expand Down
14 changes: 7 additions & 7 deletions examples/player.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
#!/usr/bin/env python3
import sys
import argparse
import re
from time import sleep
from subprocess import call
import sys
from pathlib import Path
from subprocess import call
from time import sleep
from typing import List

from yandex_music import Client
Expand All @@ -22,7 +22,7 @@
parser.add_argument(
'--token', default=DEFAULT_CACHE_FOLDER / CONFIG_NAME, help='YM API token as string or path to file'
)
parser.add_argument('--no-save-token', action='store_true', help='do\'nt save token in cache folder')
parser.add_argument('--no-save-token', action='store_true', help="do'nt save token in cache folder")
parser.add_argument('--cache-folder', type=Path, default=DEFAULT_CACHE_FOLDER, help='cached tracks folder')
parser.add_argument('--audio-player', default='cvlc', help='player to use')
parser.add_argument(
Expand All @@ -43,7 +43,7 @@
print(args)
sys.exit()

if type(args.token) is str and re.match(r'^[A-Za-z0-9]{39}$', args.token):
if isinstance(args.token, str) and re.match(r'^[A-Za-z0-9]{39}$', args.token):
if not args.no_save_token:
parser.get_default('token').write_text(args.token)
else:
Expand All @@ -62,7 +62,7 @@
if args.playlist == 'user':
user_playlists = client.users_playlists_list()
if not args.playlist_name:
print('specify --playlist-name', list(p.title for p in user_playlists))
print('specify --playlist-name', [p.title for p in user_playlists])
sys.exit(1)
playlist = next((p for p in user_playlists if p.title == args.playlist_name), None)
if playlist is None:
Expand All @@ -82,7 +82,7 @@
shuffle(tracks.tracks)

error_count = 0
for (i, short_track) in enumerate(tracks):
for i, short_track in enumerate(tracks):
if args.skip and args.skip > i:
continue

Expand Down
2 changes: 1 addition & 1 deletion examples/proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

try:
if not yandex_music_token:
raise YandexMusicError()
raise YandexMusicError

# подключаемся без прокси для получения информации об аккаунте (доступно из других стран)
client = Client(yandex_music_token, request=Request()).init()
Expand Down
7 changes: 3 additions & 4 deletions examples/radio_example/radio.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def __send_start_radio(self, batch_id):
def __send_play_start_track(self, track, play_id):
total_seconds = track.duration_ms / 1000
self.client.play_audio(
from_="desktop_win-home-playlist_of_the_day-playlist-default",
from_='desktop_win-home-playlist_of_the_day-playlist-default',
track_id=track.id,
album_id=track.albums[0].id,
play_id=play_id,
Expand All @@ -77,7 +77,7 @@ def __send_play_end_track(self, track, play_id):
played_seconds = track.duration_ms / 1000
total_seconds = track.duration_ms / 1000
self.client.play_audio(
from_="desktop_win-home-playlist_of_the_day-playlist-default",
from_='desktop_win-home-playlist_of_the_day-playlist-default',
track_id=track.id,
album_id=track.albums[0].id,
play_id=play_id,
Expand All @@ -91,8 +91,7 @@ def __send_play_end_radio(self, track, batch_id):
self.client.rotor_station_feedback_track_finished(
station=self.station_id, track_id=track.id, total_played_seconds=played_seconds, batch_id=batch_id
)
pass

@staticmethod
def __generate_play_id():
return "%s-%s-%s" % (int(random() * 1000), int(random() * 1000), int(random() * 1000))
return '%s-%s-%s' % (int(random() * 1000), int(random() * 1000), int(random() * 1000))
4 changes: 2 additions & 2 deletions examples/radio_example/radio_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
from random import random
from time import sleep

from yandex_music import Client

from radio import Radio

from yandex_music import Client

# API instance
client = Client(token='YOUR_TOKEN_HERE')

Expand Down
4 changes: 2 additions & 2 deletions examples/radio_example/stream_example.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from time import sleep

from yandex_music import Client

from radio import Radio

from yandex_music import Client

# API instance
client = Client(token='YOUR_API_KEY_HERE').init()

Expand Down
5 changes: 2 additions & 3 deletions examples/search.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from yandex_music import Client


client = Client().init()

type_to_name = {
Expand All @@ -15,7 +14,7 @@
}


def send_search_request_and_print_result(query):
def send_search_request_and_print_result(query): # noqa: C901
search_result = client.search(query)

text = [f'Результаты по запросу "{query}":', '']
Expand All @@ -35,7 +34,7 @@ def send_search_request_and_print_result(query):
elif type_ == 'artist':
best_result_text = best.name
elif type_ in ['album', 'podcast']:
best_result_text = best.title
best_result_text = best.title # noqa: SIM114
elif type_ == 'playlist':
best_result_text = best.title
elif type_ == 'video':
Expand Down
11 changes: 6 additions & 5 deletions generate_async_version.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
#!/usr/bin/env python3
import subprocess


DISCLAIMER = '# THIS IS AUTO GENERATED COPY OF client.py. DON\'T EDIT IN BY HANDS #'
DISCLAIMER = "# THIS IS AUTO GENERATED COPY OF client.py. DON'T EDIT IN BY HANDS #"
DISCLAIMER = f'{"#" * len(DISCLAIMER)}\n{DISCLAIMER}\n{"#" * len(DISCLAIMER)}\n\n'

REQUEST_METHODS = ('_request_wrapper', 'get', 'post', 'retrieve', 'download')
Expand All @@ -18,7 +17,7 @@ def gen_request(output_request_filename):
code = code.replace('resp.content', 'content')
code = code.replace(
'resp = requests.request(*args, **kwargs)',
f'async with aiohttp.request(*args, **kwargs) as _resp:\n{" " * 16}resp = _resp\n{" " * 16}content = await resp.content.read()',
f'async with aiohttp.request(*args, **kwargs) as _resp:\n{" " * 16}resp = _resp\n{" " * 16}content = await resp.content.read()', # noqa: E501
)

code = code.replace('except requests.Timeout', 'except asyncio.TimeoutError')
Expand All @@ -32,7 +31,7 @@ def gen_request(output_request_filename):
code = code.replace('proxies=self.proxies', 'proxy=self.proxy_url')
code = code.replace(
"kwargs['timeout'] = self._timeout",
f"kwargs['timeout'] = aiohttp.ClientTimeout(total=self._timeout)\n{' ' * 8}else:\n{' ' * 12}kwargs['timeout'] = aiohttp.ClientTimeout(total=kwargs['timeout'])",
f"kwargs['timeout'] = aiohttp.ClientTimeout(total=self._timeout)\n{' ' * 8}else:\n{' ' * 12}kwargs['timeout'] = aiohttp.ClientTimeout(total=kwargs['timeout'])", # noqa: E501
)

# download method
Expand Down Expand Up @@ -85,4 +84,6 @@ def gen_client(output_client_filename):
gen_client(client_filename)

for file in (request_filename, client_filename):
subprocess.run(['black', '--config', 'black.toml', file])
subprocess.run(['ruff', 'format', '--quiet', file]) # noqa: S603, S607
subprocess.run(['ruff', '--quiet', '--fix', file]) # noqa: S603, S607
subprocess.run(['ruff', 'format', '--quiet', file]) # noqa: S603, S607
Loading

0 comments on commit 07b30cb

Please sign in to comment.