Skip to content

Commit

Permalink
👷 project management changes
Browse files Browse the repository at this point in the history
  • Loading branch information
juftin authored Dec 22, 2023
1 parent 58833c4 commit bbeb14c
Show file tree
Hide file tree
Showing 26 changed files with 2,811 additions and 3,446 deletions.
8 changes: 4 additions & 4 deletions .github/workflows/lint.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ jobs:
uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Set up Python Environment 3.10
- name: Set up Python Environment 3.11
uses: actions/setup-python@v4
with:
python-version: "3.10"
python-version: "3.11"
- name: Install Hatch
run: |
python -m pip install --upgrade pip
Expand All @@ -27,14 +27,14 @@ jobs:
continue-on-error: true
run: |
echo "::add-matcher::.github/workflows/matchers/flake8.json"
hatch run lint
hatch run lint:style
echo "::remove-matcher owner=flake8::"
- name: Code Checker
id: check
continue-on-error: true
run: |
echo "::add-matcher::.github/workflows/matchers/mypy.json"
hatch run check
hatch run lint:typing
echo "::remove-matcher owner=mypy::"
- name: Raise Errors For Linting Failures
if: |
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/publish.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ jobs:
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: "3.10"
python-version: "3.11"
- name: Install Hatch
run: |
python -m pip install --upgrade pip
Expand Down
8 changes: 4 additions & 4 deletions .github/workflows/release.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,15 @@ jobs:
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: "3.10"
python-version: "3.11"
- name: Install Hatch
run: |
python -m pip install --upgrade pip
python -m pip install -q hatch
hatch env create
hatch --version
- name: Release
run: hatch run semantic-release
run: hatch run gen:release
env:
GITHUB_TOKEN: ${{ secrets.PERSONAL_ACCESS_TOKEN }}
GIT_AUTHOR_NAME: github-actions[bot]
Expand All @@ -51,7 +51,7 @@ jobs:
- name: Set up Python Environment
uses: actions/setup-python@v4
with:
python-version: "3.10"
python-version: "3.11"
- name: Install Hatch
run: |
python -m pip install --upgrade pip
Expand All @@ -63,4 +63,4 @@ jobs:
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
- name: Deploy Documentation Changes
run: hatch run docs-deploy --force
run: hatch run docs:gh-deploy --force
2 changes: 1 addition & 1 deletion .github/workflows/tests.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -44,5 +44,5 @@ jobs:
- name: Test Suite
run: |
echo "::add-matcher::.github/workflows/matchers/python.json"
hatch run +py="${{ matrix.python }}" test:matrix
hatch run +py="${{ matrix.python }}" all:cov
echo "::remove-matcher owner=python::"
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,13 @@ repos:
- id: format
name: format
description: Runs Code Auto-Formatters
entry: hatch run format
entry: hatch run lint:fmt
language: system
pass_filenames: false
- id: lint
name: lint
description: Runs Code Linters
entry: hatch run format
entry: hatch run lint:style
language: system
pass_filenames: false
require_serial: false
4 changes: 2 additions & 2 deletions browsr/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
browsr
"""

from .browsr import Browsr
from .universal_directory_tree import BrowsrDirectoryTree
from browsr.browsr import Browsr
from browsr.universal_directory_tree import BrowsrDirectoryTree

__all__ = ["Browsr", "BrowsrDirectoryTree"]
41 changes: 21 additions & 20 deletions browsr/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from dataclasses import dataclass, field
from os import PathLike
from textwrap import dedent
from typing import Any, ClassVar, Dict, List, Optional, Union
from typing import Any, ClassVar

import numpy as np
import upath
Expand All @@ -38,9 +38,9 @@ class BrowsrPath(UPath):
A UPath object that can be extended with persisted kwargs
"""

__path_kwargs__: ClassVar[Dict[str, Any]] = {}
__path_kwargs__: ClassVar[dict[str, Any]] = {}

