-
Notifications
You must be signed in to change notification settings - Fork 0
/
wingrep.cpp
427 lines (373 loc) · 13.4 KB
/
wingrep.cpp
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
#include <filesystem>
#include <fstream>
#include <iostream>
#include <mutex>
#include <thread>
#include "wingrep.h"
#include <queue>
const string EXTENSION_EXCLUSION_LIST[] = { "zip", "obj", "so", "dll" };
const string EXCLUDE_PATH_CONTAINING[] = { "test" };
//---------------------------------------------------------------------------------------------
// Static variables used by the worker threads
//---------------------------------------------------------------------------------------------
static vector<thread> g_workerThreads;
static queue<string> g_pathsToProcess;
static bool g_searchComplete = false;
static long long g_results = 0;
static mutex g_mtx;
//---------------------------------------------------------------------------------------------
// IsValidExtension
//---------------------------------------------------------------------------------------------
static bool IsValidExtension(const string& filepath)
{
size_t extensionStart = filepath.rfind('.');
if (extensionStart != string::npos)
{
string extension = filepath.substr(extensionStart + 1, filepath.size());
for (const auto& excludedExtension : EXTENSION_EXCLUSION_LIST)
{
if (excludedExtension == extension)
{
return false;
}
}
}
else
{
// No extension found
return false;
}
}
//---------------------------------------------------------------------------------------------
// IsValidFileToSearch
//---------------------------------------------------------------------------------------------
static bool IsValidFileToSearch(const string & filepath)
{
if (!IsValidExtension(filepath))
{
return false;
}
return true;
}
//---------------------------------------------------------------------------------------------
// IsPathInExclusionList
//---------------------------------------------------------------------------------------------
static bool IsPathInExclusionList(const string & filepath)
{
for (const auto& excludePath : EXCLUDE_PATH_CONTAINING)
{
if (filepath.find(excludePath) != string::npos)
{
return true;
}
}
return false;
}
//---------------------------------------------------------------------------------------------
// DisplayConstraintInfo
//---------------------------------------------------------------------------------------------
static void DisplayConstraintInfo()
{
cout << "\n--------------------------------------------------------------------\n";
cout << "Skipping directories containing following word(s):\n";
for (const auto& excludePath : EXCLUDE_PATH_CONTAINING)
{
cout << excludePath << endl;
}
cout << "\nSkipping files with following extension(s):\n";
for (const auto& excludedExtension : EXTENSION_EXCLUSION_LIST)
{
cout << excludedExtension << endl;
}
cout << "--------------------------------------------------------------------\n";
}
//---------------------------------------------------------------------------------------------
// @name : AddPathToProcess
//
// @description : Adds a path to the queue of directory paths that needs to be
// processed by worker threads.
//
// @returns : Nothing
//---------------------------------------------------------------------------------------------
static void AddPathToProcess(const string& path)
{
g_mtx.lock();
g_pathsToProcess.push(path);
g_mtx.unlock();
}
//---------------------------------------------------------------------------------------------
// @name : GetPathToProcess
//
// @description : Fetches the directory that needs processing from front of the queue.
//
// @returns : Directory path
//---------------------------------------------------------------------------------------------
static string GetPathToProcess()
{
string path;
g_mtx.lock();
if (!g_pathsToProcess.empty())
{
path = g_pathsToProcess.front();
g_pathsToProcess.pop();
}
g_mtx.unlock();
return path;
}
//---------------------------------------------------------------------------------------------
// @name : SearchLine
//
// @description : Looks for the search string in the line. Does the searching on the
// basis of options provided.
//
// @returns : true if match found.
//---------------------------------------------------------------------------------------------
static bool SearchLine(const string& line, const GrepOptions_t& options)
{
bool bFoundMatch = false;
size_t foundIndex = string::npos;
if (options.bCaseInsensitive)
{
std::string tmpSearchString(options.searchString);
std::string tmpLine(line);
std::transform(options.searchString.begin(), options.searchString.end(), tmpSearchString.begin(), ::toupper);
std::transform(line.begin(), line.end(), tmpLine.begin(), ::toupper);
foundIndex = tmpLine.find(tmpSearchString);
}
else
{
foundIndex = line.find(options.searchString);
}
if (foundIndex != string::npos)
{
bFoundMatch = true;
// Match whole word if option is specified
if (options.bMatchWholeWord)
{
if (foundIndex == 0)
{
// Found at the beginning of the line
size_t wordEndIndex = foundIndex + options.searchString.size();
if (line[wordEndIndex] != ' ')
{
bFoundMatch = false;
}
}
else if (foundIndex + options.searchString.size() == line.size())
{
// Found at end of the line
if (line[foundIndex - 1] != ' ')
{
bFoundMatch = false;
}
}
else
{
// Found somewhere in the middle
if (line[foundIndex - 1] != ' ' || line[foundIndex + options.searchString.size()] != ' ')
{
bFoundMatch = false;
}
}
}
}
return bFoundMatch;
}
//---------------------------------------------------------------------------------------------
// @name : DisplaySearchResult
//
// @description : Show search result on console as per specified options.
//
// @returns : Nothing
//---------------------------------------------------------------------------------------------
static void DisplaySearchResult(const string& file, const string& line, int lineNumber, const GrepOptions_t& options)
{
g_mtx.lock();
std::cout << file;
if (options.bShowLineNumbers)
{
cout << ":" << lineNumber;
}
std::cout << " " << line << endl;
g_mtx.unlock();
}
//---------------------------------------------------------------------------------------------
// @name : ProcessFile
//
// @description : Searches the provided file for the search_string as per the options
// specified. If found, displays the information on console.
//
// @returns : Count of matches found in the file.
//---------------------------------------------------------------------------------------------
static long long ProcessFile(const string& file, const GrepOptions_t& options)
{
long long results = 0;
if (!IsValidFileToSearch(file))
{
return results;
}
string line;
long lineNumber = 1;
ifstream infile(file.c_str());
while (getline(infile, line))
{
if (!line.empty())
{
bool bFoundMatch = SearchLine(line, options);
// Match is found, show result on console
if (bFoundMatch)
{
DisplaySearchResult(file, line, lineNumber, options);
results++;
}
}
lineNumber++;
}
return results;
}
//---------------------------------------------------------------------------------------------
// @name : GetFilesToSearch
//
// @description : Retrieves all files present in the specified search path.
//
// @returns : Vector of files that are required to be parsed
//---------------------------------------------------------------------------------------------
static void ProcessFiles(const string& searchPath, const GrepOptions_t& options)
{
if (filesystem::exists(searchPath) /*&& !IsPathInExclusionList(searchPath)*/)
{
for (const auto& entry : filesystem::directory_iterator(searchPath))
{
if (filesystem::is_directory(entry) && options.bRecursiveSearch)
{
//g_mtx.lock();
//cout << "Looking in " << entry.path().string() << "\n";
//g_mtx.unlock();
AddPathToProcess(entry.path().string());
}
else
{
string file = entry.path().string();
g_results += ProcessFile(file, options);
}
}
}
}
//---------------------------------------------------------------------------------------------
// @name : DirectoryProcessingWorkerThread
//
// @description : Worker thread which runs continuously to process a directory. Once
// all g_searchComplete becomes true, this worker terminates execution.
// g_searchComplete becomes true when there are no more paths to process.
//
// @returns : Nothing
//---------------------------------------------------------------------------------------------
static void DirectoryProcessingWorkerThread(const GrepOptions_t& options)
{
long long directoriesProcessed = 0;
//g_mtx.lock();
//cout << "Worker thread " << this_thread::get_id() << " spawned\n";
//g_mtx.unlock();
while (!g_searchComplete)
{
string path = GetPathToProcess();
if (!path.empty())
{
ProcessFiles(path, options);
directoriesProcessed++;
}
}
g_mtx.lock();
//cout << "Worker thread " << this_thread::get_id() << " processed " << directoriesProcessed << " locations\n";
g_mtx.unlock();
}
//---------------------------------------------------------------------------------------------
// @name : MarkSearchComplete
//
// @description : Check if all the directories in the work queue have been processed.
// When done, it marks the search complete.
//
// @returns : Nothing
//---------------------------------------------------------------------------------------------
static void MarkSearchComplete()
{
while (1)
{
// Check if all the locations have been searched
if (g_pathsToProcess.empty())
{
g_mtx.lock();
g_searchComplete = true;
g_mtx.unlock();
break;
}
}
}
//---------------------------------------------------------------------------------------------
// @name : SpawnWorkerThreads
//
// @description : Creates multiple worker threads each of which is responsible for
// processing a directory.
//
// @returns : Nothing
//---------------------------------------------------------------------------------------------
static void SpawnWorkerThreads(const GrepOptions_t& options)
{
unsigned int workerThreadsCount = 0;
unsigned int hardwareConcurrency = thread::hardware_concurrency();
if (options.threadsToUse <= 0 || options.threadsToUse > hardwareConcurrency)
{
workerThreadsCount = hardwareConcurrency;
}
else
{
workerThreadsCount = options.threadsToUse;
}
for (unsigned int i = 0; i < workerThreadsCount; i++)
{
thread workerThread(DirectoryProcessingWorkerThread, options);
g_workerThreads.push_back(move(workerThread));
}
cout << "Spawned " << workerThreadsCount << " worker threads\n";
}
//---------------------------------------------------------------------------------------------
// @name : WaitForWorkerThreadsToComplete
//
// @description : Join all the worker threads
//
// @returns : Nothing
//---------------------------------------------------------------------------------------------
static void WaitForWorkerThreadsToComplete()
{
for (auto& workerThread : g_workerThreads)
{
if (workerThread.joinable())
{
workerThread.join();
}
}
}
//---------------------------------------------------------------------------------------------
// @name : GetSearchResults
//
// @description : This is the core function which processes the search string in the
// provided path as per the options(flags) specified.
//
// @returns : Number of matching search results
//---------------------------------------------------------------------------------------------
long long GetSearchResults(const GrepOptions_t& options)
{
if (filesystem::exists(options.searchPath))
{
SpawnWorkerThreads(options);
ProcessFiles(options.searchPath, options);
MarkSearchComplete();
WaitForWorkerThreadsToComplete();
}
else
{
cout << "Invalid search path : " << options.searchPath << endl;
}
//DisplayConstraintInfo();
return g_results;
}