Skip to content

Commit

Permalink
Add is_file optional argument to calc_output_path
Browse files Browse the repository at this point in the history
Also:
* Use it in the `Builder`.
* Move `calc_output_path` to `utils.py`.
* Add type annotations.
  • Loading branch information
kojiishi committed Jan 7, 2022
1 parent 4f5b757 commit c4f4a1f
Show file tree
Hide file tree
Showing 9 changed files with 110 additions and 57 deletions.
2 changes: 1 addition & 1 deletion east_asian_spacing/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from east_asian_spacing.config import *
from east_asian_spacing.dump import *
from east_asian_spacing.font import *
from east_asian_spacing.log_utils import *
from east_asian_spacing.shaper import *
from east_asian_spacing.spacing import *
from east_asian_spacing.tester import *
from east_asian_spacing.utils import *
38 changes: 15 additions & 23 deletions east_asian_spacing/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,15 @@
import sys
import time
from typing import Optional
from typing import TextIO
from typing import Union

from east_asian_spacing.config import Config
from east_asian_spacing.font import Font
from east_asian_spacing.log_utils import init_logging
from east_asian_spacing.spacing import EastAsianSpacing
from east_asian_spacing.tester import EastAsianSpacingTester
from east_asian_spacing.utils import calc_output_path
from east_asian_spacing.utils import init_logging

logger = logging.getLogger('build')

Expand All @@ -38,15 +41,19 @@ async def build_and_save(self, output=None, **kwargs):
return self.save(output, **kwargs)

def save(self,
output=None,
stem_suffix=None,
glyph_out=None,
glyph_comment=0,
print_path=False):
output: Optional[pathlib.Path] = None,
stem_suffix: Optional[str] = None,
glyph_out: Optional[Union[pathlib.Path, str, TextIO]] = None,
glyph_comment: int = 0,
print_path: bool = False) -> pathlib.Path:
assert self.has_spacings
font = self.font
path_before_save = font.path
output = self.calc_output_path(path_before_save, output, stem_suffix)
output = calc_output_path(path_before_save,
output,
stem_suffix=stem_suffix,
is_file=output
and Font.is_font_extension(output.suffix))
logger.info('Saving to "%s"', output)
font.save(output)
paths = [output, path_before_save]
Expand All @@ -58,19 +65,6 @@ def save(self,
flush=True) # Flush, for better parallelism when piping.
return output

@staticmethod
def calc_output_path(input_path, output_path, stem_suffix=None):
if output_path:
if isinstance(output_path, str):
output_path = pathlib.Path(output_path)
output_path = output_path / input_path.name
else:
output_path = input_path
if not stem_suffix:
return output_path
return (output_path.parent /
f'{output_path.stem}{stem_suffix}{output_path.suffix}')

async def _config_for_font(self, font: Font) -> Optional[Config]:
config = self.config.for_font(font)
if config is None:
Expand Down Expand Up @@ -166,7 +160,7 @@ def _united_spacings(self):
united_spacing.unite(spacing)
return united_spacing

def save_glyphs(self, output, **kwargs):
def save_glyphs(self, output: Union[pathlib.Path, str, TextIO], **kwargs):
assert self.has_spacings
font = self.font
if isinstance(output, str):
Expand Down Expand Up @@ -281,8 +275,6 @@ async def main():
else:
args.glyph_out = pathlib.Path(args.glyph_out)
args.glyph_out.mkdir(exist_ok=True, parents=True)
if args.output:
args.output.mkdir(exist_ok=True, parents=True)
for input in Builder.expand_paths(args.inputs):
font = Font.load(input)
if font.is_collection:
Expand Down
2 changes: 1 addition & 1 deletion east_asian_spacing/dump.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from typing import Iterable

from east_asian_spacing.font import Font
from east_asian_spacing.log_utils import init_logging
from east_asian_spacing.utils import init_logging

logger = logging.getLogger('dump')

Expand Down
10 changes: 5 additions & 5 deletions east_asian_spacing/shaper.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
import uharfbuzz as hb

from east_asian_spacing.font import Font
import east_asian_spacing.log_utils as log_utils
import east_asian_spacing.utils as utils

logger = logging.getLogger('shaper')

Expand Down Expand Up @@ -381,7 +381,7 @@ async def shape(self, text):
self.language, self.script, features)
# logger.debug('lang=%s, script=%s, features=%s', buffer.language,
# buffer.script, features)
if log_utils._log_shaper_logs:
if utils._log_shaper_logs:
buffer.set_message_func(
lambda message: logger.debug('uharfbuzz: %s', message))
# buffer.cluster_level = hb.BufferClusterLevel.DEFAULT
Expand Down Expand Up @@ -411,7 +411,7 @@ async def shape(self, text):
hb_shape = HbShapeShaper._hb_shape_path or 'hb-shape'
args = [hb_shape, '--output-format=json', '--no-glyph-names']
self.append_hb_args(text, args)
if log_utils._log_shaper_logs:
if utils._log_shaper_logs:
args.append('--trace')
logger.debug('subprocess.run: %s', shlex.join(args))
proc = await asyncio.create_subprocess_exec(
Expand All @@ -421,7 +421,7 @@ async def shape(self, text):
raise CalledProcessError(proc.returncode, hb_shape, stdout, stderr)
with io.StringIO(stdout.decode('utf-8')) as file:
for line in file:
if log_utils._log_shaper_logs:
if utils._log_shaper_logs:
logger.debug('hb-shape: %s', line.rstrip())
if line.startswith('['):
glyphs = json.loads(line)
Expand Down Expand Up @@ -508,7 +508,7 @@ async def main():
default=0)
args = parser.parse_args()
show_dump_images()
log_utils.init_logging(args.verbose)
utils.init_logging(args.verbose)
_init_shaper() # Re-initialize to show logging.
font = Font.load(args.font_path)
if font.is_collection:
Expand Down
4 changes: 2 additions & 2 deletions east_asian_spacing/spacing.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@

