1 /**
2 Command line tool that identifies equivalent lines in an input stream. Equivalent
3 lines are identified using either the full line or a set of fields as the key. By
4 default, input is written to standard output, retaining only the first occurrence of
5 equivalent lines. There are also options for marking and numbering equivalent lines
6 rather, without filtering out duplicates.
7 
8 This tool is similar in spirit to the Unix 'uniq' tool, with some key differences.
9 First, the key can be composed of individual fields, not just the full line. Second,
10 input does not need to be sorted. (Unix 'uniq' only detects equivalent lines when
11 they are adjacent, hence the usual need for sorting.)
12 
13 There are a couple alternative to uniq'ing the input lines. One is to mark lines with
14 an equivalence ID, which is a one-upped counter. The other is to number lines, with
15 each unique key have its own set of numbers.
16 
17 Copyright (c) 2015-2019, eBay Software Foundation
18 Initially written by Jon Degenhardt
19 
20 License: Boost Licence 1.0 (http://boost.org/LICENSE_1_0.txt)
21 */
22 module tsv_utils.tsv_uniq;
23 
24 import std.stdio;
25 import std.format : format;
26 import std.typecons : tuple;
27 
28 auto helpText = q"EOS
29 Synopsis: tsv-uniq [options] [file...]
30 
31 tsv-uniq filters out duplicate lines using fields as a key. Filtering is
32 based on the entire line when key fields are not provided. Options are
33 also available for assigning a unique id to each key and numbering the
34 occurrences of each key. Use '--help-verbose' for more details.
35 
36 Options:
37 EOS";
38 
39 auto helpTextVerbose = q"EOS
40 Synopsis: tsv-uniq [options] [file...]
41 
42 tsv-uniq identifies equivalent lines in tab-separated value files. Input
43 is read line by line, recording a key for each line based on one or more
44 of the fields. Two lines are equivalent if they have the same key. The
45 first time a key is seen its line is written to standard output.
46 Subsequent lines containing the same key are discarded. This command
47 uniq's a file on fields 2 and 3:
48 
49    tsv-uniq -f 2,3 file.tsv
50 
51 This is similar to the Unix 'uniq' program, but based on individual
52 fields and without requiring sorted data.
53 
54 tsv-uniq can be run without specifying a key field. In this case the
55 whole line is used as a key, same as the Unix 'uniq' program. This works
56 on any line-oriented text file, not just TSV files.
57 
58 The above is the default behavior ('uniq' mode). The alternates to 'uniq'
59 mode are 'number' mode and 'equiv-class' mode. In 'equiv-class' mode, all
60 lines are written to standard output, but with a field appended marking
61 equivalent entries with an ID. The ID is a one-upped counter. Example:
62 
63    tsv-uniq --header -f 2,3 --equiv file.tsv
64 
65 'Number' mode also writes all lines to standard output, but with a field
66 appended numbering the occurrence count for the line's key. The first line
67 with a specific key is assigned the number '1', the second with the key is
68 assigned number '2', etc. 'Number' and 'equiv-class' modes can be combined.
69 
70 The '--r|repeated' option can be used to print only lines occurring more
71 than once. Specifically, the second occurrence of a key is printed. The
72 '--a|at-least N' option is similar, printing lines occurring at least N
73 times. (Like repeated, the Nth line with the key is printed.)
74 
75 The '--m|max MAX' option changes the behavior to output the first MAX
76 lines for each key, rather than just the first line for each key.
77 
78 If both '--a|at-least' and '--m|max' are specified, the occurrences
79 starting with 'at-least' and ending with 'max' are output.
80 
81 Options:
82 EOS";
83 
84 /** Container for command line options.
85  */
86 struct TsvUniqOptions
87 {
88     enum defaultEquivHeader = "equiv_id";
89     enum defaultEquivStartID = 1;
90     enum defaultNumberHeader = "equiv_line";
91 
92     string programName;
93     bool helpVerbose = false;                 // --h|help-verbose
94     bool versionWanted = false;               // --V|version
95     size_t[] fields;                          // --f|fields
96     bool hasHeader = false;                   // --H|header
97     bool onlyRepeated = false;                // --r|repeated. Shorthand for '--atleast 2'
98     size_t atLeast = 0;                       // --a|at-least. Zero implies default behavior.
99     size_t max = 0;                           // --m|max. Zero implies default behavior.
100     bool numberMode = false;                  // --z|number
101     string numberHeader = defaultNumberHeader;  // --number-header
102     bool equivMode = false;                   // --e|equiv
103     string equivHeader = defaultEquivHeader;  // --equiv-header
104     long equivStartID = defaultEquivStartID;  // --equiv-start
105     bool ignoreCase = false;                  // --i|ignore-case
106     char delim = '\t';                        // --d|delimiter
107     bool keyIsFullLine = false;               // Derived. True if no fields specified or '--f|fields 0'
108 
109     /* Returns a tuple. First value is true if command line arguments were successfully
110      * processed and execution should continue, or false if an error occurred or the user
111      * asked for help. If false, the second value is the appropriate exit code (0 or 1).
112      *
113      * Returning true (execution continues) means args have been validated and derived
114      * values calculated. In addition, field indices have been converted to zero-based.
115      * If the whole line is the key, the individual fields list will be cleared.
116      *
117      * Repeat count control variables 'atLeast' and max' - These values are left at zero
118      * if no repeat count options are specified. They are set if repeat count options
119      * are specified, as follows:
120      *   * atLeast - Will be zero unless --r|repeated or --a|at-least is specified.
121      *     --r|repeated option sets it 2, --a|at-least sets it to the specified value.
122      *   * max - Default to zero. Is set to the --m|max value if provided. Is set to
123      *    'atLeast' if --r|repeated or --a|at-least is provided.
124      *
125      * An exception to the above: If --e|equiv-mode is specified, then (max == 0)
126      * represents the default "output all values" case. In this case max may be less
127      * than the at-least value.
128      */
129     auto processArgs (ref string[] cmdArgs)
130     {
131         import std.algorithm : any, each;
132         import std.getopt;
133         import std.path : baseName, stripExtension;
134         import std.typecons : Yes, No;
135         import tsv_utils.common.utils :  makeFieldListOptionHandler;
136 
137         programName = (cmdArgs.length > 0) ? cmdArgs[0].stripExtension.baseName : "Unknown_program_name";
138 
139         try
140         {
141             arraySep = ",";    // Use comma to separate values in command line options
142             auto r = getopt(
143                 cmdArgs,
144                 "help-verbose",  "              Print full help.", &helpVerbose,
145                 std.getopt.config.caseSensitive,
146                 "V|version",     "              Print version information and exit.", &versionWanted,
147                 "H|header",      "              Treat the first line of each file as a header.", &hasHeader,
148                 std.getopt.config.caseInsensitive,
149 
150                 "f|fields",      "<field-list>  Fields to use as the key. Default: 0 (entire line).",
151                 fields.makeFieldListOptionHandler!(size_t, No.convertToZeroBasedIndex,Yes.allowFieldNumZero),
152 
153                 "i|ignore-case", "              Ignore case when comparing keys.", &ignoreCase,
154                 "r|repeated",    "              Output only lines that are repeated (based on the key).", &onlyRepeated,
155                 "a|at-least",    "INT           Output only lines that are repeated INT times (based on the key). Zero and one are ignored.", &atLeast,
156                 "m|max",         "INT           Max number of each unique key to output (zero is ignored).", &max,
157                 "e|equiv",       "              Output equivalence class IDs rather than uniq'ing entries.", &equivMode,
158                 "equiv-header",  "STR           Use STR as the equiv-id field header (when using '-H --equiv'). Default: 'equiv_id'.", &equivHeader,
159                 "equiv-start",   "INT           Use INT as the first equiv-id. Default: 1.", &equivStartID,
160                 "z|number",      "              Output equivalence class occurrence counts rather than uniq'ing entries.", &numberMode,
161                 "number-header", "STR           Use STR as the '--number' field header (when using '-H --number)'. Default: 'equiv_line'.", &numberHeader,
162                 "d|delimiter",   "CHR           Field delimiter. Default: TAB. (Single byte UTF-8 characters only.)", &delim,
163                 );
164 
165             if (r.helpWanted)
166             {
167                 defaultGetoptPrinter(helpText, r.options);
168                 return tuple(false, 0);
169             }
170             else if (helpVerbose)
171             {
172                 defaultGetoptPrinter(helpTextVerbose, r.options);
173                 return tuple(false, 0);
174             }
175             else if (versionWanted)
176             {
177                 import tsv_utils.common.tsvutils_version;
178                 writeln(tsvutilsVersionNotice("tsv-uniq"));
179                 return tuple(false, 0);
180             }
181 
182             /* Consistency checks */
183             if (!equivMode)
184             {
185                 if (equivHeader != defaultEquivHeader)
186                 {
187                     throw new Exception("--equiv-header requires --e|equiv");
188                 }
189                 else if (equivStartID != defaultEquivStartID)
190                 {
191                     throw new Exception("--equiv-start requires --e|equiv");
192                 }
193             }
194 
195             if (!numberMode && numberHeader != defaultNumberHeader)
196             {
197                  throw new Exception("--number-header requires --z|number");
198             }
199 
200             if (fields.length > 1 && fields.any!(x => x == 0))
201             {
202                 throw new Exception("Whole line as key (--f|field 0) cannot be combined with multiple fields.");
203             }
204 
205             /* Derivations */
206             if (fields.length == 0)
207             {
208                 keyIsFullLine = true;
209             }
210             else if (fields.length == 1 && fields[0] == 0)
211             {
212                 keyIsFullLine = true;
213                 fields.length = 0;
214             }
215 
216             if (onlyRepeated && atLeast <= 1) atLeast = 2;
217             if (atLeast >= 2 && max < atLeast)
218             {
219                 // Don't modify max if it is zero and equivMode or numberMode is in effect.
220                 if (max != 0 || (!equivMode && !numberMode)) max = atLeast;
221             }
222 
223             if (!keyIsFullLine) fields.each!((ref x) => --x);  // Convert to 1-based indexing.
224 
225         }
226         catch (Exception exc)
227         {
228             stderr.writefln("[%s] Error processing command line arguments: %s", programName, exc.msg);
229             return tuple(false, 1);
230         }
231         return tuple(true, 0);
232     }
233 }
234 
235 static if (__VERSION__ >= 2085) extern(C) __gshared string[] rt_options = [ "gcopt=cleanup:none" ];
236 
237 /** Main program. Processes command line arguments and calls tsvUniq which implements
238  * the main processing logic.
239  */
240 int main(string[] cmdArgs)
241 {
242     /* When running in DMD code coverage mode, turn on report merging. */
243     version(D_Coverage) version(DigitalMars)
244     {
245         import core.runtime : dmd_coverSetMerge;
246         dmd_coverSetMerge(true);
247     }
248 
249     TsvUniqOptions cmdopt;
250     auto r = cmdopt.processArgs(cmdArgs);
251     if (!r[0]) return r[1];
252     try tsvUniq(cmdopt, cmdArgs[1..$]);
253     catch (Exception exc)
254     {
255         stderr.writefln("Error [%s]: %s", cmdopt.programName, exc.msg);
256         return 1;
257     }
258     return 0;
259 }
260 
261 /** Outputs the unique lines from all the input files.
262  *
263  * Processes the lines in each input file. All lines are added to an associated array.
264  * The first time a line is seen it is output. If key fields are being used these are
265  * used as the basis for the associative array entries rather than the full line.
266  */
267 void tsvUniq(in TsvUniqOptions cmdopt, in string[] inputFiles)
268 {
269     import tsv_utils.common.utils : InputFieldReordering, bufferedByLine, BufferedOutputRange;
270     import std.algorithm : splitter;
271     import std.array : join;
272     import std.conv : to;
273     import std.range;
274     import std.uni : toLower;
275 
276     /* InputFieldReordering maps the key fields from an input line to a separate buffer. */
277     auto keyFieldsReordering = cmdopt.keyIsFullLine ? null : new InputFieldReordering!char(cmdopt.fields);
278 
279     /* BufferedOutputRange is a performance enhancement for writing to stdout. */
280     auto bufferedOutput = BufferedOutputRange!(typeof(stdout))(stdout);
281 
282     /* The master hash. The key is the specified fields concatenated together (including
283      * separators). The value is a struct with the equiv-id and occurrence count.
284      */
285     struct EquivEntry { size_t equivID; size_t count; }
286     EquivEntry[string] equivHash;
287 
288     size_t numFields = cmdopt.fields.length;
289     long nextEquivID = cmdopt.equivStartID;
290     bool headerWritten = false;
291     foreach (filename; (inputFiles.length > 0) ? inputFiles : ["-"])
292     {
293         auto inputStream = (filename == "-") ? stdin : filename.File();
294         foreach (lineNum, line; inputStream.bufferedByLine.enumerate(1))
295         {
296             if (cmdopt.hasHeader && lineNum == 1)
297             {
298                 /* Header line. */
299                 if (!headerWritten)
300                 {
301                     bufferedOutput.append(line);
302 
303                     if (cmdopt.equivMode)
304                     {
305                         bufferedOutput.append(cmdopt.delim);
306                         bufferedOutput.append(cmdopt.equivHeader);
307                     }
308 
309                     if (cmdopt.numberMode)
310                     {
311                         bufferedOutput.append(cmdopt.delim);
312                         bufferedOutput.append(cmdopt.numberHeader);
313                     }
314 
315                     bufferedOutput.appendln();
316                     headerWritten = true;
317                 }
318             }
319             else
320             {
321                 /* Regular line (not header). Start by finding the key. */
322                 typeof(line) key;
323                 if (cmdopt.keyIsFullLine)
324                 {
325                     key = line;
326                 }
327                 else
328                 {
329                     assert(keyFieldsReordering !is null);
330 
331                     /* Copy the key fields to a new buffer. */
332                     keyFieldsReordering.initNewLine;
333                     foreach (fieldIndex, fieldValue; line.splitter(cmdopt.delim).enumerate)
334                     {
335                         keyFieldsReordering.processNextField(fieldIndex, fieldValue);
336                         if (keyFieldsReordering.allFieldsFilled) break;
337                     }
338 
339                     if (!keyFieldsReordering.allFieldsFilled)
340                     {
341                         throw new Exception(
342                             format("Not enough fields in line. File: %s, Line: %s",
343                                    (filename == "-") ? "Standard Input" : filename, lineNum));
344                     }
345 
346                     key = keyFieldsReordering.outputFields.join(cmdopt.delim);
347                 }
348 
349                 if (cmdopt.ignoreCase) key = key.toLower;
350 
351                 bool isOutput = false;
352                 EquivEntry currEntry;
353                 EquivEntry* priorEntry = (key in equivHash);
354                 if (priorEntry is null)
355                 {
356                     isOutput = (cmdopt.atLeast <= 1);
357                     currEntry.equivID = nextEquivID;
358                     currEntry.count = 1;
359                     equivHash[key.to!string] = currEntry;
360                     nextEquivID++;
361                 }
362                 else
363                 {
364                     (*priorEntry).count++;
365                     currEntry = *priorEntry;
366 
367                     if ((currEntry.count <= cmdopt.max && currEntry.count >= cmdopt.atLeast) ||
368                         (cmdopt.equivMode && cmdopt.max == 0) ||
369                         (cmdopt.numberMode && cmdopt.max == 0))
370                     {
371                         isOutput = true;
372                     }
373                 }
374 
375                 if (isOutput)
376                 {
377                     bufferedOutput.append(line);
378 
379                     if (cmdopt.equivMode)
380                     {
381                         bufferedOutput.append(cmdopt.delim);
382                         bufferedOutput.append(currEntry.equivID.to!string);
383                     }
384 
385                     if (cmdopt.numberMode)
386                     {
387                         bufferedOutput.append(cmdopt.delim);
388                         bufferedOutput.append(currEntry.count.to!string);
389                     }
390 
391                     bufferedOutput.appendln();
392                 }
393             }
394         }
395     }
396 }