refactor: use single console instance

This commit is contained in:
Nathaniel Landau
2023-03-03 21:10:43 -05:00
parent bf869cfc15
commit 0b744f65ee
8 changed files with 51 additions and 46 deletions

View File

@@ -7,7 +7,8 @@ from textwrap import wrap
import rich.repr import rich.repr
import typer import typer
from loguru import logger from loguru import logger
from rich import print
from obsidian_metadata._utils.console import console
class LogLevel(Enum): class LogLevel(Enum):
@@ -38,7 +39,7 @@ def dryrun(msg: str) -> None:
Args: Args:
msg: Message to print msg: Message to print
""" """
print(f"[cyan]DRYRUN | {msg}[/cyan]") console.print(f"[cyan]DRYRUN | {msg}[/cyan]")
def success(msg: str) -> None: def success(msg: str) -> None:
@@ -47,7 +48,7 @@ def success(msg: str) -> None:
Args: Args:
msg: Message to print msg: Message to print
""" """
print(f"[green]SUCCESS | {msg}[/green]") console.print(f"[green]SUCCESS | {msg}[/green]")
def warning(msg: str) -> None: def warning(msg: str) -> None:
@@ -56,7 +57,7 @@ def warning(msg: str) -> None:
Args: Args:
msg: Message to print msg: Message to print
""" """
print(f"[yellow]WARNING | {msg}[/yellow]") console.print(f"[yellow]WARNING | {msg}[/yellow]")
def error(msg: str) -> None: def error(msg: str) -> None:
@@ -65,7 +66,7 @@ def error(msg: str) -> None:
Args: Args:
msg: Message to print msg: Message to print
""" """
print(f"[red]ERROR | {msg}[/red]") console.print(f"[red]ERROR | {msg}[/red]")
def notice(msg: str) -> None: def notice(msg: str) -> None:
@@ -74,7 +75,7 @@ def notice(msg: str) -> None:
Args: Args:
msg: Message to print msg: Message to print
""" """
print(f"[bold]NOTICE | {msg}[/bold]") console.print(f"[bold]NOTICE | {msg}[/bold]")
def info(msg: str) -> None: def info(msg: str) -> None:
@@ -83,7 +84,7 @@ def info(msg: str) -> None:
Args: Args:
msg: Message to print msg: Message to print
""" """
print(f"INFO | {msg}") console.print(f"INFO | {msg}")
def usage(msg: str, width: int = 80) -> None: def usage(msg: str, width: int = 80) -> None:
@@ -95,9 +96,9 @@ def usage(msg: str, width: int = 80) -> None:
""" """
for _n, line in enumerate(wrap(msg, width=width)): for _n, line in enumerate(wrap(msg, width=width)):
if _n == 0: if _n == 0:
print(f"[dim]USAGE | {line}") console.print(f"[dim]USAGE | {line}")
else: else:
print(f"[dim] | {line}") console.print(f"[dim] | {line}")
def debug(msg: str) -> None: def debug(msg: str) -> None:
@@ -106,7 +107,7 @@ def debug(msg: str) -> None:
Args: Args:
msg: Message to print msg: Message to print
""" """
print(f"[blue]DEBUG | {msg}[/blue]") console.print(f"[blue]DEBUG | {msg}[/blue]")
def dim(msg: str) -> None: def dim(msg: str) -> None:
@@ -115,7 +116,7 @@ def dim(msg: str) -> None:
Args: Args:
msg: Message to print msg: Message to print
""" """
print(f"[dim]{msg}[/dim]") console.print(f"[dim]{msg}[/dim]")
def _log_formatter(record: dict) -> str: def _log_formatter(record: dict) -> str:
@@ -171,7 +172,7 @@ class LoggerManager:
self.log_level = log_level self.log_level = log_level
if self.log_file == Path("/logs") and self.log_to_file: # pragma: no cover if self.log_file == Path("/logs") and self.log_to_file: # pragma: no cover
print("No log file specified") console.print("No log file specified")
raise typer.Exit(1) raise typer.Exit(1)
if self.verbosity >= VerboseLevel.TRACE.value: if self.verbosity >= VerboseLevel.TRACE.value:
@@ -239,7 +240,7 @@ class LoggerManager:
""" """
if self.log_level <= LogLevel.TRACE.value: if self.log_level <= LogLevel.TRACE.value:
if msg: if msg:
print(msg) console.print(msg)
return True return True
return False return False
@@ -254,7 +255,7 @@ class LoggerManager:
""" """
if self.log_level <= LogLevel.DEBUG.value: if self.log_level <= LogLevel.DEBUG.value:
if msg: if msg:
print(msg) console.print(msg)
return True return True
return False return False
@@ -269,7 +270,7 @@ class LoggerManager:
""" """
if self.log_level <= LogLevel.INFO.value: if self.log_level <= LogLevel.INFO.value:
if msg: if msg:
print(msg) console.print(msg)
return True return True
return False return False
@@ -284,6 +285,6 @@ class LoggerManager:
""" """
if self.log_level <= LogLevel.WARNING.value: if self.log_level <= LogLevel.WARNING.value:
if msg: if msg:
print(msg) console.print(msg)
return True return True
return False # pragma: no cover return False # pragma: no cover

