Skip to content

Commit

Permalink
Merge pull request #26 from mxstack/pathlib
Browse files Browse the repository at this point in the history
Use pathlib
  • Loading branch information
jensens authored Feb 27, 2024
2 parents dcf3d35 + cab0d34 commit 91c553b
Show file tree
Hide file tree
Showing 13 changed files with 115 additions and 114 deletions.
2 changes: 2 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@

- Drop Python 3.7 support.

- Use `pathlib.Path` instead of `os.path`.

## 1.0a3 (2024-02-06)

- Add `typecheck` target and use it for mypy instead of `check` target.
Expand Down
14 changes: 6 additions & 8 deletions src/mxmake/hook.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
from mxmake.utils import list_value
from mxmake.utils import NAMESPACE
from mxmake.utils import ns_name
from pathlib import Path

import logging
import mxdev
import os


logger = logging.getLogger("mxmake")
Expand Down Expand Up @@ -46,17 +46,15 @@ def generate_templates(self, state: mxdev.State):
def generate_additional_sources_targets(self, state: mxdev.State):
config = state.configuration
additional_sources_targets = []
sources_folder = config.settings.get("default-target", "sources")
sources_folder = Path(config.settings.get("default-target", "sources"))
for package_name in config.packages:
source_folder = os.path.join(sources_folder, package_name)
source_folder = sources_folder / package_name
# case new source package has been added to mx.ini
if not os.path.exists(source_folder):
if not source_folder.exists():
continue
for child in os.listdir(source_folder):
for child in source_folder.iterdir():
if child in ADDITIONAL_SOURCES_TARGETS:
additional_sources_targets.append(
os.path.join(source_folder, child)
)
additional_sources_targets.append(source_folder / child)
if not additional_sources_targets:
return
environment = get_template_environment()
Expand Down
8 changes: 4 additions & 4 deletions src/mxmake/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@
from mxmake.topics import resolve_domain_dependencies
from mxmake.topics import set_domain_runtime_depends
from operator import attrgetter
from pathlib import Path
from textwrap import indent

import argparse
import inquirer
import logging
import mxdev
import os
import sys


Expand Down Expand Up @@ -99,10 +99,10 @@ def init_command(args: argparse.Namespace):
print("#######################\n")

# obtain target folder
target_folder = os.getcwd()
target_folder = Path.cwd()

# parse existing makefile
parser = MakefileParser(os.path.join(target_folder, "Makefile"))
parser = MakefileParser(target_folder / "Makefile")

# obtain topics to include
topics = load_topics()
Expand Down Expand Up @@ -186,7 +186,7 @@ def init_command(args: argparse.Namespace):
print("Skip generation of Makefile, nothing selected")

# mx ini generation
if not os.path.exists(os.path.join(target_folder, "mx.ini")):
if not (target_folder / "mx.ini").exists():
print("\n``mx.ini`` configuration file not exists. Create One?")
yn = inquirer.text(message="Y/n")
if yn not in ["n", "N"]:
Expand Down
8 changes: 4 additions & 4 deletions src/mxmake/parser.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from mxmake.topics import get_domain
from pathlib import Path

import os
import typing


Expand All @@ -11,7 +11,7 @@ class SettingMissing(Exception):


class MakefileParser:
def __init__(self, path: str):
def __init__(self, path: Path):
self.path = path
self.fqns: typing.List = []
self.topics: typing.Dict = {}
Expand Down Expand Up @@ -61,9 +61,9 @@ def parse_setting(self, lines: typing.List[str], name: str) -> str:
return value

def parse(self) -> None:
if not os.path.exists(self.path):
if not self.path.exists():
return
with open(self.path) as fd:
with self.path.open() as fd:
lines = [line.rstrip() for line in fd.readlines() if line.strip()]
self.parse_fqns(lines)
self.parse_settings(lines)
43 changes: 22 additions & 21 deletions src/mxmake/templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@
from mxmake.utils import gh_actions_path
from mxmake.utils import mxmake_files
from mxmake.utils import ns_name
from pathlib import Path

import abc
import io
import mxdev
import os
import typing


