Skip to content

Commit

Permalink
Add a general rename command (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
lalmei authored Dec 1, 2022
1 parent f6cbf53 commit 36b446c
Show file tree
Hide file tree
Showing 22 changed files with 170 additions and 67 deletions.
15 changes: 15 additions & 0 deletions .dependabot.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
version: 2
- package-ecosystem: "pip"
directory: "/"
schedule:
interval: "weekly"
day: "friday"
assignees:
- "octocat"
reviewers:
- "lalmei"
labels:
- "dependencies"
- "python"
open-pull-requests-limit: 5

17 changes: 17 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# EditorConfig is awesome: http://EditorConfig.org

root = true

[*]
indent_style = space
indent_size = 4
trim_trailing_whitespace = true
insert_final_newline = true
end_of_line = lf

[*.md]
trim_trailing_whitespace = false

[Makefile]
indent_style = tab
trim_trailing_whitespace = false
2 changes: 1 addition & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ jobs:
matrix:
python-version: ['3.10','3.11']
poetry-version: ['1.2.2']
os: [ubuntu-latest, macosx-latest]
os: [ubuntu-latest]
fail-fast: false
steps:
- uses: actions/checkout@v3
Expand Down
2 changes: 1 addition & 1 deletion config/.isort.cfg
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[settings]
line_length = 120
line_length = 80
multi_line_output = 3
balanced_wrapping = true
default_section = "THIRDPARTY"
Expand Down
2 changes: 1 addition & 1 deletion config/flake8.ini
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ classmethod-decorators =
validator
exclude = fixtures,docs,site
show-source = true
max-line-length = 140
max-line-length = 80
statistics = True
docstring-convention = google
ban-relative-imports = true
Expand Down
2 changes: 1 addition & 1 deletion config/flake8_all.ini
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ classmethod-decorators =
exclude = fixtures,docs,site
show-source = true
color = true
max-line-length = 140
max-line-length = 80
statistics = true
bug-report = true
docstring-convention = google
Expand Down
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,6 @@ mkdocs-gitlab-plugin = "^0.1.4"
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"

[tool.black]
line-length = 80
36 changes: 10 additions & 26 deletions src/asunder/command/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

from asunder._version import version_info
from asunder.command.rename_cmd import app as refactor
from asunder.utils.logging import get_logger_console

app = typer.Typer(
add_completion=True, invoke_without_command=True, no_args_is_help=True
Expand All @@ -22,28 +23,6 @@
app.add_typer(refactor, name="refactor")


def _set_up_logger(console: Console) -> logging.Logger:
"""
Log to console with a simple formatter; used by CLI
Parameters
----------
console : Console
rich console with style and colored
Returns
-------
logging.Logger
logger with the CLI name
"""
module_logger = logging.getLogger("asunder")
module_logger.addHandler(RichHandler(rich_tracebacks=True, console=console))
module_logger.setLevel(level=logging.WARNING)

return module_logger


def _version_callback(value: bool) -> None:
"""
Print model version information.
Expand Down Expand Up @@ -72,9 +51,14 @@ def main(
dry_run: Optional[bool] = typer.Option(
False, "--dry-run", help="Show changes but do not execute them"
),
verbose: Optional[bool] = typer.Option(False, "--verbose", help="verbose mode"),
verbose: Optional[bool] = typer.Option(
False, "--verbose", help="verbose mode"
),
version: Optional[bool] = typer.Option(
None, "--version", help="check model version", callback=_version_callback
None,
"--version",
help="check model version",
callback=_version_callback,
),
) -> None:
"""
Expand All @@ -95,8 +79,8 @@ def main(
help="check model version", callback=_version_callback)
"""
console = Console()
logger = _set_up_logger(console)

logger, console = get_logger_console()

if verbose:
logger.setLevel(logging.DEBUG)
Expand Down
21 changes: 15 additions & 6 deletions src/asunder/command/rename_cmd.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,37 @@
import logging
import os
from pathlib import Path
from typing import Optional

import typer
from typer import Context

from asunder.project import Project
from asunder.rope import rename
from asunder.rope_sdk import rename as rename_changes
from asunder.utils.logging import get_logger_console

app = typer.Typer(add_completion=True, no_args_is_help=True)

logger = logging.getLogger("asunder")


@app.command(no_args_is_help=True)
def module(
def rename(
ctx: Context,
path: Path = typer.Option(Path.cwd() / "src", help="path to package source code"),
path: Path = typer.Option(
Path.cwd() / "src", help="path to package source code"
),
module: str = typer.Argument(
"", help='full module name to be renamed, e.g. "package.module"'
"", help='module where renaming will take placed, e.g. "package.module"'
),
old_name: Optional[str] = typer.Option(
"", help="old name of module/class/attribute"
),
name: str = typer.Argument("", help="new module name only"),
name: str = typer.Argument("", help="new module/class/attribute name"),
) -> None:

if not old_name:
old_name = module
dry_run = ctx.obj.get("dry_run", True)

logger, console = get_logger_console()
Expand All @@ -35,7 +44,7 @@ def module(

logger.info("Calculating Changes")
# compute changes needed
changes = rename(project.rope_project, module, name)
changes = rename_changes(project.rope_project, module, old_name, name)

if not dry_run:
logger.info("Perfoming Changes")
Expand Down
4 changes: 3 additions & 1 deletion src/asunder/project/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@


class Project:
def __init__(self, path: Path = Path.cwd(), console: Console = Console()) -> None:
def __init__(
self, path: Path = Path.cwd(), console: Console = Console()
) -> None:

self.rope_project = RopeProject(str(path / "src"))
self.console = console
Expand Down
3 changes: 0 additions & 3 deletions src/asunder/rope/__init__.py

This file was deleted.

13 changes: 0 additions & 13 deletions src/asunder/rope/rename_module.py

This file was deleted.

3 changes: 3 additions & 0 deletions src/asunder/rope_sdk/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from asunder.rope_sdk.refactor.rename.rename import rename, rename_module

__all__: list[str] = ["rename_module, rename"]
3 changes: 3 additions & 0 deletions src/asunder/rope_sdk/find/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from asunder.rope_sdk.find.find import find_definition_in_resource

__all__: list[str] = ["find_definition_in_resource"]
14 changes: 14 additions & 0 deletions src/asunder/rope_sdk/find/find.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from rope.base.project import Project as RopeProject
from rope.refactor.occurrences import Finder


def find_definition_in_resource(
repo_project: RopeProject, name: str, resource: str
):
FINDER = partial(Finder, repo_project)
finder = FINDER(name)
return next(
occ
for occ in finder.find_occurrences(resource=resource)
if occ.is_defined() or occ.is_written()
)
Empty file.
15 changes: 15 additions & 0 deletions src/asunder/rope_sdk/refactor/move/move.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# @app.command()
# def move(ctx: Context,
# path: Path = typer.Option(Path.cwd() / "src",
# help="path to package source code"),
# module: str = typer.Argument(
# "", help='full module name to be renamed, e.g. "package.module"'):

# """
# Move module: --source <module> --target <module> [--do False]
# """
# source_resource = PROJECT.get_resource(source)
# target_resource = PROJECT.get_resource(target)
# mover = create_move(PROJECT, source_resource)
# changes = mover.get_changes(target_resource)
# execute_changes(changes, do)
Empty file.
28 changes: 28 additions & 0 deletions src/asunder/rope_sdk/refactor/rename/rename.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import logging

from rope.base.change import ChangeSet
from rope.base.project import Project as RopeProject
from rope.refactor.rename import Rename

from asunder.rope_sdk.find import find_definition_in_resource

logger = logging.getLogger("asunder")


def rename_module(
rope_project: RopeProject, module: str, to_name: str
) -> ChangeSet:
module_resource = rope_project.get_resource(module)
return Rename(rope_project, module_resource).get_changes(to_name)


def rename(
rope_project: RopeProject, module: str, from_name: str, to_name: str
) -> ChangeSet:
module_resource = rope_project.get_resource(module)
definition_occurrence = find_definition_in_resource(
rope_project, from_name, module_resource
)
return Rename(
rope_project, module_resource, definition_occurrence.offset
).get_changes(to_name)
43 changes: 37 additions & 6 deletions src/asunder/utils/logging.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,51 @@
from logging import Logger, getLogger
from typing import cast
from logging import WARNING, Logger, getLogger
from typing import Optional, cast

from rich.console import Console
from rich.logging import RichHandler


def get_logger_console() -> tuple[Logger, Console]:
def _set_up_logger(console: Optional[Console] = None) -> Logger:
"""
Log to console with a simple formatter; used by CLI
Parameters
----------
console : Console
rich console with style and colored
Returns
-------
logging.Logger
logger with the CLI name
"""
if not console:
console = Console()
module_logger = getLogger("asunder")
module_logger.addHandler(RichHandler(rich_tracebacks=True, console=console))
module_logger.setLevel(level=WARNING)

return module_logger


def get_logger_console(
console: Optional[Console] = None,
) -> tuple[Logger, Console]:

if not console:
console = Console()

logger = getLogger("asunder")

if len(logger.handlers) > 0:

handler: RichHandler = cast(RichHandler, logger.handlers[0])
console = handler.console
print("handler names = ", [handle.__dict__ for handle in logger.handlers])
print(
"handler names = ", [handle.__dict__ for handle in logger.handlers]
)
else:
raise AttributeError("No Handlers in logger")
logger = _set_up_logger(console)
logger.debug("Setting up rich log handler")

return logger, console
4 changes: 3 additions & 1 deletion tests/test_app/test_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ def test_parse_args() -> None:
"""
test verbose mode
"""
verbose_check = re.compile(r"\[[\w*\S*\s*]*\] (INFO Setting verbose mode ON)")
verbose_check = re.compile(
r"\[[\w*\S*\s*]*\] (INFO Setting verbose mode ON)"
)

result = runner.invoke(app, ["--verbose"], input="")
console.print(result.stdout)
Expand Down
7 changes: 0 additions & 7 deletions tests/test_unit/test_rename.py

This file was deleted.

0 comments on commit 36b446c

Please sign in to comment.