Skip to content

Commit

Permalink
apply black linting to whole project.
Browse files Browse the repository at this point in the history
  • Loading branch information
BrianPugh committed Dec 16, 2023
1 parent 0be1664 commit 1fdf804
Show file tree
Hide file tree
Showing 30 changed files with 390 additions and 366 deletions.
2 changes: 1 addition & 1 deletion .gitattributes
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@

*.rst text eol=lf
*.rst text eol=lf
2 changes: 1 addition & 1 deletion .github/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
interval: "weekly"
46 changes: 46 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
repos:
- repo: https://github.com/psf/black
rev: 23.12.0
hooks:
- id: black
args:
- "--line-length=120"
- "--target-version=py38"
- "--target-version=py39"
- "--target-version=py310"
- "--target-version=py311"
- "--target-version=py312"
types: [python]

- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
- id: check-added-large-files
- id: check-ast
- id: check-builtin-literals
- id: check-case-conflict
- id: check-docstring-first
- id: check-shebang-scripts-are-executable
- id: check-merge-conflict
- id: check-json
- id: check-toml
- id: check-xml
- id: check-yaml
- id: debug-statements
- id: destroyed-symlinks
- id: detect-private-key
- id: end-of-file-fixer
exclude: ^LICENSE|\.(html|csv|txt|svg|py)$
- id: pretty-format-json
args: ["--autofix", "--no-ensure-ascii", "--no-sort-keys"]
- id: requirements-txt-fixer
- id: trailing-whitespace
args: [--markdown-linebreak-ext=md]
exclude: \.(html|svg)$

- repo: https://github.com/codespell-project/codespell
rev: v2.2.6
additional_dependencies:
- tomli
hooks:
- id: codespell
2 changes: 1 addition & 1 deletion MANIFEST.in
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ graft src
graft littlefs
include README.rst
global-exclude src *.so __pycache__/*
global-exclude *.py[cod]
global-exclude *.py[cod]
2 changes: 1 addition & 1 deletion ci/build-wheels.sh
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,4 @@ for PYBIN in /opt/python/*/bin/; do
fi
"${PYBIN}/pip" install littlefs-python --no-index -f /io/wheels
"${PYBIN}/py.test" /io/test
done
done
25 changes: 12 additions & 13 deletions ci/download_release_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,27 @@
import os

HERE = os.path.dirname(__file__)
DIST_DIR = os.path.abspath(os.path.join(HERE, '..', 'dist'))
REPO = 'jrast/littlefs-python'
DIST_DIR = os.path.abspath(os.path.join(HERE, "..", "dist"))
REPO = "jrast/littlefs-python"

if not os.path.exists(DIST_DIR):
os.mkdir(DIST_DIR)

resp = requests.get('https://api.github.com/repos/%s/releases/latest' % REPO)
resp = requests.get("https://api.github.com/repos/%s/releases/latest" % REPO)

if resp.status_code != 200:
raise RuntimeError('Github API call failed!')
raise RuntimeError("Github API call failed!")

data = resp.json()

print('Release Tag:', data['tag_name'])
print("Release Tag:", data["tag_name"])

print('Assets:')
num_assets = len(data['assets'])
for nr, e in enumerate(data['assets'], 1):
print('(%2d/%2d) Downloading %s' % (nr, num_assets, e['name']))
r = requests.get(e['browser_download_url'], allow_redirects=True)
print("Assets:")
num_assets = len(data["assets"])
for nr, e in enumerate(data["assets"], 1):
print("(%2d/%2d) Downloading %s" % (nr, num_assets, e["name"]))
r = requests.get(e["browser_download_url"], allow_redirects=True)
if r.status_code != 200:
raise RuntimeError('Downloading %s failed!' % e['name'])
with open(os.path.join(DIST_DIR, e['name']), 'wb') as fh:
raise RuntimeError("Downloading %s failed!" % e["name"])
with open(os.path.join(DIST_DIR, e["name"]), "wb") as fh:
fh.write(r.content)