Expand Down Expand Up @@ -58,7 +58,7 @@ def __init__(
self.environment = environment

@abc.abstractproperty
def target_folder(self) -> str:
def target_folder(self) -> Path:
"""Target folder for rendered template."""

@abc.abstractproperty
Expand All @@ -78,20 +78,21 @@ def write(self) -> None:
if not self.environment:
raise RuntimeError("Cannot write template without environment")
target_folder = self.target_folder
os.makedirs(target_folder, exist_ok=True)
target_path = os.path.join(target_folder, self.target_name)
target_folder.mkdir(exist_ok=True)
target_path = target_folder / self.target_name
template = self.environment.get_template(self.template_name)
with open(target_path, "w") as f:
with target_path.open("w") as f:
f.write(template.render(**self.template_variables))
os.chmod(target_path, self.file_mode)
target_path.chmod(self.file_mode)

def remove(self) -> bool:
"""Remove rendered template if exists. Return bool if file existed."""
target_path = os.path.join(self.target_folder, self.target_name)
if os.path.exists(target_path):
os.remove(target_path)
return True
return False
target_path = self.target_folder / self.target_name
try:
target_path.unlink()
except FileNotFoundError:
return False
return True


class MxIniBoundTemplate(Template):
Expand Down Expand Up @@ -141,7 +142,7 @@ def test_runner(self):
return self.config.settings.get("mxmake-test-runner", "pytest")

@property
def target_folder(self) -> str:
def target_folder(self) -> Path:
return mxmake_files()

@property
Expand Down Expand Up @@ -208,7 +209,7 @@ class PipConf(MxIniBoundTemplate):
template_name: str = "pip.conf"

@property
def target_folder(self) -> str:
def target_folder(self) -> Path:
return mxmake_files()

@property
Expand All @@ -232,11 +233,11 @@ class Makefile(Template):
description: str = "Makefile"
target_name = "Makefile"
template_name = "Makefile"
target_folder = ""
target_folder = Path()

def __init__(
self,
target_folder: str,
target_folder: Path,
domains: typing.List[Domain],
domain_settings: typing.Dict[str, str],
environment: typing.Union[Environment, None] = None,
Expand Down Expand Up @@ -306,7 +307,7 @@ def __init__(
self.additional_sources_targets = additional_sources_targets

@property
def target_folder(self) -> str:
def target_folder(self) -> Path:
return mxmake_files()

@property
Expand All @@ -324,11 +325,11 @@ class MxIni(Template):
description: str = "mx configutation file"
target_name = "mx.ini"
template_name = "mx.ini"
target_folder = ""
target_folder = Path()

def __init__(
self,
target_folder: str,
target_folder: Path,
domains: typing.List[Domain],
environment: typing.Union[Environment, None] = None,
) -> None:
Expand Down Expand Up @@ -357,7 +358,7 @@ class Topics(Template):
description: str = "Topics documentation for sphinx"
target_name = ""
template_name = "topics.md"
target_folder = ""
target_folder = Path()

@property
def template_variables(self) -> typing.Dict[str, typing.Any]:
Expand Down Expand Up @@ -386,7 +387,7 @@ class Dependencies(Template):
description: str = "Dependencies documentation for sphinx"
target_name = ""
template_name = "dependencies.md"
target_folder = ""
target_folder = Path()

@property
def template_variables(self) -> typing.Dict[str, typing.Any]:
Expand Down Expand Up @@ -426,7 +427,7 @@ class GHActionsTemplate(Template):
template_variables = dict()

@property
def target_folder(self) -> str:
def target_folder(self) -> Path:
return gh_actions_path()


Expand Down
9 changes: 5 additions & 4 deletions src/mxmake/testing/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from contextlib import contextmanager
from mxmake import templates
from pathlib import Path

import doctest
import mxdev
Expand All @@ -11,7 +12,7 @@


def temp_directory(fn):
tempdir = tempfile.mkdtemp()
tempdir = Path(tempfile.mkdtemp())

def wrapper(self):
try:
Expand All @@ -38,9 +39,9 @@ def __init__(self, reset_registry: bool = False):

def __call__(self, fn: typing.Callable):
def wrapper(*a):
tempdir = tempfile.mkdtemp()
os.environ["MXMAKE_FILES"] = tempdir
os.environ["MXMAKE_GH_ACTIONS_PATH"] = tempdir
tempdir = Path(tempfile.mkdtemp())
os.environ["MXMAKE_FILES"] = str(tempdir)
os.environ["MXMAKE_GH_ACTIONS_PATH"] = str(tempdir)
try:
if self.reset_registry:
with reset_template_registry():
Expand Down
7 changes: 3 additions & 4 deletions src/mxmake/tests/test_hook.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,13 @@
from mxmake import testing

import mxdev
import os
import pathlib
import unittest


class TestHook(unittest.TestCase):
@testing.template_directory()
def test_Hook(self, tempdir):
mxini = pathlib.Path(tempdir, "mx.ini")
mxini = tempdir / "mx.ini"
with mxini.open("w") as fd:
fd.write(
"[settings]\n" "mxmake-templates = run-tests run-coverage inexistent"
Expand All @@ -21,5 +19,6 @@ def test_Hook(self, tempdir):
state = mxdev.State(configuration=configuration)
hook_.write(state)
self.assertEqual(
sorted(os.listdir(tempdir)), ["mx.ini", "run-coverage.sh", "run-tests.sh"]
[entry.name for entry in sorted(tempdir.iterdir())],
["mx.ini", "run-coverage.sh", "run-tests.sh"],
)
3 changes: 1 addition & 2 deletions src/mxmake/tests/test_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from mxmake import testing
from mxmake import topics

import os
import unittest


Expand Down Expand Up @@ -37,7 +36,7 @@ def test_MakefileParser(self, tempdir):

template.write()

makefile_path = os.path.join(tempdir, "Makefile")
makefile_path = tempdir / "Makefile"
makefile_parser = parser.MakefileParser(makefile_path)

self.assertEqual(
Expand Down
Loading

0 comments on commit 91c553b

Please sign in to comment.