Skip to content

Commit

Permalink
Add suport for python-brace-format
Browse files Browse the repository at this point in the history
Building upon python-babel#838, this adds support for python-brace-format flags in
the python extractor.

Fixes python-babel#333
  • Loading branch information
ljodal committed Feb 1, 2022
1 parent dc224f9 commit bc3ead8
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 2 deletions.
5 changes: 4 additions & 1 deletion babel/messages/extract.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
import sys
from tokenize import generate_tokens, COMMENT, NAME, OP, STRING

from babel.util import parse_encoding, parse_future_flags, pathmatch, has_python_format
from babel.util import parse_encoding, parse_future_flags, pathmatch, has_python_format, has_python_brace_format
from textwrap import dedent


Expand Down Expand Up @@ -480,6 +480,9 @@ def extract_python(fileobj, keywords, comment_tags, options):
if has_python_format(message for message in messages if message):
flags.add("python-format")

if has_python_brace_format(message for message in messages if message):
flags.add('python-brace-format')

if len(messages) > 1:
messages = tuple(messages)
else:
Expand Down
14 changes: 14 additions & 0 deletions babel/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import re
import textwrap
import pytz as _pytz
import string
from babel import localtime

missing = object()
Expand Down Expand Up @@ -281,3 +282,16 @@ def has_python_format(ids):
if isinstance(ids, str):
ids = [ids]
return any(PYTHON_FORMAT.search(id) for id in ids)


FORMATTER = string.Formatter()


def has_python_brace_format(ids):
if isinstance(ids, str):
ids = [ids]
return any(
field_name
for message_id in ids
for _, field_name, format_spec, conversion in FORMATTER.parse(message_id)
)
19 changes: 18 additions & 1 deletion tests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
import pytest

from babel import util
from babel.util import parse_future_flags, has_python_format
from babel.util import parse_future_flags, has_python_format, has_python_brace_format


class _FF:
Expand Down Expand Up @@ -124,6 +124,23 @@ def test_has_python_format(ids):

@pytest.mark.parametrize('ids', [
('foo',),
('foo {name}',),
])
def test_not_has_python_format(ids):
assert not has_python_format(ids)

@pytest.mark.parametrize('ids', [
('foo {name} bar',),
('foo {name:.3f} bar',),
('foo {name!r:20} bar',),
])
def test_has_python_brace_format(ids):
assert has_python_brace_format(ids)

@pytest.mark.parametrize('ids', [
('foo',),
('fo {}', ),
('foo %d bar',),
])
def test_not_has_python_brace_format(ids):
assert not has_python_brace_format(ids)

0 comments on commit bc3ead8

Please sign in to comment.