3 changes: 0 additions & 3 deletions docs/api/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,3 @@ littlefs.lfs module
.. automodule:: littlefs.lfs
:members:
:undoc-members:



2 changes: 1 addition & 1 deletion docs/cli.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
Command Line Interface
======================

.. argparse::
.. argparse::
:module: littlefs.__main__
:func: get_parser
:prog: littlefs-python
2 changes: 1 addition & 1 deletion docs/doc8.ini
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
[doc8]

max-line-length=99
max-line-length=99
2 changes: 1 addition & 1 deletion docs/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
sphinx~=7.2
sphinx-argparse~=0.4.0
sphinx-argparse~=0.4.0
2 changes: 1 addition & 1 deletion mypy.ini
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
check_untyped_defs = True

[mypy-pytest.*]
ignore_missing_imports = True
ignore_missing_imports = True
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
pytest>=4.0.0
tox>=3.14.0
pytest>=4.0.0
64 changes: 23 additions & 41 deletions src/littlefs/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,11 @@
if TYPE_CHECKING:
from .lfs import LFSStat


class LittleFS:
"""Littlefs file system"""

def __init__(self, context:Optional['UserContext']=None, mount=True, **kwargs) -> None:
def __init__(self, context: Optional["UserContext"] = None, mount=True, **kwargs) -> None:
self.cfg = lfs.LFSConfig(context=context, **kwargs)
self.fs = lfs.LFSFilesystem()

Expand All @@ -72,7 +73,7 @@ def block_count(self) -> int:
return self.fs.block_count

@property
def context(self) -> 'UserContext':
def context(self) -> "UserContext":
"""User context of the file system"""
return self.cfg.user_context

Expand Down Expand Up @@ -102,18 +103,12 @@ def fs_grow(self, block_count: int) -> int:

return lfs.fs_grow(self.fs, block_count)

def fs_stat(self) -> 'LFSFSStat':
def fs_stat(self) -> "LFSFSStat":
"""Get the status of the filesystem"""
return lfs.fs_stat(self.fs)

def open(
self,
fname: str,
mode='r',
buffering: int = -1,
encoding: str = None,
errors: str = None,
newline: str = None
self, fname: str, mode="r", buffering: int = -1, encoding: str = None, errors: str = None, newline: str = None
) -> IO:
"""Open a file.
Expand Down Expand Up @@ -174,25 +169,17 @@ def open(
exclusive_modes = (creating, reading, writing, appending)

if sum(int(m) for m in exclusive_modes) > 1:
raise ValueError(
"must have exactly one of create/read/write/append mode"
)
raise ValueError("must have exactly one of create/read/write/append mode")

if binary:
if encoding is not None:
raise ValueError(
"binary mode doesn't take an encoding argument"
)
raise ValueError("binary mode doesn't take an encoding argument")

if errors is not None:
raise ValueError(
"binary mode doesn't take an errors argument"
)
raise ValueError("binary mode doesn't take an errors argument")

if newline is not None:
raise ValueError(
"binary mode doesn't take a newline argument"
)
raise ValueError("binary mode doesn't take a newline argument")

if buffering == 1:
msg = (
Expand Down Expand Up @@ -244,13 +231,7 @@ def open(
if binary:
return buffered

wrapped = io.TextIOWrapper(
buffered,
encoding,
errors,
newline,
line_buffering
)
wrapped = io.TextIOWrapper(buffered, encoding, errors, newline, line_buffering)

return wrapped

Expand All @@ -266,7 +247,7 @@ def removeattr(self, path: str, typ: Union[str, bytes, int]) -> None:
typ = _typ_to_uint8(typ)
lfs.removeattr(self.fs, path, typ)

def listdir(self, path='.') -> List[str]:
def listdir(self, path=".") -> List[str]:
"""List directory content
List the content of a directory. This function uses :meth:`scandir`
Expand All @@ -290,10 +271,10 @@ def mkdir(self, path: str) -> int:

