Skip to content

Commit

Permalink
Autoformat
Browse files Browse the repository at this point in the history
  • Loading branch information
desbma committed Aug 8, 2021
1 parent 0201521 commit db12dc3
Show file tree
Hide file tree
Showing 10 changed files with 100 additions and 100 deletions.
16 changes: 8 additions & 8 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# https://pre-commit.com
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.4.0
rev: v4.0.1
hooks:
- id: check-added-large-files
- id: check-case-conflict
Expand All @@ -24,14 +24,14 @@ repos:
- --markdown-linebreak-ext=md

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.812
rev: v0.910
hooks:
- id: mypy
args:
- --ignore-missing-imports

- repo: https://gitlab.com/pycqa/flake8
rev: 3.8.4
rev: 3.9.2
hooks:
- id: flake8
args:
Expand All @@ -43,20 +43,20 @@ repos:
- --max-line-length=120

- repo: https://github.com/pycqa/pydocstyle
rev: 5.1.1
rev: 6.1.1
hooks:
- id: pydocstyle
args:
# http://www.pydocstyle.org/en/5.1.1/error_codes.html
- --ignore=D105,D107,D202,D210,D211,D212

- repo: https://github.com/shellcheck-py/shellcheck-py
rev: v0.7.1.1
rev: v0.7.2.1
hooks:
- id: shellcheck

- repo: https://github.com/pre-commit/mirrors-isort
rev: v5.7.0
rev: v5.9.3
hooks:
- id: isort
args:
Expand All @@ -65,15 +65,15 @@ repos:
- --profile=black

- repo: https://github.com/psf/black
rev: 20.8b1
rev: 21.7b0
hooks:
- id: black
language_version: python3
args:
- --line-length=120

- repo: https://github.com/pre-commit/mirrors-prettier
rev: v2.2.1
rev: v2.3.2
hooks:
- id: prettier
args:
Expand Down
36 changes: 18 additions & 18 deletions amg/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@

@contextlib.contextmanager
def date_locale_neutral():
""" Context manager to call with a neutral default locale. """
"""Context manager to call with a neutral default locale."""
loc = locale.getlocale(locale.LC_TIME)
locale.setlocale(locale.LC_TIME, "C")
try:
Expand All @@ -93,7 +93,7 @@ def date_locale_neutral():


def fetch_page(url: str, *, http_cache: Optional[web_cache.WebCache] = None) -> lxml.etree.XML:
""" Fetch page & parse it with LXML. """
"""Fetch page & parse it with LXML."""
if (http_cache is not None) and (url in http_cache):
logging.getLogger().info(f"Got data for URL {url!r} from cache")
page = http_cache[url]
Expand All @@ -109,7 +109,7 @@ def fetch_page(url: str, *, http_cache: Optional[web_cache.WebCache] = None) ->


