Debian Codegraph @

crazy_complete/bash_patterns.py

raw
1 # SPDX-License-Identifier: GPL-3.0-or-later
2 # Copyright (C) 2025-2026 Benjamin Abendroth <[email protected]>
3
4 '''Module for creating Bash globs.'''
5
6 from collections import defaultdict
7
8 from .algo import numbers_are_contiguous
9
10
11 class TrieNode:
12 '''Trie class.'''
13
14 # pylint: disable=too-few-public-methods
15
16 def __init__(self):
17 self.children = defaultdict(TrieNode)
18 self.is_terminal = False
19
20 def insert(self, string):
21 '''Insert string into trie.'''
22
23 node = self
24 for char in string:
25 node = node.children[char]
26 node.is_terminal = True
27
28
29 def _build_pattern(parts):
30 if len(parts) == 1:
31 return parts[0]
32
33 try:
34 ints = sorted(map(int, parts))
35 if numbers_are_contiguous(ints):
36 return f'[{ints[0]}-{ints[-1]}]'
37 except ValueError:
38 pass
39
40 return "@(" + "|".join(sorted(parts)) + ")"
41
42
43 def trie_to_pattern(node):
44 '''
45 Recursively convert the trie into a Bash extglob pattern.
46 '''
47 if not node.children:
48 return ""
49
50 parts = []
51 for token, child in node.children.items():
52 sub = trie_to_pattern(child)
53 if sub:
54 parts.append(token + sub)
55 else:
56 parts.append(token)
57
58 # Terminal means that this path can end here
59 if node.is_terminal:
60 parts.append("") # Represent the option to stop early
61
62 return _build_pattern(parts)
63
64
65 def compact_glob_trie(strings):
66 '''
67 Build a recursive glob pattern that matches all input strings.
68 '''
69 strings = sorted(set(strings))
70 if len(strings) == 1:
71 return strings[0]
72
73 # Build Trie
74 root = TrieNode()
75 for string in strings:
76 root.insert(string)
77
78 # Convert Trie to pattern
79 return trie_to_pattern(root)
80
81
82 def make_pattern(strings):
83 '''Make a glob pattern that matches `strings`.'''
84
85 candidate0 = '|'.join(strings)
86 candidate1 = compact_glob_trie(strings)
87
88 return candidate0 if len(candidate0) < len(candidate1) else candidate1