from east_asian_spacing.config import Config
from east_asian_spacing.font import Font
import east_asian_spacing.log_utils as log_utils
from east_asian_spacing.shaper import GlyphData, GlyphDataList
from east_asian_spacing.shaper import GlyphDataList
from east_asian_spacing.shaper import InkPart
from east_asian_spacing.shaper import Shaper
from east_asian_spacing.utils import init_logging

logger = logging.getLogger('spacing')
_log_shaper = logging.getLogger('shaper')
Expand Down Expand Up @@ -676,7 +676,7 @@ async def main():
action="count",
default=0)
args = parser.parse_args()
log_utils.init_logging(args.verbose)
init_logging(args.verbose)

font = Font.load(args.path)
if font.is_collection:
Expand Down
2 changes: 1 addition & 1 deletion east_asian_spacing/ttc.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

from fontTools.ttLib.ttCollection import TTCollection

from east_asian_spacing.log_utils import init_logging
from east_asian_spacing.utils import init_logging

logger = logging.getLogger('ttc')

Expand Down
29 changes: 29 additions & 0 deletions east_asian_spacing/log_utils.py → east_asian_spacing/utils.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import logging
import pathlib
from typing import Optional
from typing import Union

_log_shaper_logs = False

Expand Down Expand Up @@ -50,3 +53,29 @@ def init_logging(verbose: int, main=None, debug=None):

global _log_shaper_logs
_log_shaper_logs = True


def calc_output_path(input_path: pathlib.Path,
output_path: Optional[Union[pathlib.Path, str]],
stem_suffix: Optional[str] = None,
is_file: bool = False) -> pathlib.Path:
if output_path:
if not isinstance(output_path, pathlib.Path):
output_path = pathlib.Path(output_path)
if output_path.is_dir():
output_path = output_path / input_path.name
elif output_path.is_file() or is_file:
# `output` is an existing file or a new file.
pass
else:
# `output` is a new directory.
output_path.mkdir(parents=True, exist_ok=True)
output_path = output_path / input_path.name
else:
output_path = input_path

if stem_suffix:
name = f'{output_path.stem}{stem_suffix}{output_path.suffix}'
output_path = output_path.parent / name

return output_path
24 changes: 0 additions & 24 deletions tests/builder_test.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import io
import os
import pathlib
import pytest
import shutil
Expand All @@ -10,29 +9,6 @@
from east_asian_spacing import Font


def test_calc_output_path(data_dir):

def call(input_path, output_path, stem_suffix=None):
input_path = pathlib.Path(input_path)
if output_path:
output_path = pathlib.Path(output_path)
result = Builder.calc_output_path(input_path, output_path, stem_suffix)
return str(result)

assert call('c.otf', None) == 'c.otf'
assert call('a/b/c.otf', None) == os.path.join('a', 'b', 'c.otf')

assert call('c.otf', None, '-chws') == 'c-chws.otf'
assert call('a/b/c.otf', None,
'-chws') == os.path.join('a', 'b', 'c-chws.otf')

assert call('c.otf', 'build') == os.path.join('build', 'c.otf')
assert call('a/b/c.otf', 'build') == os.path.join('build', 'c.otf')

assert call('a/b/c.otf', 'build',
'-xyz') == os.path.join('build', 'c-xyz.otf')


def test_expand_paths(monkeypatch):

def call(items):
Expand Down
56 changes: 56 additions & 0 deletions tests/utils_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import os
import pathlib

from east_asian_spacing import calc_output_path


def test_calc_output_path():

def call(input_path, output_path, stem_suffix=None):
input_path = pathlib.Path(input_path)
if output_path:
output_path = pathlib.Path(output_path)
result = calc_output_path(input_path, output_path, stem_suffix)
return str(result)

assert call('c.otf', None) == 'c.otf'
assert call('a/b/c.otf', None) == os.path.join('a', 'b', 'c.otf')

assert call('c.otf', None, '-chws') == 'c-chws.otf'
assert call('a/b/c.otf', None,
'-chws') == os.path.join('a', 'b', 'c-chws.otf')

assert call('c.otf', 'build') == os.path.join('build', 'c.otf')
assert call('a/b/c.otf', 'build') == os.path.join('build', 'c.otf')

assert call('a/b/c.otf', 'build',
'-xyz') == os.path.join('build', 'c-xyz.otf')


def test_calc_output_path_dir(tmp_path: pathlib.Path):
name = 'name'
input = pathlib.Path('in') / name

# `output` should be a directory if it's an existing directory.
output = tmp_path / 'dir'
output.mkdir()
result = calc_output_path(input, output)
assert result == output / name

# `output` should be a file if it's an existing file.
output = tmp_path / 'file'
output.write_text('test')
result = calc_output_path(input, output)
assert result == output

# `output` should be a directory if it does not exist.
output = tmp_path / 'new_dir'
result = calc_output_path(input, output)
assert result == output / name
assert output.is_dir()

# `output` should be a file if it does not exist and `is_file=True`.
output = tmp_path / 'new_file'
result = calc_output_path(input, output, is_file=True)
assert result == output
assert not output.exists()

0 comments on commit c4f4a1f

Please sign in to comment.