-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsmart_search.py
More file actions
251 lines (219 loc) · 9.73 KB
/
smart_search.py
File metadata and controls
251 lines (219 loc) · 9.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
#!/usr/bin/env python3
"""
Smart Search Script - Python Version
A powerful search tool for finding files and content with various options.
"""
import os
import re
import argparse
import fnmatch
from pathlib import Path
from typing import List, Tuple, Optional
# ANSI color codes
class Colors:
RED = '\033[0;31m'
GREEN = '\033[0;32m'
YELLOW = '\033[1;33m'
BLUE = '\033[0;34m'
PURPLE = '\033[0;35m'
CYAN = '\033[0;36m'
NC = '\033[0m' # No Color
def print_colored(text: str, color: str = Colors.NC) -> None:
"""Print text with color."""
print(f"{color}{text}{Colors.NC}")
def search_filenames(search_term: str, search_path: str, recursive: bool = True,
ignore_case: bool = False, exact_match: bool = False,
file_type: Optional[str] = None) -> List[str]:
"""Search for files by name."""
results = []
path_obj = Path(search_path)
print_colored(f"🔍 Searching for filenames containing: '{search_term}'", Colors.BLUE)
print_colored(f"📁 Search path: {search_path}", Colors.BLUE)
print()
# Build search pattern
if exact_match:
if file_type:
pattern = f"{search_term}.{file_type}"
else:
pattern = search_term
else:
if file_type:
pattern = f"*{search_term}*.{file_type}"
else:
pattern = f"*{search_term}*"
# Search function
def matches_pattern(filename: str) -> bool:
if ignore_case:
return fnmatch.fnmatch(filename.lower(), pattern.lower())
return fnmatch.fnmatch(filename, pattern)
try:
if recursive:
for root, dirs, files in os.walk(search_path):
# Check directories
for dir_name in dirs:
if matches_pattern(dir_name):
full_path = os.path.join(root, dir_name)
results.append(('dir', full_path))
# Check files
for file_name in files:
if matches_pattern(file_name):
full_path = os.path.join(root, file_name)
results.append(('file', full_path))
else:
# Non-recursive search
if path_obj.is_dir():
for item in path_obj.iterdir():
if matches_pattern(item.name):
if item.is_file():
results.append(('file', str(item)))
elif item.is_dir():
results.append(('dir', str(item)))
except PermissionError as e:
print_colored(f"❌ Permission denied: {e}", Colors.RED)
except Exception as e:
print_colored(f"❌ Error during search: {e}", Colors.RED)
# Display results
if results:
print_colored("📄 Found files:", Colors.GREEN)
for item_type, path in results:
if item_type == 'file':
print_colored(f" 📄 {path}", Colors.GREEN)
else:
print_colored(f" 📁 {path}", Colors.BLUE)
print()
else:
print_colored("❌ No files found matching the criteria", Colors.RED)
print()
return [path for _, path in results]
def search_content(search_term: str, search_path: str, recursive: bool = True,
ignore_case: bool = False, exact_match: bool = False,
file_type: Optional[str] = None) -> List[Tuple[str, int, str]]:
"""Search for content within files."""
results = []
path_obj = Path(search_path)
print_colored(f"🔍 Searching for content: '{search_term}'", Colors.BLUE)
print_colored(f"📁 Search path: {search_path}", Colors.BLUE)
print()
# Compile regex pattern
flags = re.IGNORECASE if ignore_case else 0
if exact_match:
pattern = re.compile(r'\b' + re.escape(search_term) + r'\b', flags)
else:
pattern = re.compile(re.escape(search_term), flags)
def should_search_file(file_path: Path) -> bool:
"""Check if file should be searched based on type filter."""
if file_type:
return file_path.suffix.lstrip('.').lower() == file_type.lower()
return True
def search_in_file(file_path: Path) -> List[Tuple[int, str]]:
"""Search for pattern in a single file."""
matches = []
try:
# Try to read as text file
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
for line_num, line in enumerate(f, 1):
if pattern.search(line):
matches.append((line_num, line.strip()))
except (UnicodeDecodeError, PermissionError, IsADirectoryError):
# Skip binary files or files we can't read
pass
except Exception as e:
print_colored(f"❌ Error reading {file_path}: {e}", Colors.RED)
return matches
try:
if recursive:
for root, dirs, files in os.walk(search_path):
for file_name in files:
file_path = Path(root) / file_name
if should_search_file(file_path):
matches = search_in_file(file_path)
for line_num, line in matches:
results.append((str(file_path), line_num, line))
else:
# Non-recursive search
if path_obj.is_dir():
for item in path_obj.iterdir():
if item.is_file() and should_search_file(item):
matches = search_in_file(item)
for line_num, line in matches:
results.append((str(item), line_num, line))
elif path_obj.is_file() and should_search_file(path_obj):
matches = search_in_file(path_obj)
for line_num, line in matches:
results.append((str(path_obj), line_num, line))
except Exception as e:
print_colored(f"❌ Error during content search: {e}", Colors.RED)
# Display results
if results:
print_colored("📝 Found content matches:", Colors.GREEN)
for file_path, line_num, line in results:
print_colored(f" {file_path}:", Colors.CYAN, end='')
print_colored(f"{line_num}:", Colors.YELLOW, end=' ')
# Highlight the search term in the line
highlighted_line = pattern.sub(f"{Colors.RED}\\g<0>{Colors.NC}", line)
print(highlighted_line)
print()
else:
print_colored("❌ No content matches found", Colors.RED)
print()
return results
def main():
parser = argparse.ArgumentParser(
description="Smart Search Script - Find files and content with various options",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
%(prog)s "config.txt" /home/user # Find files named config.txt
%(prog)s -c "function main" ./src # Find 'function main' in files
%(prog)s -a "test" . # Find both files and content with 'test'
%(prog)s -i -c "TODO" . # Case-insensitive content search
%(prog)s -t py "class" ./project # Search in Python files only
%(prog)s --no-recursive "*.log" /var/log # Non-recursive search for log files
"""
)
parser.add_argument('search_term', help='Term to search for')
parser.add_argument('path', nargs='?', default='.', help='Path to search in (default: current directory)')
parser.add_argument('-c', '--content', action='store_true',
help='Search for text content within files')
parser.add_argument('-a', '--all', action='store_true',
help='Search both filenames and content')
parser.add_argument('--no-recursive', action='store_true',
help='Search only in specified directory (non-recursive)')
parser.add_argument('-i', '--ignore-case', action='store_true',
help='Search case-insensitive')
parser.add_argument('-e', '--exact', action='store_true',
help='Search for exact matches only')
parser.add_argument('-t', '--type', dest='file_type',
help='File type filter (e.g., txt, py, js)')
args = parser.parse_args()
# Validate path
if not os.path.exists(args.path):
print_colored(f"❌ Error: Path '{args.path}' does not exist", Colors.RED)
return 1
# Display configuration
print_colored("🚀 Smart Search Configuration:", Colors.PURPLE)
print_colored(f" Search term: '{args.search_term}'", Colors.YELLOW)
print_colored(f" Search path: {args.path}", Colors.CYAN)
print_colored(f" Recursive: {not args.no_recursive}", Colors.GREEN)
print_colored(f" Ignore case: {args.ignore_case}", Colors.GREEN)
print_colored(f" Exact match: {args.exact}", Colors.GREEN)
if args.file_type:
print_colored(f" File type: {args.file_type}", Colors.GREEN)
print()
# Perform search
recursive = not args.no_recursive
if args.all:
search_filenames(args.search_term, args.path, recursive,
args.ignore_case, args.exact, args.file_type)
search_content(args.search_term, args.path, recursive,
args.ignore_case, args.exact, args.file_type)
elif args.content:
search_content(args.search_term, args.path, recursive,
args.ignore_case, args.exact, args.file_type)
else:
search_filenames(args.search_term, args.path, recursive,
args.ignore_case, args.exact, args.file_type)
print_colored("✅ Search completed!", Colors.GREEN)
return 0
if __name__ == "__main__":
exit(main())