def fetch_ressource(url: str, dest_filepath: str) -> None:
""" Fetch ressource, and write it to file. """
"""Fetch ressource, and write it to file."""
logging.getLogger().debug(f"Fetching {url!r}...")
headers = {"User-Agent": USER_AGENT}
with contextlib.closing(
Expand All @@ -122,7 +122,7 @@ def fetch_ressource(url: str, dest_filepath: str) -> None:


def parse_review_block(review: lxml.etree.Element) -> Optional[ReviewMetadata]:
""" Parse review block from main page and return a ReviewMetadata object. """
"""Parse review block from main page and return a ReviewMetadata object."""
tags = tuple(
t.split("-", 1)[1]
for t in review.get("class").split(" ")
Expand Down Expand Up @@ -164,7 +164,7 @@ def make_absolute_url(url: str) -> str:


def get_reviews() -> Iterable[ReviewMetadata]:
""" Parse site and yield ReviewMetadata objects. """
"""Parse site and yield ReviewMetadata objects."""
previous_review = None
for i in itertools.count():
url = REVIEW_URL
Expand All @@ -181,7 +181,7 @@ def get_reviews() -> Iterable[ReviewMetadata]:
def get_embedded_track(
page: lxml.etree.Element, http_cache: web_cache.WebCache
) -> Tuple[Optional[Sequence[str]], bool]:
""" Parse page and extract embedded track. """
"""Parse page and extract embedded track."""
urls: Optional[Sequence[str]] = None
audio_only = False
try:
Expand Down Expand Up @@ -236,11 +236,11 @@ def get_embedded_track(

class KnownReviews:

""" Persistent state for reviews to track played tracks. """
"""Persistent state for reviews to track played tracks."""

class DataIndex(enum.IntEnum):

""" Review metadata identifier. """
"""Review metadata identifier."""

LAST_PLAYED = 0
PLAY_COUNT = 1
Expand All @@ -262,11 +262,11 @@ def __init__(self):
del self.data[url]

def isKnownUrl(self, url: str) -> bool:
""" Return True if url if from a known review, False instead. """
"""Return True if url if from a known review, False instead."""
return url in self.data

def setLastPlayed(self, url: str) -> None:
""" Memorize a review's track has been read. """
"""Memorize a review's track has been read."""
try:
e = list(self.data[url])
except KeyError:
Expand All @@ -282,11 +282,11 @@ def setLastPlayed(self, url: str) -> None:
self.data[url] = tuple(e)

def getLastPlayed(self, url: str) -> datetime.datetime:
""" Return datetime of last review track playback. """
"""Return datetime of last review track playback."""
return self.data[url][self.__class__.DataIndex.LAST_PLAYED]

def getPlayCount(self, url: str) -> int:
""" Return number of time a track has been played. """
"""Return number of time a track has been played."""
try:
return self.data[url][self.__class__.DataIndex.PLAY_COUNT]
except IndexError:
Expand All @@ -295,7 +295,7 @@ def getPlayCount(self, url: str) -> int:


def get_cover_data(review: ReviewMetadata) -> bytes:
""" Fetch cover and return buffer of JPEG data. """
"""Fetch cover and return buffer of JPEG data."""
cover_url = review.cover_url if review.cover_url is not None else review.cover_thumbnail_url
cover_ext = os.path.splitext(urllib.parse.urlsplit(cover_url).path)[1][1:].lower()

Expand Down Expand Up @@ -324,7 +324,7 @@ def get_cover_data(review: ReviewMetadata) -> bytes:
def download_and_merge(
review: ReviewMetadata, track_urls: Sequence[str], tmp_dir: str, cover_filepath: str
) -> Optional[str]:
""" Download track, merge audio & album art, and return merged filepath. """
"""Download track, merge audio & album art, and return merged filepath."""
# fetch audio
with ytdl_tqdm.ytdl_tqdm(leave=False, mininterval=0.05, miniters=1) as ytdl_progress:
# https://github.com/ytdl-org/youtube-dl/blob/b8b622fbebb158db95edb05a8cc248668194b430/youtube_dl/YoutubeDL.py#L143-L323
Expand Down Expand Up @@ -397,7 +397,7 @@ def download_and_merge(


def backslash_unescape(s: str) -> str:
""" Revert backslash escaping. """
"""Revert backslash escaping."""
# https://stackoverflow.com/a/57192592
return codecs.decode(codecs.encode(s, "latin-1", "backslashreplace"), "unicode-escape")

Expand All @@ -410,7 +410,7 @@ def download_track(
tmp_dir: str,
tqdm_line_lock: threading.Lock,
):
""" Download a single track, and return its metadata. """
"""Download a single track, and return its metadata."""
with contextlib.ExitStack() as cm:
filename_template = (
f"{date_published.strftime('%Y%m%d')}. "
Expand Down Expand Up @@ -462,7 +462,7 @@ def download_track(
def download_audio(
review: ReviewMetadata, date_published: datetime.datetime, track_urls: Sequence[str], *, max_cover_size: int
) -> bool:
""" Download audio track(s) to file(s) in current directory, return True if success. """
"""Download audio track(s) to file(s) in current directory, return True if success."""
with tempfile.TemporaryDirectory(prefix="amg_") as tmp_dir:
# download
tqdm_line_locks = [threading.Lock() for _ in range(MAX_PARALLEL_DOWNLOADS)]
Expand Down Expand Up @@ -551,7 +551,7 @@ def download_audio(


def play(review: ReviewMetadata, track_urls: Sequence[str], *, merge_with_picture: bool) -> None:
""" Play it fucking loud. """
"""Play it fucking loud."""
# TODO support other players (vlc, avplay, ffplay...)
merge_with_picture = merge_with_picture and HAS_FFMPEG
if merge_with_picture:
Expand Down
4 changes: 2 additions & 2 deletions amg/colored_logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@

class ColoredFormatter(logging.Formatter):

""" Logging formatter coloring terminal output according to error criticity. """
"""Logging formatter coloring terminal output according to error criticity."""

def format(self, record):
""" See logging.Formatter.format. """
"""See logging.Formatter.format."""
message = super().format(record)
if sys.stderr.isatty() and not sys.platform.startswith("win32"):
try:
Expand Down
12 changes: 6 additions & 6 deletions amg/menu.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

class AmgMenu(cursesmenu.CursesMenu):

""" Custom menu to choose review/track. """
"""Custom menu to choose review/track."""

UserAction = enum.Enum("UserAction", ("DEFAULT", "OPEN_REVIEW", "DOWNLOAD_AUDIO"))

Expand Down Expand Up @@ -52,12 +52,12 @@ def process_user_input(self):
self.select()

def get_last_user_action(self):
""" Return last user action when item was selected. """
"""Return last user action when item was selected."""
return self.user_action

@staticmethod
def reviewsToStrings(reviews, known_reviews, http_cache):
""" Generate a list of string representations of reviews. """
"""Generate a list of string representations of reviews."""
lines = []
for i, review in enumerate(reviews):
try:
Expand Down Expand Up @@ -91,7 +91,7 @@ def reviewsToStrings(reviews, known_reviews, http_cache):

@staticmethod
def setupAndShow(mode, reviews, known_reviews, http_cache, selected_idx=None):
""" Set up and display interactive menu, return selected review index or None if exist requested. """
"""Set up and display interactive menu, return selected review index or None if exist requested."""
menu = AmgMenu(
reviews=reviews, known_reviews=known_reviews, http_cache=http_cache, mode=mode, selected_idx=selected_idx
)
Expand All @@ -102,14 +102,14 @@ def setupAndShow(mode, reviews, known_reviews, http_cache, selected_idx=None):

class ReviewItem(cursesmenu.items.SelectionItem):

""" Custom menu item (menu line), overriden to support several actions per item. """
"""Custom menu item (menu line), overriden to support several actions per item."""

def __init__(self, review, review_string, index, menu):
super().__init__(review_string, index, menu)
self.review = review

def action(self):
""" React to user action. """
"""React to user action."""
if self.menu.get_last_user_action() is AmgMenu.UserAction.OPEN_REVIEW:
webbrowser.open_new_tab(self.review.url)
self.should_exit = False
Expand Down
4 changes: 2 additions & 2 deletions amg/sanitize.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@


def sanitize_for_path(s: str) -> str:
""" Sanitize a string to be FAT/NTFS friendly when used in file path. """
"""Sanitize a string to be FAT/NTFS friendly when used in file path."""
s = s.translate(str.maketrans("/\\|*", "---x"))
s = "".join(c for c in unidecode.unidecode_expect_ascii(s) if c in VALID_PATH_CHARS)
s = s.strip()
Expand All @@ -45,7 +45,7 @@ def sanitize_for_path(s: str) -> str:


def normalize_tag_case(s: str) -> str:
""" Normalize case of an audio tag string. """
"""Normalize case of an audio tag string."""

def split_sep_char(w, c):
parts = w.split(c, 1)
Expand Down

0 comments on commit db12dc3

Please sign in to comment.