Skip to content

Commit

Permalink
replace as_bytes with write_to
Browse files Browse the repository at this point in the history
  • Loading branch information
fcurella committed Aug 18, 2023
1 parent 8a14947 commit 9273323
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 25 deletions.
21 changes: 10 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ with open("fonts/MyFont.ttf") as fh:
```

### Methods
- [`as_bytes`](#as_bytes)
- [`clone`](#clone)
- [`close`](#close)
- [`get_characters`](#get_characters)
Expand Down Expand Up @@ -78,17 +77,8 @@ with open("fonts/MyFont.ttf") as fh:
- [`subset`](#subset)
- [`to_sliced_variable`](#to_sliced_variable)
- [`to_static`](#to_static)
- [`write_to`](#write_to)

#### `as_bytes`
```python
"""
Exports the font as a bytes object.
:returns: The font as bytes that can be written to any file object.
:rtype: bytes
"""
data = font.as_bytes()
```
#### `clone`
```python
"""
Expand Down Expand Up @@ -691,6 +681,15 @@ If coordinates are not specified each axis will be pinned at its default value.
"""
font.to_static(coordinates=None, **options)
```
#### `write_to`
```python
"""
Writes the font to a file-like object.
:param fileobject: A file-like object to write to.
"""
font.write_to(fh)
```

## Testing
```bash
Expand Down
15 changes: 4 additions & 11 deletions fontbro/font.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import sys
import tempfile
from curses import ascii
from io import BytesIO
from pathlib import Path

import fsutil
Expand Down Expand Up @@ -1096,20 +1095,14 @@ def save_as_woff2(self, filepath=None, overwrite=True):
flavor=self.FORMAT_WOFF2, filepath=filepath, overwrite=overwrite
)

def as_bytes(self):
def write_to(self, fileobject):
"""
Exports the font as a bytes object.
Writes the font to a file-like object.
:returns: The font as bytes that can be written to any file object.
:rtype: bytes
:param fileobject: A file-like object to write to.
"""
tmp = BytesIO()
font = self.get_ttfont()
font.save(tmp)
tmp.seek(0)
content = tmp.read()
tmp.close()
return content
font.save(fileobject)

def set_name(self, key, value):
"""
Expand Down
10 changes: 7 additions & 3 deletions tests/test_save.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from io import BytesIO

from fontbro import Font
from tests import AbstractTestCase

Expand Down Expand Up @@ -37,10 +39,12 @@ def test_save_fileobject_error(self):
with self.assertRaises(ValueError):
font.save()

def test_as_bytes(self):
def test_write_to(self):
font = self._get_font("/Roboto_Mono/static/RobotoMono-Regular.ttf")

content = font.as_bytes()
buf = BytesIO()
font.write_to(buf)
buf.seek(0)
content = buf.read()
# 00 01 00 00 00 is the file signature for TrueType fonts
self.assertEqual(content[:5], b"\x00\x01\x00\x00\x00")

Expand Down

0 comments on commit 9273323

Please sign in to comment.