Skip to content

Commit

Permalink
Add directory(location) contextmanager
Browse files Browse the repository at this point in the history
  • Loading branch information
mdrachuk committed Nov 12, 2019
1 parent 4151702 commit 1d5e3d8
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 2 deletions.
2 changes: 1 addition & 1 deletion lightweight/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@
from .path import SitePath
from .template import template

__version__ = '1.0.0.dev22'
__version__ = '1.0.0.dev23'
19 changes: 18 additions & 1 deletion lightweight/files.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import os
from contextlib import contextmanager
from glob import iglob
from pathlib import Path
from typing import Iterator, Optional, Union
from typing import Iterator, Union


def paths(glob: Union[str, Path]) -> Iterator[Path]:
Expand All @@ -11,3 +13,18 @@ def paths(glob: Union[str, Path]) -> Iterator[Path]:
return iter([glob])
return map(Path, iglob(glob, recursive=True))


@contextmanager
def directory(location: str):
"""Execute the following statements with provided location as "cwd" (current working directory).
:Example:
project_location = os.path.dirname(os.path.realpath(__file__))
with directory(project_location):
site.include('index.html')
"""
cwd = os.getcwd()
os.chdir(location)
yield
os.chdir(cwd)
6 changes: 6 additions & 0 deletions tests/test_paths.py → tests/test_files.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from pathlib import Path

from lightweight import paths
from lightweight.files import directory


def test_dir():
Expand All @@ -24,3 +25,8 @@ def test_recursive_files():

def test_path():
assert set(paths(Path('resources/test.html'))) == {Path('resources/test.html')}


def test_directory():
with directory('site'), open('file') as f:
assert 'A test file.' == f.read()

0 comments on commit 1d5e3d8

Please sign in to comment.