From 59839c3528fe64790785325065092d0e01b0989a Mon Sep 17 00:00:00 2001
From: Anton Sarukhanov <code@ant.sr>
Date: Tue, 10 Dec 2019 20:31:56 -0500
Subject: [PATCH] Hide redundant formats by default.

---
 whatformat/util/whatdateformat.py | 33 ++++++++++++++++++++++++-------
 1 file changed, 26 insertions(+), 7 deletions(-)

diff --git a/whatformat/util/whatdateformat.py b/whatformat/util/whatdateformat.py
index 41859f3..0fc5eb3 100644
--- a/whatformat/util/whatdateformat.py
+++ b/whatformat/util/whatdateformat.py
@@ -39,23 +39,42 @@ def get_all_format_strings(date_string, allow_reuse=False,
                 possible_parts.append([delimiter])
 
         possible_combinations = list(product(*possible_parts))
-        for parts_sequence in possible_combinations:
-            if any([bool('%-' in x) for x in parts_sequence]) and not no_zero:
-                if str(parts_sequence).replace('%-', '%') in \
-                        [str(c) for c in possible_combinations]:
-                    continue
+        if not no_zero:
+            possible_combinations = _remove_extra_nlz(  # type: ignore
+                possible_combinations)
+        for sequence in possible_combinations:
             if not allow_reuse:
-                counts = Counter(parts_sequence)
+                counts = Counter(sequence)
                 max_count = max(
                     counts[diretive] for diretive in FORMAT_DIRECTIVES)
                 if max_count > 1:
                     continue
-            format_string = "".join(parts_sequence)
+            format_string = "".join(sequence)
             if parsed_datetime.strftime(
                     format_string).lower() == date_string.lower():
                 yield format_string
 
 
+def _remove_extra_nlz(combinations) -> Iterator[List[str]]:
+    """Remove unnecessary non-leading-zero variants.
+
+    Remove non-leading-zero directives (e.g. "%-I") if the corresponding
+    leading-zero directive (e.g. "%I") is also a match.
+    """
+    for variant in combinations:
+        is_duplicate = False
+        for i, token in enumerate(variant):
+            if '-' in token:
+                with_zero = (variant[:i] +
+                             (token.replace('-', ''),) +
+                             variant[(i + 1):])
+                if with_zero in combinations:
+                    is_duplicate = True
+                    break
+        if not is_duplicate:
+            yield variant
+
+
 def get_unique_format_strings(date_string, allow_reuse=False) -> List[str]:
     """Return date format strings matching date_string, without duplicates."""
     return list(set(get_all_format_strings(date_string, allow_reuse)))
-- 
GitLab