|
| 1 | +using System; |
| 2 | +using System.IO; |
| 3 | +using System.Linq; |
| 4 | + |
| 5 | +using SearchEngine; |
| 6 | +using SearchEngine.UI; |
| 7 | +using SearchEngine.Core.Model; |
| 8 | + |
| 9 | +class Program |
| 10 | +{ |
| 11 | + static void Main(string[] args) |
| 12 | + { |
| 13 | + var defaultDocs = Path.Combine(AppContext.BaseDirectory, "docs"); |
| 14 | + var docsPath = args.Length > 0 ? args[0] : defaultDocs; |
| 15 | + Directory.CreateDirectory(docsPath); |
| 16 | + |
| 17 | + Console.WriteLine($"[i] Indexing documents from: {Path.GetFullPath(docsPath)}"); |
| 18 | + |
| 19 | + var engine = new SearchEngine.SearchEngine(docsPath); |
| 20 | + var ui = new ConsoleUi(); |
| 21 | + |
| 22 | + Console.WriteLine("\nType your query (or type 'exit' to quit):"); |
| 23 | + |
| 24 | + while (true) |
| 25 | + { |
| 26 | + Console.ForegroundColor = ConsoleColor.Green; |
| 27 | + Console.Write("> "); |
| 28 | + Console.ResetColor(); |
| 29 | + |
| 30 | + var line = Console.ReadLine() ?? ""; |
| 31 | + if (line.Trim().Equals("exit", StringComparison.OrdinalIgnoreCase)) |
| 32 | + break; |
| 33 | + |
| 34 | + var query = ParseQuery(line); |
| 35 | + var results = engine.Search(query).Take(10); |
| 36 | + |
| 37 | + ui.DisplayResults(results); |
| 38 | + Console.WriteLine(); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + static SearchQuery ParseQuery(string line) |
| 43 | + { |
| 44 | + var mustInclude = new System.Collections.Generic.List<string>(); |
| 45 | + var atLeastOne = new System.Collections.Generic.List<string>(); |
| 46 | + var mustExclude = new System.Collections.Generic.List<string>(); |
| 47 | + |
| 48 | + var index = line.IndexOf("get", StringComparison.Ordinal); |
| 49 | + if (index >= 0) line = line.Remove(index, 3); |
| 50 | + |
| 51 | + var matches = System.Text.RegularExpressions.Regex.Matches(line, @"[+-]?\"".*?\""|\S+") |
| 52 | + .Cast<System.Text.RegularExpressions.Match>() |
| 53 | + .Select(m => m.Value); |
| 54 | + |
| 55 | + foreach (var tok in matches) |
| 56 | + { |
| 57 | + if (tok.StartsWith("+")) |
| 58 | + atLeastOne.Add(tok.Substring(1).Trim('\"')); |
| 59 | + else if (tok.StartsWith("-")) |
| 60 | + mustExclude.Add(tok.Substring(1).Trim('\"')); |
| 61 | + else |
| 62 | + mustInclude.Add(tok.Trim('\"')); |
| 63 | + } |
| 64 | + |
| 65 | + return new SearchQuery(mustInclude, atLeastOne, mustExclude); |
| 66 | + } |
| 67 | +} |
0 commit comments