View File

@@ -0,0 +1,4 @@
"""Rich console object for the application."""
from rich.console import Console
console = Console()

View File

@@ -6,6 +6,7 @@ from typing import Any
import typer import typer
from obsidian_metadata.__version__ import __version__ from obsidian_metadata.__version__ import __version__
from obsidian_metadata._utils.console import console
def clean_dictionary(dictionary: dict[str, Any]) -> dict[str, Any]: def clean_dictionary(dictionary: dict[str, Any]) -> dict[str, Any]:
@@ -181,5 +182,5 @@ def remove_markdown_sections(
def version_callback(value: bool) -> None: def version_callback(value: bool) -> None:
"""Print version and exit.""" """Print version and exit."""
if value: if value:
print(f"{__package__.split('.')[0]}: v{__version__}") console.print(f"{__package__.split('.')[0]}: v{__version__}")
raise typer.Exit() raise typer.Exit()

View File

@@ -5,7 +5,6 @@ from typing import Optional
import questionary import questionary
import typer import typer
from rich import print
from obsidian_metadata._config import Config from obsidian_metadata._config import Config
from obsidian_metadata._utils import ( from obsidian_metadata._utils import (
@@ -14,6 +13,7 @@ from obsidian_metadata._utils import (
docstring_parameter, docstring_parameter,
version_callback, version_callback,
) )
from obsidian_metadata._utils.console import console
from obsidian_metadata.models import Application from obsidian_metadata.models import Application
app = typer.Typer(add_completion=False, no_args_is_help=True, rich_markup_mode="rich") app = typer.Typer(add_completion=False, no_args_is_help=True, rich_markup_mode="rich")
@@ -171,7 +171,7 @@ def main(
|_| |_|\___|\__\__,_|\__,_|\__,_|\__\__,_| |_| |_|\___|\__\__,_|\__,_|\__,_|\__\__,_|
""" """
clear_screen() clear_screen()
print(banner) console.print(banner)
config: Config = Config(config_path=config_file, vault_path=vault_path) config: Config = Config(config_path=config_file, vault_path=vault_path)
if len(config.vaults) == 0: if len(config.vaults) == 0:

View File

@@ -5,12 +5,12 @@ from pathlib import Path
from typing import Any from typing import Any
import questionary import questionary
from rich import box, print from rich import box
from rich.console import Console
from rich.table import Table from rich.table import Table
from obsidian_metadata._config import VaultConfig from obsidian_metadata._config import VaultConfig
from obsidian_metadata._utils import alerts from obsidian_metadata._utils import alerts
from obsidian_metadata._utils.console import console
from obsidian_metadata.models import Vault, VaultFilter from obsidian_metadata.models import Vault, VaultFilter
from obsidian_metadata.models.enums import MetadataType from obsidian_metadata.models.enums import MetadataType
from obsidian_metadata.models.questions import Questions from obsidian_metadata.models.questions import Questions
@@ -71,7 +71,7 @@ class Application:
case _: case _:
break break
print("Done!") console.print("Done!")
return return
def application_add_metadata(self) -> None: def application_add_metadata(self) -> None:
@@ -218,7 +218,7 @@ class Application:
alerts.notice("No filters have been applied") alerts.notice("No filters have been applied")
return return
print("") console.print("")
table = Table( table = Table(
"Opt", "Opt",
"Filter", "Filter",
@@ -254,7 +254,7 @@ class Application:
) )
table.add_row(f"{len(self.filters) + 1}", "Clear All") table.add_row(f"{len(self.filters) + 1}", "Clear All")
table.add_row(f"{len(self.filters) + 2}", "Return to Main Menu") table.add_row(f"{len(self.filters) + 2}", "Return to Main Menu")
Console().print(table) console.print(table)
num = self.questions.ask_number( num = self.questions.ask_number(
question="Enter the number of the filter to clear" question="Enter the number of the filter to clear"
@@ -297,25 +297,25 @@ class Application:
while True: while True:
match self.questions.ask_selection(choices=choices, question="Select a vault action"): match self.questions.ask_selection(choices=choices, question="Select a vault action"):
case "all_metadata": case "all_metadata":
print("") console.print("")
self.vault.metadata.print_metadata(area=MetadataType.ALL) self.vault.metadata.print_metadata(area=MetadataType.ALL)
print("") console.print("")
case "all_frontmatter": case "all_frontmatter":
print("") console.print("")
self.vault.metadata.print_metadata(area=MetadataType.FRONTMATTER) self.vault.metadata.print_metadata(area=MetadataType.FRONTMATTER)
print("") console.print("")
case "all_inline": case "all_inline":
print("") console.print("")
self.vault.metadata.print_metadata(area=MetadataType.INLINE) self.vault.metadata.print_metadata(area=MetadataType.INLINE)
print("") console.print("")
case "all_keys": case "all_keys":
print("") console.print("")
self.vault.metadata.print_metadata(area=MetadataType.KEYS) self.vault.metadata.print_metadata(area=MetadataType.KEYS)
print("") console.print("")
case "all_tags": case "all_tags":
print("") console.print("")
self.vault.metadata.print_metadata(area=MetadataType.TAGS) self.vault.metadata.print_metadata(area=MetadataType.TAGS)
print("") console.print("")
case "export_csv": case "export_csv":
path = self.questions.ask_path(question="Enter a path for the CSV file") path = self.questions.ask_path(question="Enter a path for the CSV file")
if path is None: if path is None:
@@ -378,7 +378,7 @@ class Application:
changed_notes = self.vault.get_changed_notes() changed_notes = self.vault.get_changed_notes()
if len(changed_notes) == 0: if len(changed_notes) == 0:
print("\n") console.print("\n")
alerts.notice("No changes to commit.\n") alerts.notice("No changes to commit.\n")
return False return False

View File

@@ -4,9 +4,7 @@ import copy
import re import re
from io import StringIO from io import StringIO
from rich import print
from rich.columns import Columns from rich.columns import Columns
from rich.console import Console
from rich.table import Table from rich.table import Table
from ruamel.yaml import YAML from ruamel.yaml import YAML
@@ -17,6 +15,7 @@ from obsidian_metadata._utils import (
merge_dictionaries, merge_dictionaries,
remove_markdown_sections, remove_markdown_sections,
) )
from obsidian_metadata._utils.console import console
from obsidian_metadata.models import Patterns # isort: ignore from obsidian_metadata.models import Patterns # isort: ignore
from obsidian_metadata.models.enums import MetadataType from obsidian_metadata.models.enums import MetadataType
@@ -172,7 +171,7 @@ class VaultMetadata:
"\n".join(sorted(value)) if isinstance(value, list) else value "\n".join(sorted(value)) if isinstance(value, list) else value
) )
table.add_row(f"[bold]{key}[/]", str(values)) table.add_row(f"[bold]{key}[/]", str(values))
Console().print(table) console.print(table)
if list_to_print is not None: if list_to_print is not None:
columns = Columns( columns = Columns(
@@ -181,7 +180,7 @@ class VaultMetadata:
expand=True, expand=True,
title=header if area != MetadataType.ALL else "All inline tags", title=header if area != MetadataType.ALL else "All inline tags",
) )
print(columns) console.print(columns)
def rename(self, key: str, value_1: str, value_2: str = None) -> bool: def rename(self, key: str, value_1: str, value_2: str = None) -> bool:
"""Replace a value in the frontmatter. """Replace a value in the frontmatter.

View File

@@ -8,11 +8,11 @@ from pathlib import Path
import rich.repr import rich.repr
import typer import typer
from rich.console import Console
from rich.table import Table from rich.table import Table
from obsidian_metadata._utils import alerts from obsidian_metadata._utils import alerts
from obsidian_metadata._utils.alerts import logger as log from obsidian_metadata._utils.alerts import logger as log
from obsidian_metadata._utils.console import console
from obsidian_metadata.models import ( from obsidian_metadata.models import (
Frontmatter, Frontmatter,
InlineMetadata, InlineMetadata,
@@ -355,7 +355,7 @@ class Note:
def print_note(self) -> None: def print_note(self) -> None:
"""Print the note to the console.""" """Print the note to the console."""
print(self.file_content) console.print(self.file_content)
def print_diff(self) -> None: def print_diff(self) -> None:
"""Print a diff of the note's original state and it's new state.""" """Print a diff of the note's original state and it's new state."""
@@ -372,7 +372,7 @@ class Note:
elif line.startswith("-"): elif line.startswith("-"):
table.add_row(line, style="red") table.add_row(line, style="red")
Console().print(table) console.print(table)
def rename_inline_tag(self, tag_1: str, tag_2: str) -> bool: def rename_inline_tag(self, tag_1: str, tag_2: str) -> bool:
"""Rename an inline tag from the note ONLY if it's not in the metadata as well. """Rename an inline tag from the note ONLY if it's not in the metadata as well.

View File

@@ -9,7 +9,6 @@ from pathlib import Path
import rich.repr import rich.repr
from rich import box from rich import box
from rich.console import Console
from rich.progress import Progress, SpinnerColumn, TextColumn from rich.progress import Progress, SpinnerColumn, TextColumn
from rich.prompt import Confirm from rich.prompt import Confirm
from rich.table import Table from rich.table import Table
@@ -17,6 +16,7 @@ from rich.table import Table
from obsidian_metadata._config.config import VaultConfig from obsidian_metadata._config.config import VaultConfig
from obsidian_metadata._utils import alerts from obsidian_metadata._utils import alerts
from obsidian_metadata._utils.alerts import logger as log from obsidian_metadata._utils.alerts import logger as log
from obsidian_metadata._utils.console import console
from obsidian_metadata.models import InsertLocation, MetadataType, Note, VaultMetadata from obsidian_metadata.models import InsertLocation, MetadataType, Note, VaultMetadata
@@ -202,7 +202,7 @@ class Vault:
log.debug("Backing up vault") log.debug("Backing up vault")
if self.dry_run: if self.dry_run:
alerts.dryrun(f"Backup up vault to: {self.backup_path}") alerts.dryrun(f"Backup up vault to: {self.backup_path}")
print("\n") console.print("\n")
return return
try: try:
@@ -357,14 +357,14 @@ class Vault:
table.add_row("Active filters", str(len(self.filters))) table.add_row("Active filters", str(len(self.filters)))
table.add_row("Notes with changes", str(len(self.get_changed_notes()))) table.add_row("Notes with changes", str(len(self.get_changed_notes())))
Console().print(table) console.print(table)
def list_editable_notes(self) -> None: def list_editable_notes(self) -> None:
"""Print a list of notes within the scope that are being edited.""" """Print a list of notes within the scope that are being edited."""
table = Table(title="Notes in current scope", show_header=False, box=box.HORIZONTALS) table = Table(title="Notes in current scope", show_header=False, box=box.HORIZONTALS)
for _n, _note in enumerate(self.notes_in_scope, start=1): for _n, _note in enumerate(self.notes_in_scope, start=1):
table.add_row(str(_n), str(_note.note_path.relative_to(self.vault_path))) table.add_row(str(_n), str(_note.note_path.relative_to(self.vault_path)))
Console().print(table) console.print(table)
def num_excluded_notes(self) -> int: def num_excluded_notes(self) -> int:
"""Count number of excluded notes.""" """Count number of excluded notes."""