Skip to content

Commit

Permalink
refactor: follow some flake8 rules
Browse files Browse the repository at this point in the history
* remove unused imports
* simplify functions that have a high complexity according to mccabe
* enable more checks for flake8
  • Loading branch information
elkaboussi committed Mar 7, 2024
1 parent 37e0cf0 commit 9f2d111
Show file tree
Hide file tree
Showing 11 changed files with 67 additions and 39 deletions.
8 changes: 5 additions & 3 deletions .flake8
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
[flake8]
max-line-length = 88
max-complexity = 18
select = B,C,E,F,W,T4,B9
ignore = E203, E266, E501, W503, F403, F401
max-complexity = 6
indent-size = 4

; E503 line break before binary operator
ignore = W503
56 changes: 41 additions & 15 deletions analyzer/directory_traversal.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import sys
from pathlib import Path
from typing import Generator, Union
from typing import Generator, List, Union

from rich import print
import rich


def walk_through_dir(root_dir: Union[str, Path]) -> Generator[Path, None, None]:
Expand All @@ -13,22 +13,48 @@ def walk_through_dir(root_dir: Union[str, Path]) -> Generator[Path, None, None]:
root_dir (Union[str, Path]): The root directory to start the traversal.
Yields:
Generator[Path, None, None]: Yields FileInfo objects for each file in the directory tree.
Generator[Path, None, None]: Yields Path objects for each file
in the directory tree.
"""
root_path = Path(root_dir)
stack = [root_path]
stack: List[Path] = [root_path]

while stack:
current_path = stack.pop()
yield from process_path(stack, current_path)

try:
for child in current_path.iterdir():
if child.is_dir():
stack.append(child)
else:
yield child
except PermissionError:
print(
f"[red]Permission error accessing directory '{current_path}'. Skipping...[/red]",
file=sys.stderr,
)

def process_path(stack: List[Path], current_path: Path) -> Generator[Path, None, None]:
"""
Process a given path, yielding files and handling directories.
Args:
stack (List[Path]): The stack used for directory traversal.
current_path (Path): The path to process.
Yields:
Generator[Path, None, None]: Yields Path objects for each file
in the processed path.
"""
try:
for child in current_path.iterdir():
if child.is_dir():
stack.append(child)
else:
yield child
except PermissionError:
handle_permission_error(current_path)


def handle_permission_error(current_path: Path) -> None:
"""
Handle PermissionError when accessing a directory.
Args:
current_path (Path): The path where the PermissionError occurred.
"""
rich.print(
f"[red]Permission error accessing directory '{current_path}'"
". Skipping...[/red]",
file=sys.stderr,
)
22 changes: 11 additions & 11 deletions analyzer/permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
from pathlib import Path
from typing import List, Set, Union

import rich
from pydantic import BaseModel
from rich import print
from rich.table import Table

from analyzer.analyzer_interface import AnalyserInterface
from analyzer.analyzer_interface import AnalyserInterface, PathLike
from analyzer.utils.permissions import (
PermissionType,
generate_full_write_combination,
Expand Down Expand Up @@ -60,19 +60,19 @@ def __init__(self) -> None:
no_wrap=False,
)

def add(self, file_path) -> None:
def add(self, filepath: PathLike) -> None:
"""
Check the permissions of a file and add it to the reported files if the
permissions are bad.
Check the permissions of a file and add it to the
reported files if the permissions are bad.
Parameters:
- file_path (Path): Path to the file.
"""
try:
file_permission: PermissionType = get_file_permissions(file_path)
file_permission: PermissionType = get_file_permissions(filepath)
if file_permission not in self.bad_permissions:
return
self._table.add_row(str(file_path), file_permission.permission)
self._table.add_row(str(filepath), file_permission.permission)
except (FileNotFoundError, OSError):
pass

Expand All @@ -81,9 +81,9 @@ def report(self) -> None:
Print the report of files with bad permissions using the rich library.
"""
if self._table.rows:
print(self._table)
rich.print(self._table)
return
print("No files with bad permissions found.")
rich.print("No files with bad permissions found.")

def is_report_empty(self) -> bool:
"""
Expand All @@ -109,6 +109,6 @@ def _delete_file(self, file_path: Union[Path, str]) -> None:
"""
try:
os.remove(file_path)
print(f"[green]Deleted:[/green] {file_path}")
rich.print(f"[green]Deleted:[/green] {file_path}")
except Exception as e:
print(f"[red]Error deleting file {file_path}:[/red] {e}")
rich.print(f"[red]Error deleting file {file_path}:[/red] {e}")
1 change: 0 additions & 1 deletion analyzer/summary.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import time
from os import stat
from pathlib import Path
from typing import Union

import bitmath
Expand Down
6 changes: 4 additions & 2 deletions analyzer/utils/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,12 @@ def parse_args() -> Optional[ParsedArgs]:
Parse command-line arguments.
Returns:
Optional[ParsedArgs]: Parsed command-line arguments as an instance of ParsedArgs.
Optional[ParsedArgs]: Parsed command-line arguments
as an instance of ParsedArgs.
"""
parser = argparse.ArgumentParser(
description="Command-line tool that analyzes and reports on the filesystem structure and usage on a Linux system."
description="Command-line tool that analyzes and reports on the"
"filesystem structure and usage on a Linux system."
)

parser.add_argument(
Expand Down
2 changes: 1 addition & 1 deletion analyzer/utils/permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from pathlib import Path
from typing import Set, Union

from pydantic import BaseModel, constr
from pydantic import BaseModel


class PermissionType(BaseModel):
Expand Down
2 changes: 1 addition & 1 deletion test/test_directory_traversal.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import os
from pathlib import Path
from test.conftest import PathLike, app_file_system, fake_filesystem_files
from test.conftest import fake_filesystem_files

import pytest
from pyfakefs.fake_filesystem import FakeFilesystem
Expand Down
2 changes: 1 addition & 1 deletion test/test_file_categorization.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from pathlib import Path
from test.conftest import app_file_system, create_fakefs_file, fake_filesystem_files
from test.conftest import create_fakefs_file, fake_filesystem_files

import bitmath
import pytest
Expand Down
2 changes: 1 addition & 1 deletion test/test_file_statistics_collector.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from pathlib import Path
from test.conftest import app_file_system, create_fakefs_file, fake_filesystem_files
from test.conftest import create_fakefs_file, fake_filesystem_files

import bitmath
import pytest
Expand Down
3 changes: 1 addition & 2 deletions test/test_large_files_identification.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import os
from collections import Counter
from test.conftest import app_file_system, fake_filesystem_files
from test.conftest import fake_filesystem_files
from typing import Dict, List, Union

import bitmath
Expand Down Expand Up @@ -174,7 +174,6 @@ def test_check_sorted_files_are_updating(fs: FakeFilesystem):


def test_report(large_file_identifier, capsys: pytest.CaptureFixture):

capsys.readouterr()

list_of_large_files = [
Expand Down
2 changes: 1 addition & 1 deletion test/test_permission_reporter.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from collections import Counter
from pathlib import Path
from test.conftest import app_file_system, create_fakefs_file, fake_filesystem_files
from test.conftest import create_fakefs_file, fake_filesystem_files
from typing import List, Tuple

import pytest
Expand Down

0 comments on commit 9f2d111

Please sign in to comment.