def makedirs(self, name: str, exist_ok=False):
"""Recursive directory creation function."""
parts = [p for p in name.split('/') if p]
current_name = ''
parts = [p for p in name.split("/") if p]
current_name = ""
for nr, part in enumerate(parts):
current_name += '/%s' % part
current_name += "/%s" % part
try:
self.mkdir(current_name)
except FileExistsError as e:
Expand Down Expand Up @@ -341,13 +322,13 @@ def removedirs(self, name):
function tries to recursively remove all parent directories
which are also empty.
"""
parts = name.split('/')
parts = name.split("/")
while parts:
try:
name = '/'.join(parts)
name = "/".join(parts)
if not name:
break
self.remove('/'.join(parts))
self.remove("/".join(parts))
except errors.LittleFSError as e:
if e.code == LittleFSError.Error.LFS_ERR_NOTEMPTY:
break
Expand All @@ -365,17 +346,17 @@ def rmdir(self, path: str) -> int:
"""
return self.remove(path)

def scandir(self, path='.') -> Iterator['LFSStat']:
def scandir(self, path=".") -> Iterator["LFSStat"]:
"""List directory content"""
dh = lfs.dir_open(self.fs, path)
info = lfs.dir_read(self.fs, dh)
while info:
if info.name not in ['.', '..']:
if info.name not in [".", ".."]:
yield info
info = lfs.dir_read(self.fs, dh)
lfs.dir_close(self.fs, dh)

def stat(self, path: str) -> 'LFSStat':
def stat(self, path: str) -> "LFSStat":
"""Get the status of a file or directory"""
return lfs.stat(self.fs, path)

Expand Down Expand Up @@ -408,7 +389,7 @@ def walk(self, top: str) -> Iterator[Tuple[str, List[str], List[str]]]:

yield top, dirs, files
for dirname in dirs:
newtop = '/'.join((top, dirname)).replace('//', '/')
newtop = "/".join((top, dirname)).replace("//", "/")
yield from self.walk(newtop)


Expand Down Expand Up @@ -487,13 +468,14 @@ def flush(self):
super().flush()
lfs.file_sync(self.fs, self.fh)


def _typ_to_uint8(typ):
try:
out = ord(typ)
except TypeError:
out = int(typ)

if not(0 <= out <= 255):
if not (0 <= out <= 255):
raise ValueError(f"type must be in range [0, 255]")

return out
15 changes: 5 additions & 10 deletions src/littlefs/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ def _fs_from_args(args: argparse.Namespace) -> LittleFS:
name_max=args.name_max,
)


def size_parser(size_str):
"""Parse filesystem / block size in different formats"""
size_str = str(size_str).lower()
Expand Down Expand Up @@ -154,22 +155,16 @@ def get_parser():
),
# formatter_class=argparse.RawTextHelpFormatter,
)
parser.add_argument('--version', action='version', version=__version__)
parser.add_argument("--version", action="version", version=__version__)

common_parser = argparse.ArgumentParser(add_help=False)
common_parser.add_argument("-v", "--verbose", action="count", default=0)
common_parser.add_argument(
"--block-size", type=size_parser, required=True, help="LittleFS block size"
)
common_parser.add_argument(
"--name-max", type=size_parser, default=255, help="LittleFS max file path length."
)
common_parser.add_argument("--block-size", type=size_parser, required=True, help="LittleFS block size")
common_parser.add_argument("--name-max", type=size_parser, default=255, help="LittleFS max file path length.")
group = common_parser.add_mutually_exclusive_group(required=True)
group.add_argument("--block-count", type=int, help="LittleFS block count")
group.add_argument("--fs-size", type=size_parser, help="LittleFS filesystem size")
common_parser.add_argument(
"--image", type=pathlib.Path, required=True, help="LittleFS filesystem image"
)
common_parser.add_argument("--image", type=pathlib.Path, required=True, help="LittleFS filesystem image")

subparsers = parser.add_subparsers(required=True, title="Available Commands", dest="command")

Expand Down
Loading

0 comments on commit 1fdf804

Please sign in to comment.