-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
193 lines (159 loc) · 5.96 KB
/
Copy pathProgram.cs
File metadata and controls
193 lines (159 loc) · 5.96 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
using System.Text.RegularExpressions;
namespace Grip;
static class Program
{
static int totalMatches;
static int totalFiles;
static void Main(string[] args)
{
if (args.Length == 0) { PrintHelp(); return; }
var opts = ParseArgs(args);
if (opts == null) return;
var paths = opts.Paths.Count > 0 ? opts.Paths : ["."];
foreach (var path in paths)
{
if (File.Exists(path))
SearchFile(path, opts);
else if (Directory.Exists(path))
SearchDir(path, opts);
else
Err($"path not found: {path}");
}
if (opts.Stats)
Console.Error.WriteLine($"\n{totalMatches} match{(totalMatches == 1 ? "" : "es")} across {totalFiles} file{(totalFiles == 1 ? "" : "s")}");
}
static void SearchDir(string dir, Options opts)
{
var enumerator = new EnumerationOptions
{
RecurseSubdirectories = opts.Recursive,
IgnoreInaccessible = true,
};
var pattern = opts.Glob ?? "*";
IEnumerable<string> files;
try { files = Directory.EnumerateFiles(dir, pattern, enumerator); }
catch (Exception ex) { Err($"cannot read directory: {ex.Message}"); return; }
foreach (var f in files)
SearchFile(f, opts);
}
static void SearchFile(string path, Options opts)
{
string[] lines;
try { lines = File.ReadAllLines(path); }
catch { return; } // binary files, permission errors — skip silently
var fileMatches = new List<(int lineNum, string line, MatchCollection matches)>();
for (int i = 0; i < lines.Length; i++)
{
MatchCollection mc;
try { mc = opts.Pattern.Matches(lines[i]); }
catch { continue; }
if (mc.Count > 0)
fileMatches.Add((i + 1, lines[i], mc));
}
if (fileMatches.Count == 0) return;
totalFiles++;
totalMatches += fileMatches.Count;
if (opts.FilesOnly)
{
Console.WriteLine(Dim(path));
return;
}
// file header
Console.WriteLine($"\n{Cyan(path)}");
foreach (var (lineNum, line, mc) in fileMatches)
{
if (opts.CountOnly) continue;
string prefix = Dim($"{lineNum,5} │ ");
string highlighted = HighlightMatches(line, mc, opts.IgnoreCase);
Console.WriteLine(prefix + highlighted);
}
if (opts.CountOnly)
Console.WriteLine($" {fileMatches.Count} match{(fileMatches.Count == 1 ? "" : "es")}");
}
static string HighlightMatches(string line, MatchCollection mc, bool ignoreCase)
{
// rebuild line with match spans highlighted yellow
var sb = new System.Text.StringBuilder();
int pos = 0;
foreach (Match m in mc)
{
if (m.Index > pos) sb.Append(line[pos..m.Index]);
sb.Append($"\x1b[1;33m{line[m.Index..(m.Index + m.Length)]}\x1b[0m");
pos = m.Index + m.Length;
}
if (pos < line.Length) sb.Append(line[pos..]);
return sb.ToString();
}
record Options(
Regex Pattern,
List<string> Paths,
string? Glob,
bool Recursive,
bool IgnoreCase,
bool FilesOnly,
bool CountOnly,
bool Stats
);
static Options? ParseArgs(string[] args)
{
string? rawPattern = null;
var paths = new List<string>();
string? glob = null;
bool recursive = true;
bool ignoreCase = false;
bool filesOnly = false;
bool countOnly = false;
bool stats = true;
for (int i = 0; i < args.Length; i++)
{
switch (args[i])
{
case "-i" or "--ignore-case": ignoreCase = true; break;
case "-l" or "--files": filesOnly = true; break;
case "-c" or "--count": countOnly = true; break;
case "--no-stats": stats = false; break;
case "-r" or "--recursive": recursive = true; break;
case "--no-recursive": recursive = false; break;
case "-g" or "--glob":
if (++i >= args.Length) { Err("--glob requires a value"); return null; }
glob = args[i];
break;
default:
if (args[i].StartsWith('-')) { Err($"unknown flag: {args[i]}"); return null; }
if (rawPattern == null) rawPattern = args[i];
else paths.Add(args[i]);
break;
}
}
if (rawPattern == null) { Err("pattern required"); PrintHelp(); return null; }
Regex pattern;
try
{
var flags = RegexOptions.Compiled | (ignoreCase ? RegexOptions.IgnoreCase : 0);
pattern = new Regex(rawPattern, flags);
}
catch (RegexParseException ex) { Err($"invalid pattern: {ex.Message}"); return null; }
return new Options(pattern, paths, glob, recursive, ignoreCase, filesOnly, countOnly, stats);
}
static string Cyan(string s) => $"\x1b[36m{s}\x1b[0m";
static string Dim(string s) => $"\x1b[2m{s}\x1b[0m";
static void Err(string msg) => Console.Error.WriteLine($"\x1b[31merror:\x1b[0m {msg}");
static void PrintHelp() => Console.WriteLine("""
grip — fast file content search
usage:
grip <pattern> [path...] [flags]
flags:
-i, --ignore-case case insensitive
-l, --files only print matching filenames
-c, --count only print match count per file
-r, --recursive recurse into directories (default: on)
--no-recursive don't recurse
-g, --glob <pattern> filter files by glob (e.g. *.cs)
--no-stats suppress match count summary
examples:
grip "TODO" . --glob *.cs
grip -i "error" logs/
grip -l "password" src/
grip "func\s+\w+" --glob *.go
""");
}