def __new__(cls, *args: str | PathLike[Any], **kwargs: Any) -> "BrowsrPath":
def __new__(cls, *args: str | PathLike[Any], **kwargs: Any) -> BrowsrPath:
"""
Create a new BrowsrPath object
"""
Expand All @@ -54,10 +54,10 @@ class TextualAppContext:
"""

file_path: str = field(default_factory=os.getcwd)
config: Optional[Dict[str, Any]] = None
config: dict[str, Any] | None = None
debug: bool = False
max_file_size: int = 20
kwargs: Optional[Dict[str, Any]] = None
kwargs: dict[str, Any] | None = None

@property
def path(self) -> pathlib.Path:
Expand All @@ -66,17 +66,17 @@ def path(self) -> pathlib.Path:
"""
if "github" in str(self.file_path).lower():
file_path = str(self.file_path)
file_path = file_path.lstrip("https://")
file_path = file_path.lstrip("http://")
file_path = file_path.lstrip("www.")
file_path = file_path.lstrip("https://") # noqa: B005
file_path = file_path.lstrip("http://") # noqa: B005
file_path = file_path.lstrip("www.") # noqa: B005
if file_path.endswith(".git"):
file_path = file_path[:-4]
file_path = handle_github_url(url=str(file_path))
self.file_path = file_path
if str(self.file_path).endswith("/") and len(str(self.file_path)) > 1:
self.file_path = str(self.file_path)[:-1]
kwargs = self.kwargs or {}
PathClass = copy(BrowsrPath)
PathClass = copy(BrowsrPath) # noqa: N806
PathClass.__path_kwargs__ = kwargs
return (
PathClass(self.file_path).resolve()
Expand All @@ -94,13 +94,13 @@ class BrowsrTextualApp(App[str]):
theme_index = var(0)
linenos = var(False)
rich_themes = favorite_themes
selected_file_path: Union[upath.UPath, pathlib.Path, None, var[None]] = var(None)
selected_file_path: upath.UPath | pathlib.Path | None | var[None] = var(None)
force_show_tree = var(False)
hidden_table_view = var(False)

def __init__(
self,
config_object: Optional[TextualAppContext] = None,
config_object: TextualAppContext | None = None,
):
"""
Like the textual.app.App class, but with an extra config_object property
Expand All @@ -120,7 +120,7 @@ def df_to_table(
pandas_dataframe: DataFrame,
table: DataTable[str],
show_index: bool = True,
index_name: Optional[str] = None,
index_name: str | None = None,
) -> DataTable[str]:
"""
Convert a pandas.DataFrame obj into a rich.Table obj.
Expand All @@ -134,7 +134,8 @@ def df_to_table(
show_index: bool
Add a column with a row count to the table. Defaults to True.
index_name: Optional[str]
The column name to give to the index column. Defaults to None, showing no value.
The column name to give to the index column.
Defaults to None, showing no value.
Returns
-------
Expand Down Expand Up @@ -168,9 +169,9 @@ class CurrentFileInfoBar(Widget):
Thanks, Kupo. https://github.com/darrenburns/kupo
"""

file_info: Union[FileInfo, var[None]] = reactive(None) # type: ignore[assignment]
file_info: FileInfo | var[None] = reactive(None)

def watch_file_info(self, new_file: Union[FileInfo, None]) -> None:
def watch_file_info(self, new_file: FileInfo | None) -> None:
"""
Watch the file_info property for changes
"""
Expand Down Expand Up @@ -243,10 +244,10 @@ def handle_download_selection(self, message: Button.Pressed) -> None:
"""
Handle Button Presses
"""
self.app.confirmation_window.display = False # type: ignore[attr-defined]
self.app.confirmation_window.display = False
if message.button.variant == "success":
self.app.download_selected_file() # type: ignore[attr-defined]
self.app.table_view.display = self.app.hidden_table_view # type: ignore[attr-defined]
self.app.download_selected_file()
self.app.table_view.display = self.app.hidden_table_view


vim_scroll_bindings = [
Expand All @@ -269,7 +270,7 @@ class VimScroll(VerticalScroll):
A VerticalScroll with Vim Keybindings
"""

BINDINGS: ClassVar[List[BindingType]] = [
BINDINGS: ClassVar[list[BindingType]] = [
*VerticalScroll.BINDINGS,
*vim_scroll_bindings,
]
Expand All @@ -280,7 +281,7 @@ class VimDataTable(DataTable[str]):
A DataTable with Vim Keybindings
"""

BINDINGS: ClassVar[List[BindingType]] = [
BINDINGS: ClassVar[list[BindingType]] = [
*DataTable.BINDINGS,
*vim_cursor_bindings,
]
11 changes: 7 additions & 4 deletions browsr/_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,9 @@ def browsr(
browsr 🗂️ a pleasant file explorer in your terminal
Navigate through directories and peek at files whether they're hosted locally,
over SSH, in GitHub, AWS S3, Google Cloud Storage, or Azure Blob Storage. View code files
with syntax highlighting, format JSON files, render images, convert data files to navigable
datatables, and more.
over SSH, in GitHub, AWS S3, Google Cloud Storage, or Azure Blob Storage.
View code files with syntax highlighting, format JSON files, render images,
convert data files to navigable datatables, and more.
\f
Expand Down Expand Up @@ -184,7 +184,10 @@ def browsr(
extra_kwargs[key] = value
except ValueError as ve:
raise click.BadParameter(
message=f"Invalid Key/Value pair: `{kwarg}` - must be in the format Key=Value",
message=(
f"Invalid Key/Value pair: `{kwarg}` "
"- must be in the format Key=Value"
),
param_hint="kwargs",
) from ve
file_path = path or os.getcwd()
Expand Down
2 changes: 0 additions & 2 deletions browsr/_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,8 @@
rich_default_theme = getenv("RICH_THEME", None)

if rich_default_theme in favorite_themes:
assert isinstance(rich_default_theme, str)
favorite_themes.remove(rich_default_theme)
if rich_default_theme is not None:
assert isinstance(rich_default_theme, str)
favorite_themes.insert(0, rich_default_theme)

image_file_extensions = [
Expand Down
15 changes: 9 additions & 6 deletions browsr/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from dataclasses import dataclass
from typing import Any, BinaryIO, Dict, Optional, Union

import fitz # type: ignore[import]
import fitz
import rich_pixels
from fitz import Pixmap
from PIL import Image
Expand Down Expand Up @@ -102,7 +102,9 @@ def get_file_info(file_path: pathlib.Path) -> FileInfo:
is_cloudpath=is_cloudpath,
)
else:
last_modified = datetime.datetime.fromtimestamp(stat.st_mtime)
last_modified = datetime.datetime.fromtimestamp(
stat.st_mtime, tz=datetime.timezone.utc
)
try:
owner = file_path.owner()
group = file_path.group()
Expand Down Expand Up @@ -165,12 +167,14 @@ def handle_github_url(url: str) -> str:
elif "github.com" in url.lower():
_, org, repo, *args = url.split("/")
else:
raise ValueError(f"Invalid GitHub URL: {url}")
msg = f"Invalid GitHub URL: {url}"
raise ValueError(msg)
token = os.getenv("GITHUB_TOKEN")
auth = {"auth": ("Bearer", token)} if token is not None else {}
resp = requests.get(
f"https://api.github.com/repos/{org}/{repo}",
headers={"Accept": "application/vnd.github.v3+json"},
timeout=10,
**auth, # type: ignore[arg-type]
)
resp.raise_for_status()
Expand Down Expand Up @@ -204,8 +208,7 @@ def render_file_to_string(file_info: FileInfo) -> str:
return file_info.file.read_text(encoding="utf-8")
except UnicodeDecodeError as e:
if file_info.file.suffix.lower() in [".tar", ".gz", ".zip", ".tgz"]:
raise ArchiveFileError(
f"Cannot render archive file {file_info.file}."
) from e
msg = f"Cannot render archive file {file_info.file}."
raise ArchiveFileError(msg) from e
else:
raise e
11 changes: 7 additions & 4 deletions browsr/browsr.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

import pandas as pd
import upath
from art import text2art # type: ignore[import]
from art import text2art
from rich.markdown import Markdown
from rich.syntax import Syntax
from rich.traceback import Traceback
Expand Down Expand Up @@ -87,7 +87,6 @@ def compose(self) -> Iterable[Widget]:
"""
Compose our UI.
"""
assert isinstance(self.config_object, TextualAppContext)
file_path = self.config_object.path
if is_remote_path(file_path):
self.bind("x", "download_file", description="Download File", show=True)
Expand Down Expand Up @@ -301,7 +300,10 @@ def start_up_app(self) -> None:
)

@on(BrowsrDirectoryTree.FileSelected)
def handle_file_selected(self, message: BrowsrDirectoryTree.FileSelected) -> None:
def handle_file_selected(
self,
message: BrowsrDirectoryTree.FileSelected, # type: ignore[name-defined]
) -> None:
"""
Called when the user click a file in the directory tree.
"""
Expand Down Expand Up @@ -343,7 +345,8 @@ def _get_download_file_name(self) -> pathlib.Path:
"""
download_dir = pathlib.Path.home() / "Downloads"
if not download_dir.exists():
raise FileNotFoundError(f"Download directory {download_dir} not found")
msg = f"Download directory {download_dir} not found"
raise FileNotFoundError(msg)
download_path = download_dir / self.selected_file_path.name # type: ignore[union-attr]
handled_download_path = handle_duplicate_filenames(file_path=download_path)
return handled_download_path
Expand Down
Loading

0 comments on commit bbeb14c

Please sign in to comment.