Skip to content

Commit

Permalink
feat: add functions to extract field names from string formats
Browse files Browse the repository at this point in the history
  • Loading branch information
thorwhalen committed Nov 30, 2024
1 parent ae7596a commit ee53c20
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 5 deletions.
10 changes: 6 additions & 4 deletions lkj/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,12 @@
from lkj.filesys import get_app_data_dir, get_watermarked_dir, enable_sourcing_from_file
from lkj.strings import (
regex_based_substitution,
truncate_string_with_marker,
unique_affixes,
camel_to_snake,
snake_to_camel,
truncate_string_with_marker, # Truncate a string to a maximum length, inserting a marker in the middle.
unique_affixes, # Get unique prefixes or suffixes of a list of strings
camel_to_snake, # Convert CamelCase to snake_case
snake_to_camel, # Convert snake_case to CamelCase
fields_of_string_format, # Extract field names from a string format
fields_of_string_formats, # Extract field names from an iterable of string formats
)
from lkj.loggers import (
print_with_timestamp,
Expand Down
36 changes: 35 additions & 1 deletion lkj/strings.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,39 @@
"""Utils for strings"""

from string import Formatter

formatter = Formatter()


def fields_of_string_format(template):
return [
field_name for _, field_name, _, _ in formatter.parse(template) if field_name
]


def fields_of_string_formats(templates, *, aggregator=set):
"""
Extract all unique field names from the templates in _github_url_templates using string.Formatter.
Args:
templates (list): A list of dictionaries containing 'template' keys.
Returns:
list: A sorted list of unique field names found in the templates.
Example:
>>> templates = ['{this}/and/{that}', 'and/{that}/is/an/{other}']
>>> fields = sorted(extract_template_fields_with_formatter(templates))
['that', 'this', 'other']
"""

def field_names():
for template in templates:
yield from extract_fields_from_string_format(template)

return aggregator(field_names())


import re

# Compiled regex to handle camel case to snake case conversions, including acronyms
Expand Down Expand Up @@ -57,7 +91,7 @@ def truncate_string_with_marker(
s, *, left_limit=15, right_limit=15, middle_marker='...'
):
"""
Return a string with a limited length.
Truncate a string to a maximum length, inserting a marker in the middle.
If the string is longer than the sum of the left_limit and right_limit,
the string is truncated and the middle_marker is inserted in the middle.
Expand Down

0 comments on commit ee53c20

Please sign in to comment.