Skip to content

Commit

Permalink
Implement helper function to format a Python codebase
Browse files Browse the repository at this point in the history
  • Loading branch information
ericof committed May 17, 2024
1 parent 9f5951b commit c7926a5
Show file tree
Hide file tree
Showing 7 changed files with 75 additions and 2 deletions.
2 changes: 1 addition & 1 deletion CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

### Bug fixes:

- Small fixes to cookieplone/utils/plone.py functions [@ericof]
- Small fixes to cookieplone/utils/plone.py functions [@ericof]

## 0.6.0 (2024-05-17)

Expand Down
2 changes: 1 addition & 1 deletion cookieplone/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@
from typing import Annotated

import typer
from cookiecutter.log import configure_logger
from rich.prompt import Prompt

from cookieplone import data, settings
from cookieplone.exceptions import GeneratorException
from cookieplone.generator import generate
from cookieplone.logger import configure_logger
from cookieplone.repository import get_base_repository, get_template_options
from cookieplone.utils import console, files, internal

Expand Down
41 changes: 41 additions & 0 deletions cookieplone/logger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import logging
import sys

from cookiecutter.log import LOG_FORMATS, LOG_LEVELS
from cookiecutter.log import configure_logger as cookicutter_logger

logger = logging.getLogger("cookieplone")


def configure_logger(stream_level="DEBUG", debug_file=None):
"""Configure logging for cookiecutter.
Set up logging to stdout with given level. If ``debug_file`` is given set
up logging to file with DEBUG level.
"""
logger.setLevel(logging.DEBUG)

# Remove all attached handlers, in case there was
# a logger with using the name 'cookiecutter'
del logger.handlers[:]

# Create a file handler if a log file is provided
if debug_file is not None:
debug_formatter = logging.Formatter(LOG_FORMATS["DEBUG"])
file_handler = logging.FileHandler(debug_file)
file_handler.setLevel(LOG_LEVELS["DEBUG"])
file_handler.setFormatter(debug_formatter)
logger.addHandler(file_handler)

# Get settings based on the given stream_level
log_formatter = logging.Formatter(LOG_FORMATS[stream_level])
log_level = LOG_LEVELS[stream_level]

# Create a stream handler
stream_handler = logging.StreamHandler(stream=sys.stdout)
stream_handler.setLevel(log_level)
stream_handler.setFormatter(log_formatter)
logger.addHandler(stream_handler)

# Configure cookiecutter logger
cookicutter_logger(stream_level, debug_file)
27 changes: 27 additions & 0 deletions cookieplone/utils/plone.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import subprocess
from pathlib import Path

import xmltodict

from cookieplone.logger import logger


def add_dependency_profile_to_metadata(profile: str, raw_xml: str) -> str:
"""Inject a dependency into the metadata.xml file."""
Expand All @@ -25,3 +30,25 @@ def add_dependency_to_zcml(package: str, raw_xml: str) -> str:
data["configure"]["include"].append({"@package": f"{package}"})
raw_xml = xmltodict.unparse(data, short_empty_elements=True, pretty=True)
return raw_xml


PY_FORMATTERS = (
("zpretty", "-i", "./"),
("isort", "./"),
("black", "./"),
)


def format_python_codebase(path: Path):
"""Format a Python codebase after code generation."""
# Ensure there is a pyproject.toml
pyproject = path / "pyproject.toml"
if not pyproject.exists():
logger.info(f"Format codebase: No pyproject.toml found in {path}, stopping")
# Run formatters
for cmd in PY_FORMATTERS:
logger.debug(f"Format codebase: Running {cmd}")
proc = subprocess.run(cmd, shell=False, cwd=path, capture_output=True) # noQA:S603
if proc.returncode:
# Write errors to the main process stderr
logger.info(f"Error while running {cmd}:")
1 change: 1 addition & 0 deletions news/+format_python_codebase.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add helper function to format a Python codebase [@ericof]
1 change: 1 addition & 0 deletions news/+logger.internal
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Configure logger for cookieplone [@ericof]
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ dependencies = [
"packaging==24.0",
"gitpython==3.1.43",
"xmltodict==0.13.0",
"black",
"isort",
"zpretty"
]

[project.scripts]
Expand Down

0 comments on commit c7926a5

Please sign in to comment.