Skip to content

Commit

Permalink
clean up printing
Browse files Browse the repository at this point in the history
  • Loading branch information
carderne committed Aug 26, 2024
1 parent 2430a50 commit f820c55
Show file tree
Hide file tree
Showing 7 changed files with 137 additions and 156 deletions.
17 changes: 1 addition & 16 deletions una/check.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import difflib
from pathlib import Path

from rich.console import Console

from una import defaults, distributions, package_deps, parse, stdlib
from una import distributions, package_deps, parse, stdlib
from una.types import CheckDiff, Imports, PackageDeps


Expand All @@ -19,11 +17,6 @@ def check_package_deps(root: Path, ns: str, package: PackageDeps, alias: list[st
return diff


def print_check_results(diff: CheckDiff) -> None:
_print_missing_deps(diff.int_dep_diff, diff.package.name)
_print_missing_deps(diff.ext_dep_diff, diff.package.name)


def _extract_int_deps(paths: set[Path], ns: str) -> Imports:
all_imports = parse.fetch_all_imports(paths)
return _extract_int_dep_imports(all_imports, ns)
Expand Down Expand Up @@ -64,14 +57,6 @@ def _fetch_int_dep_imports(root: Path, ns: str, all_imports: Imports) -> Imports
return res


def _print_missing_deps(diff: set[str], package_name: str) -> None:
if not diff:
return
console = Console(theme=defaults.RICH_THEME)
missing = ", ".join(sorted(diff))
console.print(f":thinking_face: Cannot locate {missing} in {package_name}")


def _collect_all_imports(root: Path, ns: str, package: PackageDeps) -> tuple[Imports, Imports]:
dep_pkgs = {c for c in package.int_deps}
all_paths = [c.path for c in package_deps.get_package_confs(root)]
Expand Down
48 changes: 43 additions & 5 deletions una/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
from typing import Annotated

from rich.console import Console
from rich.theme import Theme
from typer import Argument, Exit, Option, Typer

from una import check, config, defaults, files, package_deps, sync
from una import check, config, files, package_deps, sync
from una.types import CheckDiff

app = Typer(name="una", no_args_is_help=True, add_completion=False)
Expand All @@ -16,6 +17,17 @@
)


def rich_console() -> Console:
theme = Theme(
{
"dat": "#999966",
"pkg": "#8A2BE2",
"dep": "#32CD32",
}
)
return Console(theme=theme)


@app.command("sync")
def sync_command(
check_only: Annotated[bool, Option(help="Only check, make no changes")] = False,
Expand All @@ -39,12 +51,38 @@ def sync_command(
failed = any(d.int_dep_diff or d.ext_dep_diff for d in diffs)
if failed:
for d in diffs:
check.print_check_results(d)
console = rich_console()
missing_ext = ", ".join(sorted(d.ext_dep_diff))
missing_int = ", ".join(sorted(d.int_dep_diff))
console.print(f"Cannot locate {missing_ext} in {d.package.name}")
console.print(f"Cannot locate {missing_int} in {d.package.name}")
raise Exit(code=1)

else:
for d in diffs:
sync.sync_package_int_deps(d, ns, quiet)
sync.sync_package_int_deps(d, ns)

if not quiet:
_print_summary(d)
_print_int_dep_imports(d)


def _print_int_dep_imports(diff: CheckDiff) -> None:
console = rich_console()
for key, values in diff.int_dep_imports.items():
imports_in_int_dep = values.difference({key})
if not imports_in_int_dep:
continue
joined = ", ".join(imports_in_int_dep)
message = f":information: [dat]{key}[/] is importing [dat]{joined}[/]"
console.print(message)


def _print_summary(diff: CheckDiff) -> None:
console = rich_console()
name = diff.package.name
for c in diff.int_dep_diff:
console.print(f"adding dep [dep]{c}[/] to [pkg]{name}[/]")


@create.command("package")
Expand All @@ -55,7 +93,7 @@ def create_package_command(
"""Creates an Una package."""
root = config.get_workspace_root()
files.create_package(root, name, path, "", "", "")
console = Console(theme=defaults.RICH_THEME)
console = rich_console()
console.print("Success!")
console.print(f"Created package {name}")

Expand All @@ -67,7 +105,7 @@ def create_workspace_command():
root = config.get_workspace_root()
ns = config.get_ns(root)
files.create_workspace(path, ns)
console = Console(theme=defaults.RICH_THEME)
console = rich_console()
console.print("Success!")
console.print("Set up workspace in current directory.")
console.print("Remember to delete the src/ directory")
8 changes: 4 additions & 4 deletions una/config.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from functools import lru_cache
from pathlib import Path

from una import defaults
from una import consts
from una.types import Conf


Expand All @@ -17,7 +17,7 @@ def _load_conf(path: Path) -> Conf:


def load_conf(path: Path) -> Conf:
fullpath = (path / defaults.PYPROJ_FILE).resolve()
fullpath = (path / consts.PYPROJ_FILE).resolve()
return _load_conf(fullpath)


Expand All @@ -35,7 +35,7 @@ def get_members(path: Path) -> list[str]:

def get_workspace_root() -> Path:
cwd = Path.cwd()
root = _find_upwards_dir(cwd, defaults.ROOT_FILE)
root = _find_upwards_dir(cwd, consts.ROOT_FILE)
if not root:
raise ValueError("Didn't find the workspace root. Expected to find a .git directory.")
return root
Expand All @@ -46,7 +46,7 @@ def _is_drive_root(cwd: Path) -> bool:


def _is_repo_root(cwd: Path) -> bool:
fullpath = cwd / defaults.ROOT_FILE
fullpath = cwd / consts.ROOT_FILE
return fullpath.exists()


Expand Down
3 changes: 3 additions & 0 deletions una/consts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
KEEP_FILE = ".keep"
ROOT_FILE = ".git"
PYPROJ_FILE = "pyproject.toml"
74 changes: 0 additions & 74 deletions una/defaults.py

This file was deleted.

95 changes: 78 additions & 17 deletions una/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,89 @@

import tomlkit

from una import config, defaults
from una import config, consts

_EXAMPLE_APP_NAME = "printer"
_EXAMPLE_LIB_NAME = "greeter"
_EXAMPLE_MEMBERS = ["apps/*", "libs/*"]
_EXAMPLE_IMPORT = "cowsay-python==1.0.2"

_TEMPLATE_PYPROJ = """\
[project]
name = "{name}"
version = "0.1.0"
description = ""
authors = []
dependencies = [{dependencies}]
requires-python = "{python_version}"
dynamic = ["una"] # needed for hatch-una metadata hook to work
[build-system]
requires = ["hatchling", "hatch-una"]
build-backend = "hatchling.build"
[tool.hatch.metadata]
allow-direct-references = true
[tool.rye]
managed = true
dev-dependencies = []
[tool.hatch.build.hooks.una-build]
[tool.hatch.metadata.hooks.una-meta]
[tool.una.deps]
{internal_deps}
"""

_EXAMPLE_INTERNAL_DEPS = """\
"../../libs/{dep_name}/{ns}/{dep_name}" = "{ns}/{dep_name}"
"""

_EXAMPLE_APP_CODE = """\
import {ns}.{lib_name} as {lib_name}
def run() -> None:
print({lib_name}.greet())
"""

_EXAMPLE_LIB_CODE = """\
import cowsay
def greet() -> str:
return cowsay.say("Hello from una!")
"""

_TEMPLATE_TEST_CODE = """\
from {ns} import {name}
def test_import():
assert {name}
"""


def create_workspace(path: Path, ns: str) -> None:
app_content = defaults.EXAMPLE_APP_CODE.format(ns=ns, lib_name=defaults.EXAMPLE_LIB_NAME)
lib_content = defaults.EXAMPLE_LIB_CODE
app_content = _EXAMPLE_APP_CODE.format(ns=ns, lib_name=_EXAMPLE_LIB_NAME)
lib_content = _EXAMPLE_LIB_CODE

_update_root_pyproj(path, ns, defaults.EXAMPLE_IMPORT)
_update_root_pyproj(path, ns, _EXAMPLE_IMPORT)
create_package(
path,
defaults.EXAMPLE_APP_NAME,
_EXAMPLE_APP_NAME,
"apps",
app_content,
"",
defaults.EXAMPLE_INTERNAL_DEPS,
_EXAMPLE_INTERNAL_DEPS.format(ns=ns, dep_name=_EXAMPLE_LIB_NAME),
)
create_package(
path,
defaults.EXAMPLE_LIB_NAME,
_EXAMPLE_LIB_NAME,
"libs",
lib_content,
f'"{defaults.EXAMPLE_IMPORT}"',
f'"{_EXAMPLE_IMPORT}"',
"",
)

Expand Down Expand Up @@ -51,17 +112,17 @@ def create_package(
_create_file(
test_dir,
f"test_{name}_import.py",
content=defaults.TEMPLATE_TEST_CODE.format(ns=ns, name=name),
content=_TEMPLATE_TEST_CODE.format(ns=ns, name=name),
)
pyproj_content = defaults.TEMPLATE_PYPROJ.format(
pyproj_content = _TEMPLATE_PYPROJ.format(
name=name,
python_version=python_version,
dependencies=dependencies,
internal_deps=internal_deps,
)
_create_file(
package_dir,
defaults.PYPROJ_FILE,
consts.PYPROJ_FILE,
pyproj_content,
)

Expand All @@ -80,17 +141,17 @@ def _create_dir(path: Path, dir_name: str, keep: bool = False) -> Path:
d = path / dir_name
d.mkdir(parents=True)
if keep:
_create_file(d, defaults.KEEP_FILE)
_create_file(d, consts.KEEP_FILE)
return d


def _update_root_pyproj(path: Path, ns: str, dependencies: str) -> None:
pyproj = path / defaults.PYPROJ_FILE
pyproj = path / consts.PYPROJ_FILE
with pyproj.open() as f:
toml = tomlkit.parse(f.read())

toml["tool"]["rye"]["virtual"] = True # type:ignore[reportIndexIssues]
toml["tool"]["rye"]["workspace"] = {"member": defaults.EXAMPLE_MEMBERS} # type:ignore[reportIndexIssues]
toml["tool"]["una"] = {"members": defaults.EXAMPLE_MEMBERS} # type:ignore[reportIndexIssues]
toml["tool"]["rye"]["virtual"] = True # pyright:ignore[reportIndexIssue]
toml["tool"]["rye"]["workspace"] = {"member": _EXAMPLE_MEMBERS} # pyright:ignore[reportIndexIssue]
toml["tool"]["una"] = {"members": _EXAMPLE_MEMBERS} # pyright:ignore[reportIndexIssue]
with pyproj.open("w") as f:
f.write(tomlkit.dumps(toml)) # type:ignore[reportUnknownMemberType]
f.write(tomlkit.dumps(toml)) # pyright:ignore[reportUnknownMemberType]
Loading

0 comments on commit f820c55

Please sign in to comment.