Coverage for fguess.py: 100%
278 statements
« prev ^ index » next coverage.py v7.10.4, created at 2025-08-22 16:14 -0700
« prev ^ index » next coverage.py v7.10.4, created at 2025-08-22 16:14 -0700
1#!/usr/bin/env python3
2"""
3f-string format specification finder - reverse engineer format specs from output examples
4Now includes datetime format detection!
5"""
6import re
7import sys
8from dataclasses import dataclass
9from datetime import datetime
10from typing import Optional
12import strptime
14__version__ = "0.0.1"
17HEX_RE = re.compile(r'0[xX][0-9a-fA-F]+')
18UNPREFIXED_HEX_RE = re.compile(r'[0-9]*[a-fA-F]+[0-9]*')
19PERCENT_RE = re.compile(r'[+-]?\d+\.?\d*%')
20ZERO_PADDED_RE = re.compile(r'0+\d+\.?\d*')
21THOUSANDS_RE = re.compile(r'[+-]?\d{1,3}(?:,\d{3})+(?:\.\d+)?')
22UNDERSCORE_RE = re.compile(r'[+-]?\d{1,3}(?:_\d{3})+(?:\.\d+)?')
23NUMBER_RE = re.compile(r'[+-]?\d+\.?\d*')
25FULL_HEX_RE = re.compile(rf'(.*?)({HEX_RE.pattern})(.*)')
26FULL_UNPREFIXED_HEX_RE = re.compile(rf'()({UNPREFIXED_HEX_RE.pattern})()')
27FULL_PERCENT_RE = re.compile(rf'(.*?)({PERCENT_RE.pattern})(.*)')
28FULL_THOUSANDS_RE = re.compile(rf'(.*?)({THOUSANDS_RE.pattern})(.*)')
29FULL_UNDERSCORE_RE = re.compile(rf'(.*?)({UNDERSCORE_RE.pattern})(.*)')
30FULL_NUMBER_RE = re.compile(rf'(.*?)({NUMBER_RE.pattern})(.*)')
31PAD_CHARS = ' _*'
35@dataclass
36class NumberParts:
37 prefix: str
38 num: str
39 suffix: str
41 def __iter__(self):
42 return iter((self.prefix, self.num, self.suffix))
45@dataclass
46class FormatSpec:
47 """Represents the components needed to build a format specification."""
48 align: str = ''
49 fill: str = ''
50 width: int = 0
51 comma: bool = False
52 underscore: bool = False
53 decimals: Optional[int] = None
54 type_char: str = ''
55 sign: str = ''
56 prefix: str = ''
57 suffix: str = ''
59 # Metadata for generating variations
60 value_type: str = 'str' # 'int', 'float', 'str', or 'datetime'
61 test_value: float = 0
62 datetime_format: str = '' # For datetime types, stores the strptime format
64 def build(self):
65 """Build the format specification string."""
66 if self.value_type == 'datetime':
67 return f'f"{self.prefix}{{variable:{self.datetime_format}}}{self.suffix}"'
68 else:
69 return build_format_spec(
70 align=self.align,
71 fill=self.fill,
72 width=self.width,
73 comma=self.comma,
74 underscore=self.underscore,
75 decimals=self.decimals,
76 type_char=self.type_char,
77 sign=self.sign,
78 prefix=self.prefix,
79 suffix=self.suffix
80 )
82 def as_tuple(self):
83 """Return (value_type, format_spec) tuple for compatibility."""
84 return (self.value_type, self.build())
87def build_format_spec(
88 align='',
89 fill='',
90 width=0,
91 comma=False,
92 underscore=False,
93 decimals=None,
94 type_char='',
95 sign='',
96 prefix='',
97 suffix='',
98):
99 """Build a format specification string."""
100 fill = fill if fill != ' ' else ''
101 width_str = str(width) if width else ''
102 comma_str = ',' if comma else ''
103 underscore_str = '_' if underscore else ''
104 decimals_str = f'.{decimals}' if decimals is not None else ''
106 # Choose separator (underscore takes precedence over comma if both somehow set)
107 separator_str = underscore_str or comma_str
109 # Special case: integer with separator but no width should omit 'd'
110 if type_char == 'd' and (comma or underscore) and not width:
111 type_char = ''
113 if align:
114 spec = f'{fill}{align}{sign}{width_str}{separator_str}{decimals_str}{type_char}'
115 else:
116 spec = f'{sign}{fill}{width_str}{separator_str}{decimals_str}{type_char}'
118 if spec:
119 return f'f"{prefix}{{variable:{spec}}}{suffix}"'
120 else:
121 return f'f"{prefix}{{variable}}{suffix}"'
124def is_padding(text):
125 """Check if text represents padding characters."""
126 return len(set(text)) == 1 and text[0] in PAD_CHARS
129def count_decimals(number_string):
130 """Return number of decimals in given numeric string."""
131 return len(number_string.split('.')[1]) if '.' in number_string else 0
134def split_numeric_literals(s):
135 """Split a string into prefix literals, numeric part, and suffix literals."""
136 # Check for hex with 0x prefix first
137 if match := FULL_HEX_RE.fullmatch(s):
138 return NumberParts(*match.groups())
140 # Check for percentage
141 if match := FULL_PERCENT_RE.fullmatch(s):
142 prefix, num, suffix = match.groups()
143 # Check if prefix/suffix look like padding
144 left_pad = is_padding(prefix)
145 right_pad = is_padding(suffix)
146 if (
147 (left_pad or right_pad)
148 and (left_pad != right_pad or prefix[0] == suffix[0])
149 ):
150 return NumberParts('', s, '')
152 return NumberParts(prefix, num, suffix)
154 # Check for unprefixed hex (must contain a-f or A-F)
155 if match := FULL_UNPREFIXED_HEX_RE.fullmatch(s):
156 prefix, num, suffix = match.groups()
157 # Always treat as unprefixed hex since the pattern doesn't capture padding
158 return NumberParts(prefix, num, suffix)
160 # Check for numbers with separators (thousands or underscore) and regular numbers
161 for regex in [FULL_THOUSANDS_RE, FULL_UNDERSCORE_RE, FULL_NUMBER_RE]:
162 if match := regex.fullmatch(s):
163 prefix, num, suffix = match.groups()
164 left_pad = is_padding(prefix)
165 right_pad = is_padding(suffix)
166 if (
167 (left_pad or right_pad)
168 and (left_pad != right_pad or prefix[0] == suffix[0])
169 ):
170 return NumberParts('', s, '')
172 return NumberParts(prefix, num, suffix)
174 return NumberParts('', s, '')
177def detect_padding(s, pad_chars=PAD_CHARS):
178 """Detect consistent padding in a string."""
179 for char in pad_chars:
180 left = len(s) - len(s.lstrip(char))
181 right = len(s.rstrip(char))
182 left_pad, core, right_pad = s[:left], s[left:right], s[right:]
183 if (left_pad or right_pad) and core:
184 return core, left_pad, right_pad, char
186 return s, '', '', ' '
189# Datetime detection functions (from strptime.py)
190def detect_datetime_format(text):
191 """Detect datetime format from text string."""
192 try:
193 return strptime.detect_format(text)
194 except ValueError:
195 return None
198def is_single_numeric_datetime_format(datetime_format):
199 """Check if datetime format is just a single numeric component like %d or %Y."""
200 single_numeric_formats = {"%d", "%m", "%y", "%Y", "%H", "%I", "%M", "%S", "%j"}
201 return datetime_format in single_numeric_formats
204def has_datetime_structure(s):
205 """Check if string has structure that suggests datetime (spaces, dashes, colons, etc)."""
206 # Look for separators that commonly appear in datetime strings
207 datetime_separators = {' ', '-', '/', ':', 'T', '+'}
208 return any(sep in s for sep in datetime_separators)
211def parse_number_to_spec(s, prefix='', suffix='', align='', fill='', width=0):
212 """Parse a string as a number and return FormatSpec objects."""
214 # Hex format with 0x prefix
215 if HEX_RE.fullmatch(s):
216 value = int(s.removeprefix('0x'), 16)
217 is_padded = s.startswith('0x0')
218 return [FormatSpec(
219 fill="0" if is_padded else "",
220 width=len(s) if is_padded else 0,
221 type_char='x',
222 sign='#',
223 prefix=prefix,
224 suffix=suffix,
225 value_type='int',
226 test_value=value
227 )]
229 # Unprefixed hex format (contains a-f or A-F)
230 if UNPREFIXED_HEX_RE.fullmatch(s):
231 value = int(s, 16)
233 # Choose format based on what's present (uppercase takes precedence if both)
234 hex_char = 'X' if s.isupper() else 'x'
236 # Check for zero padding
237 is_padded = len(s) > 1 and s[0] == '0'
239 return [FormatSpec(
240 fill="0" if is_padded else "",
241 width=len(s) if is_padded else 0,
242 type_char=hex_char,
243 prefix=prefix,
244 suffix=suffix,
245 value_type='int',
246 test_value=value
247 )]
249 # Percentage
250 if PERCENT_RE.fullmatch(s):
251 num = s.removesuffix('%')
252 value = float(num) / 100
253 decimals = count_decimals(num)
254 has_sign = num.startswith('+') # Only + triggers sign format, not -
255 return [FormatSpec(
256 align=align,
257 fill=fill,
258 width=width,
259 sign='+' if has_sign else '',
260 decimals=decimals,
261 type_char='%',
262 prefix=prefix,
263 suffix=suffix,
264 value_type='float',
265 test_value=value
266 )]
268 if ZERO_PADDED_RE.fullmatch(s.removeprefix('+')):
269 # Zero-padded number (possibly with sign)
270 width_val = len(s) # Include the sign in the width
271 decimals = count_decimals(s)
272 has_sign = s.startswith('+')
273 value = float(s) if decimals else int(s)
275 results = []
276 if not decimals:
277 spec = FormatSpec(
278 fill="0",
279 width=width_val,
280 type_char='d',
281 sign='+' if has_sign else '',
282 prefix=prefix,
283 suffix=suffix,
284 value_type='int',
285 test_value=abs(value)
286 )
287 results.append(spec)
289 spec = FormatSpec(
290 fill="0",
291 width=width_val,
292 decimals=decimals,
293 type_char='f',
294 sign='+' if has_sign else '',
295 prefix=prefix,
296 suffix=suffix,
297 value_type='float',
298 test_value=abs(float(value))
299 )
300 results.append(spec)
301 return results
303 # Regular number (check for separators)
304 clean = s.replace(',', '').replace('_', '')
305 if NUMBER_RE.fullmatch(clean):
306 has_comma = THOUSANDS_RE.fullmatch(s)
307 has_underscore = UNDERSCORE_RE.fullmatch(s)
308 decimals = count_decimals(clean)
309 has_sign = s.startswith('+')
310 sign = '+' if has_sign else ''
312 # Handle trailing decimal point with no digits after it
313 has_trailing_decimal = '.' in clean and decimals == 0
314 if has_trailing_decimal:
315 # Strip trailing decimal point for integer conversion
316 clean_for_int = clean.rstrip('.')
317 value = int(clean_for_int) if clean_for_int else 0
318 float_value = float(clean)
319 else:
320 value = float(clean) if decimals else int(clean)
321 float_value = float(clean)
323 results = []
324 if not decimals and (align or has_comma or has_underscore or sign or fill.strip()):
325 # Integer format
326 spec = FormatSpec(
327 align=align,
328 fill=fill,
329 width=width,
330 comma=has_comma,
331 underscore=has_underscore,
332 type_char='d',
333 sign=sign,
334 prefix=prefix,
335 suffix=suffix,
336 value_type='int',
337 test_value=abs(int(value))
338 )
339 results.append(spec)
341 # Float format - but skip if it's a trailing decimal point case
342 # because f"{5:.0f}" produces "5" not "5."
343 if not has_trailing_decimal:
344 spec = FormatSpec(
345 align=align,
346 fill=fill,
347 width=width,
348 comma=has_comma,
349 underscore=has_underscore,
350 decimals=decimals,
351 type_char='f',
352 sign=sign,
353 prefix=prefix,
354 suffix=suffix,
355 value_type='float',
356 test_value=abs(float_value)
357 )
358 if not decimals and (has_comma or has_underscore):
359 results.insert(0, spec)
360 else:
361 results.append(spec)
362 return results
364 return []
367def split_datetime_literals(s):
368 """Try to find datetime parts within a string with literals."""
369 # Try to find potential datetime substrings
370 # Look for patterns that commonly appear in datetimes
371 datetime_patterns = [
372 # ISO-like dates
373 re.compile(r'(.*?)(\d{4}-\d{2}-\d{2}(?:\s+\d{1,2}:\d{2}(?::\d{2})?)?(?:\s*[AP]M)?)(.*)', re.IGNORECASE),
374 # US dates
375 re.compile(r'(.*?)(\d{1,2}/\d{1,2}/\d{2,4}(?:\s+\d{1,2}:\d{2}(?::\d{2})?\s*[AP]M?)?)(.*)', re.IGNORECASE),
376 # Times
377 re.compile(r'(.*?)(\d{1,2}:\d{2}(?::\d{2})?(?:\s*[AP]M)?)(.*)', re.IGNORECASE),
378 # Month names with dates/years
379 re.compile(r'(.*?)(\b(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\s+\d{1,2}(?:,?\s+\d{4})?(?:\s+\d{1,2}:\d{2}(?::\d{2})?)?(?:\s*[AP]M)?)(.*)', re.IGNORECASE),
380 # Weekday names with dates
381 re.compile(r'(.*?)(\b(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*\s+(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\s+\d{1,2}(?:\s+\d{4})?(?:\s+\d{1,2}:\d{2}(?::\d{2})?)?(?:\s*[AP]M)?)(.*)', re.IGNORECASE),
382 # Just month or weekday names
383 re.compile(r'(.*?)(\b(?:January|February|March|April|May|June|July|August|September|October|November|December|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday|Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec|Mon|Tue|Wed|Thu|Fri|Sat|Sun)\b)(.*)', re.IGNORECASE),
384 ]
386 for pattern in datetime_patterns:
387 match = pattern.fullmatch(s)
388 if match:
389 prefix, datetime_part, suffix = match.groups()
390 # Try to detect datetime format on the extracted part
391 datetime_format = detect_datetime_format(datetime_part.strip())
392 return prefix, datetime_part.strip(), suffix, datetime_format
394 return None, s, None, None
397def analyze_number_format(s):
398 """Analyze a string and return possible format specifications."""
399 results = []
401 # Try datetime detection on full string first
402 datetime_format = detect_datetime_format(s)
403 datetime_prefix = ''
404 datetime_suffix = ''
405 datetime_part = s
407 # If full string detection failed, try to find datetime parts within literals
408 if not datetime_format:
409 prefix, datetime_part, suffix, datetime_format = split_datetime_literals(s)
410 if datetime_format:
411 datetime_prefix = prefix or ''
412 datetime_suffix = suffix or ''
414 if datetime_format:
415 # Determine test value for datetime
416 test_dt = datetime.strptime(datetime_part, datetime_format)
418 spec = FormatSpec(
419 value_type='datetime',
420 datetime_format=datetime_format,
421 prefix=datetime_prefix,
422 suffix=datetime_suffix,
423 test_value=0, # Not used for datetime
424 )
426 # Check if this is a single numeric component
427 is_single_numeric = is_single_numeric_datetime_format(datetime_format)
429 if is_single_numeric:
430 # Single numeric datetime formats get lower priority
431 datetime_results = [spec.as_tuple()]
432 else:
433 # Multi-part datetime formats get higher priority
434 datetime_results = [spec.as_tuple()]
435 else:
436 datetime_results = []
437 is_single_numeric = False
439 # Continue with existing numeric format detection
440 # First, split into literals and numeric part
441 prefix, number_part, suffix = split_numeric_literals(s)
443 # Handle cases with literals
444 if prefix or suffix:
445 numeric_results = parse_number_to_spec(number_part, prefix, suffix)
447 # Always add string version
448 spec = FormatSpec(
449 prefix=prefix,
450 suffix=suffix,
451 value_type='str',
452 test_value=0
453 )
454 numeric_results.append(spec)
455 numeric_results = [spec.as_tuple() for spec in numeric_results]
456 else:
457 # No literals found, check for padding
458 core, left_pad, right_pad, fill_char = detect_padding(s)
460 # Determine alignment and width
461 if left_pad and right_pad:
462 if len(left_pad) == len(right_pad):
463 align = '^' # True center alignment - equal padding on both sides
464 else:
465 # Unequal padding - treat as literals, not alignment
466 spec = FormatSpec(
467 prefix=left_pad,
468 suffix=right_pad,
469 value_type='str'
470 )
471 return [spec.as_tuple()]
472 elif left_pad:
473 align = '>'
474 elif right_pad:
475 align = '<'
476 else:
477 align = ''
479 width = len(s) if (left_pad or right_pad) else 0
481 # Parse the core number
482 if left_pad or right_pad:
483 numeric_results = parse_number_to_spec(core, align=align, fill=fill_char, width=width)
485 # Add string format (always add when we have padding)
486 spec = FormatSpec(
487 align=align,
488 fill=fill_char,
489 width=width,
490 value_type='str'
491 )
492 numeric_results.append(spec)
493 else:
494 numeric_results = parse_number_to_spec(core, align=align, fill=fill_char, width=width)
496 numeric_results = [spec.as_tuple() for spec in numeric_results]
498 # Now combine results with proper priority ordering
499 # Priority rules:
500 # 1. Multi-part datetime formats (highest priority when datetime structure detected)
501 # 2. Numeric formats (int/float)
502 # 3. String formats
503 # 4. Single numeric datetime formats (lowest priority)
505 if datetime_results and not is_single_numeric:
506 # Multi-part datetime: prioritize datetime if string has datetime structure
507 if has_datetime_structure(s):
508 results.extend(datetime_results)
509 results.extend(numeric_results)
510 else:
511 # No clear datetime structure, prioritize numeric
512 results.extend(numeric_results)
513 results.extend(datetime_results)
514 elif datetime_results and is_single_numeric:
515 # Single numeric datetime: lowest priority
516 results.extend(numeric_results)
517 results.extend(datetime_results)
518 else:
519 # No datetime formats found, just use numeric results
520 results.extend(numeric_results)
522 return results
525def get_test_value(input_str, type_name):
526 """Determine appropriate test value for validation."""
527 if type_name == 'datetime':
528 # Try to parse the original datetime
529 datetime_format = detect_datetime_format(input_str)
530 if datetime_format:
531 return datetime.strptime(input_str, datetime_format)
533 # If full string parsing failed, try to extract datetime part from literals
534 prefix, datetime_part, suffix, datetime_format = split_datetime_literals(input_str)
535 if datetime_format:
536 return datetime.strptime(datetime_part, datetime_format)
538 # Return default datetime if parsing fails
539 return datetime(2030, 1, 24, 5, 45, 13)
541 # Extract just the numeric part for non-datetime types
542 prefix, number_part, suffix = split_numeric_literals(input_str)
543 if prefix or suffix:
544 input_str = number_part
546 # If still no numeric part, check for padding
547 core, _, _, _ = detect_padding(input_str)
548 if core != input_str:
549 input_str = core
551 if type_name == 'str':
552 return input_str
554 elif type_name == 'int':
555 # Parse as integer
556 clean = input_str.replace(',', '').replace('_', '').removeprefix('+')
557 if clean and clean.removeprefix('-').isdigit():
558 return int(clean)
559 # Try for hex with 0x prefix
560 if HEX_RE.fullmatch(input_str):
561 return int(input_str.removeprefix('0x'), 16)
562 # Try for unprefixed hex
563 if UNPREFIXED_HEX_RE.fullmatch(input_str):
564 return int(input_str, 16)
565 return 0
567 else: # float
568 # Parse as float
569 clean = input_str.replace(',', '').replace('_', '').removeprefix('+')
570 if PERCENT_RE.fullmatch(input_str):
571 return float(clean.removesuffix('%')) / 100
573 if clean and NUMBER_RE.fullmatch(clean):
574 return float(clean)
575 return 0.0
578def main():
579 """Main entry point for the CLI tool."""
580 if len(sys.argv) > 1:
581 input_str = sys.argv[1]
582 else:
583 print("Enter a formatted string (or 'quit' to exit):")
584 input_str = input()
585 if input_str.lower() == 'quit':
586 return
588 print(f"\nInput: '{input_str}'")
589 print("-" * 40)
591 results = analyze_number_format(input_str)
593 if not results:
594 print("No format specifications found")
595 return
597 # Display unique results
598 seen = set()
599 for type_name, format_spec in results:
600 seen.add((type_name, format_spec))
602 # Get test value and validate
603 test_value = get_test_value(input_str, type_name)
605 print(f"{type_name:8} → {format_spec}")
606 print(f" (e.g., variable = {test_value!r})")
607 print()
610if __name__ == "__main__":
611 while True:
612 main()
613 if len(sys.argv) > 1:
614 break
615 print("\n" + "=" * 40)