|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.IO; |
| 4 | +using System.Text; |
| 5 | + |
| 6 | +namespace Utils.Files |
| 7 | +{ |
| 8 | + public class LineClones : IUtil |
| 9 | + { |
| 10 | + public string Name => "lclones"; |
| 11 | + public string Info => "Removes line clones in a text file." + |
| 12 | + "If -paths parses each line as a path and removes duplicate filenames. " + Environment.NewLine + |
| 13 | + "Args: not interactive (-ni), source text file (-src), output text file (-dst), clones file (-clones), lines are paths (-paths)"; |
| 14 | + |
| 15 | + public int Run(RunArgs ra) |
| 16 | + { |
| 17 | + bool interactive = !ra.InArgs.ContainsKey("-ni"); |
| 18 | + var allText = string.Empty; |
| 19 | + var src = string.Empty; |
| 20 | + var dst = string.Empty; |
| 21 | + var clones = string.Empty; |
| 22 | + var linesArePaths = false; |
| 23 | + |
| 24 | + if (interactive) |
| 25 | + { |
| 26 | + Utils.ReadString("Source file: ", ref src, true); |
| 27 | + Utils.ReadString("Output file: ", ref dst, true); |
| 28 | + Utils.ReadString("Clones file: ", ref clones, false); |
| 29 | + linesArePaths = Utils.ReadWord("Lines are paths? [default is no] (y/*): ", "y"); |
| 30 | + } |
| 31 | + else |
| 32 | + { |
| 33 | + if (ra.InArgs.ContainsKey("-src")) src = ra.InArgs.GetFirstValue("-src"); |
| 34 | + else throw new ArgumentNullException("-src"); |
| 35 | + if (ra.InArgs.ContainsKey("-dst")) dst = ra.InArgs.GetFirstValue("-dst"); |
| 36 | + else throw new ArgumentNullException("-dst"); |
| 37 | + if (ra.InArgs.ContainsKey("-paths")) linesArePaths = true; |
| 38 | + if (ra.InArgs.ContainsKey("-clones")) clones = ra.InArgs.GetFirstValue("-clones"); |
| 39 | + } |
| 40 | + |
| 41 | + allText = File.ReadAllText(src); |
| 42 | + var allLines = allText.Split(Environment.NewLine); |
| 43 | + var linesMap = new Dictionary<string, string>(); |
| 44 | + var clonesList = new List<string>(); |
| 45 | + |
| 46 | + for (var i = 0; i < allLines.Length; i++) |
| 47 | + { |
| 48 | + var line = allLines[i]; |
| 49 | + |
| 50 | + if (linesArePaths) line = Path.GetFileName(line); |
| 51 | + if (!linesMap.ContainsKey(line)) linesMap.Add(line, allLines[i]); |
| 52 | + else clonesList.Add(allLines[i]); |
| 53 | + } |
| 54 | + |
| 55 | + var sb = new StringBuilder(); |
| 56 | + |
| 57 | + foreach (var line in linesMap.Values) |
| 58 | + sb.AppendLine(line); |
| 59 | + |
| 60 | + File.WriteAllText(dst, sb.ToString()); |
| 61 | + |
| 62 | + if (!string.IsNullOrWhiteSpace(clones)) |
| 63 | + { |
| 64 | + clonesList.Sort(); |
| 65 | + |
| 66 | + sb.Clear(); |
| 67 | + foreach (var line in clonesList) |
| 68 | + sb.AppendLine(line); |
| 69 | + |
| 70 | + File.WriteAllText(clones, sb.ToString()); |
| 71 | + } |
| 72 | + |
| 73 | + "Done.".PrintLine(); |
| 74 | + $"{clonesList.Count} clones found".PrintLine(); |
| 75 | + |
| 76 | + return 0; |
| 77 | + } |
| 78 | + } |
| 79 | +} |
0 commit comments