|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/csv" |
| 5 | + "flag" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "os" |
| 9 | + "path" |
| 10 | + "strings" |
| 11 | + |
| 12 | + // Caltech Library Packages |
| 13 | + "github.com/caltechlibrary/cli" |
| 14 | + "github.com/caltechlibrary/datatools" |
| 15 | +) |
| 16 | + |
| 17 | +var ( |
| 18 | + usage = `USAGE: %s [OPTIONS]` |
| 19 | + |
| 20 | + description = ` |
| 21 | +%s normalizes a CSV file based on the options selected. It |
| 22 | +helps to address issues like variable number of columns, leading/trailing |
| 23 | +spaces in columns, and non-UTF-8 encoding issues. |
| 24 | +
|
| 25 | +By default input is expected from standard in and output is sent to |
| 26 | +standard out (errors to standard error). These can be modified by |
| 27 | +appropriate options. The csv file is processed as a stream of rows so |
| 28 | +minimal memory is used to operate on the file. |
| 29 | +
|
| 30 | +` |
| 31 | + |
| 32 | + examples = ` |
| 33 | +
|
| 34 | +EXAMPLES |
| 35 | +
|
| 36 | +Normalizing a spread sheet's column count to 5 padding columns as needed per row. |
| 37 | +
|
| 38 | + cat mysheet.csv | %s -field-per-row=5 |
| 39 | +
|
| 40 | +Trim leading spaces. |
| 41 | +
|
| 42 | + cat mysheet.csv | %s -left-trim-spaces |
| 43 | +
|
| 44 | +Trim trailing spaces. |
| 45 | +
|
| 46 | + cat mysheet.csv | %s -right-trim-spaces |
| 47 | +
|
| 48 | +Trim leading and trailing spaces |
| 49 | +
|
| 50 | + cat mysheet.csv | %s -trim-spaces |
| 51 | +
|
| 52 | +` |
| 53 | + |
| 54 | + // Standard Options |
| 55 | + showHelp bool |
| 56 | + showLicense bool |
| 57 | + showVersion bool |
| 58 | + showExamples bool |
| 59 | + inputFName string |
| 60 | + outputFName string |
| 61 | + |
| 62 | + // App Options |
| 63 | + comma string |
| 64 | + rowComment string |
| 65 | + fieldsPerRecord int |
| 66 | + lazyQuotes bool |
| 67 | + trailingComma bool |
| 68 | + trimSpace bool |
| 69 | + trimLeadingSpace bool |
| 70 | + trimTrailingSpace bool |
| 71 | + reuseRecord bool |
| 72 | + commaOut string |
| 73 | + useCRLF bool |
| 74 | + stopOnError bool |
| 75 | + |
| 76 | + verbose bool |
| 77 | +) |
| 78 | + |
| 79 | +func init() { |
| 80 | + // Standard options |
| 81 | + flag.BoolVar(&showHelp, "h", false, "display help") |
| 82 | + flag.BoolVar(&showHelp, "help", false, "display help") |
| 83 | + flag.BoolVar(&showLicense, "l", false, "display license") |
| 84 | + flag.BoolVar(&showLicense, "license", false, "display license") |
| 85 | + flag.BoolVar(&showVersion, "v", false, "display version") |
| 86 | + flag.BoolVar(&showVersion, "version", false, "display version") |
| 87 | + flag.BoolVar(&showExamples, "example", false, "display example(s)") |
| 88 | + flag.StringVar(&inputFName, "i", "", "input filename") |
| 89 | + flag.StringVar(&inputFName, "input", "", "input filename") |
| 90 | + flag.StringVar(&outputFName, "o", "", "output filename") |
| 91 | + flag.StringVar(&outputFName, "output", "", "output filename") |
| 92 | + |
| 93 | + // Application specific options |
| 94 | + flag.IntVar(&fieldsPerRecord, "fields-per-row", 0, "set the number of columns to output right padding empty cells as needed") |
| 95 | + flag.BoolVar(&lazyQuotes, "use-lazy-quoting", false, "If LazyQuotes is true, a quote may appear in an unquoted field and a non-doubled quote may appear in a quoted field.") |
| 96 | + flag.BoolVar(&trimSpace, "trim-spaces", false, "If set to true leading and trailing white space in a field is ignored.") |
| 97 | + flag.BoolVar(&trimLeadingSpace, "left-trim-spaces", false, "If set to true leading white space in a field is ignored.") |
| 98 | + flag.BoolVar(&trimTrailingSpace, "right-trim-spaces", false, "If set to true trailing white space in a field is ignored.") |
| 99 | + flag.BoolVar(&reuseRecord, "reuse", true, "if false then a new array is allocated for each row processed, if true the array gets reused") |
| 100 | + flag.StringVar(&comma, "comma", "", "if set use this character in place of a comma for delimiting cells") |
| 101 | + flag.StringVar(&rowComment, "comment-char", "", "if set, rows starting with this character will be ignored as comments") |
| 102 | + flag.StringVar(&commaOut, "output-comma", "", "if set use this character in place of a comma for delimiting output cells") |
| 103 | + flag.BoolVar(&useCRLF, "use-crlf", false, "if set use a charage return and line feed in output") |
| 104 | + flag.BoolVar(&stopOnError, "stop-on-error", false, "exit on error, useful if you're trying to debug a problematic CSV file") |
| 105 | + |
| 106 | + flag.BoolVar(&verbose, "verbose", false, "write verbose output to standard error") |
| 107 | +} |
| 108 | + |
| 109 | +func main() { |
| 110 | + appName := path.Base(os.Args[0]) |
| 111 | + flag.Parse() |
| 112 | + args := flag.Args() |
| 113 | + |
| 114 | + cfg := cli.New(appName, "", datatools.Version) |
| 115 | + cfg.UsageText = fmt.Sprintf(usage, appName) |
| 116 | + cfg.DescriptionText = fmt.Sprintf(description, appName) |
| 117 | + cfg.OptionText = "OPTIONS" |
| 118 | + cfg.ExampleText = fmt.Sprintf(examples, appName, appName, appName, appName) |
| 119 | + |
| 120 | + if showHelp == true { |
| 121 | + if len(args) > 0 { |
| 122 | + fmt.Println(cfg.Help(args...)) |
| 123 | + } else { |
| 124 | + fmt.Println(cfg.Usage()) |
| 125 | + } |
| 126 | + os.Exit(0) |
| 127 | + } |
| 128 | + |
| 129 | + if showExamples == true { |
| 130 | + if len(args) > 0 { |
| 131 | + fmt.Println(cfg.Example(args...)) |
| 132 | + } else { |
| 133 | + fmt.Println(cfg.ExampleText) |
| 134 | + } |
| 135 | + os.Exit(0) |
| 136 | + } |
| 137 | + |
| 138 | + if showLicense == true { |
| 139 | + fmt.Println(cfg.License()) |
| 140 | + os.Exit(0) |
| 141 | + } |
| 142 | + |
| 143 | + if showVersion == true { |
| 144 | + fmt.Println(cfg.Version()) |
| 145 | + os.Exit(0) |
| 146 | + } |
| 147 | + |
| 148 | + in, err := cli.Open(inputFName, os.Stdin) |
| 149 | + if err != nil { |
| 150 | + fmt.Fprintf(os.Stderr, "%s\n", err) |
| 151 | + os.Exit(1) |
| 152 | + } |
| 153 | + defer cli.CloseFile(inputFName, in) |
| 154 | + |
| 155 | + out, err := cli.Create(outputFName, os.Stdout) |
| 156 | + if err != nil { |
| 157 | + fmt.Fprintf(os.Stderr, "%s\n", err) |
| 158 | + os.Exit(1) |
| 159 | + } |
| 160 | + defer cli.CloseFile(outputFName, out) |
| 161 | + |
| 162 | + // Loop through input CSV, apply options, write to output CSV |
| 163 | + if trimSpace == true { |
| 164 | + trimLeadingSpace = true |
| 165 | + trimTrailingSpace = true |
| 166 | + } |
| 167 | + |
| 168 | + // Setup our CSV reader with any cli options |
| 169 | + var rStr []rune |
| 170 | + |
| 171 | + r := csv.NewReader(in) |
| 172 | + if comma != "" { |
| 173 | + rStr = []rune(comma) |
| 174 | + if len(rStr) > 0 { |
| 175 | + r.Comma = rStr[0] |
| 176 | + } |
| 177 | + } |
| 178 | + if rowComment != "" { |
| 179 | + rStr = []rune(rowComment) |
| 180 | + if len(rStr) > 0 { |
| 181 | + r.Comment = rStr[0] |
| 182 | + } |
| 183 | + } |
| 184 | + r.FieldsPerRecord = fieldsPerRecord |
| 185 | + r.LazyQuotes = lazyQuotes |
| 186 | + r.TrimLeadingSpace = trimLeadingSpace |
| 187 | + r.ReuseRecord = reuseRecord |
| 188 | + |
| 189 | + w := csv.NewWriter(out) |
| 190 | + if commaOut != "" { |
| 191 | + rStr = []rune(commaOut) |
| 192 | + if len(rStr) > 0 { |
| 193 | + w.Comma = rStr[0] |
| 194 | + } |
| 195 | + } |
| 196 | + w.UseCRLF = useCRLF |
| 197 | + |
| 198 | + // i is so we can track row count as we process each streamed in row |
| 199 | + expectedCellCount := 0 |
| 200 | + hasError := false |
| 201 | + i := 1 |
| 202 | + for { |
| 203 | + row, err := r.Read() |
| 204 | + if err == io.EOF { |
| 205 | + break |
| 206 | + } |
| 207 | + if i == 1 { |
| 208 | + expectedCellCount = len(row) |
| 209 | + } |
| 210 | + if err != nil { |
| 211 | + serr := fmt.Sprintf("%s", err) |
| 212 | + if strings.HasSuffix(serr, "wrong number of fields in line") == true && fieldsPerRecord >= 0 { |
| 213 | + if verbose { |
| 214 | + fmt.Fprintf(os.Stderr, "row %d: expected %d, got %d cells\n", i, expectedCellCount, len(row)) |
| 215 | + } |
| 216 | + // Trim trailing cells if needed |
| 217 | + if fieldsPerRecord > 0 && len(row) >= fieldsPerRecord { |
| 218 | + row = row[0:fieldsPerRecord] |
| 219 | + } |
| 220 | + // Append cells if needed |
| 221 | + for len(row) < expectedCellCount { |
| 222 | + row = append(row, "") |
| 223 | + } |
| 224 | + } else { |
| 225 | + hasError = true |
| 226 | + if verbose { |
| 227 | + fmt.Fprintf(os.Stderr, "%s\n", err) |
| 228 | + } |
| 229 | + } |
| 230 | + } |
| 231 | + if trimSpace { |
| 232 | + for i := range row { |
| 233 | + s := row[i] |
| 234 | + row[i] = strings.TrimSpace(s) |
| 235 | + } |
| 236 | + } |
| 237 | + if err := w.Write(row); err != nil { |
| 238 | + fmt.Fprintf(os.Stderr, "error writing row %d: %s\n", i, err) |
| 239 | + } |
| 240 | + i++ |
| 241 | + if verbose == true && (i%100) == 0 { |
| 242 | + fmt.Fprintf(os.Stderr, "Processed %d rows\n", i) |
| 243 | + } |
| 244 | + if hasError && stopOnError { |
| 245 | + os.Exit(1) |
| 246 | + } |
| 247 | + } |
| 248 | + // Finally we need to flush any remaining output... |
| 249 | + w.Flush() |
| 250 | + if verbose { |
| 251 | + fmt.Fprintf(os.Stderr, "Processed %d rows\n", i) |
| 252 | + } |
| 253 | +} |
0 commit comments