module CsvShapeCheck

Overview

Inspect the shape of a CSV file before an import: byte order mark, line endings, delimiter, header problems, rows with a different field count, blank and empty records, cells with stray spaces and an unterminated quote. It reads shape only and does not judge what the cells contain. The CSV reader is written here (double quotes, "" escapes, line breaks inside quotes) so the shard needs nothing but the standard prelude.

Defined in:

csv_shape_check.cr

Constant Summary

CANDIDATES = [{',', "comma"}, {';', "semicolon"}, {'\t', "tab"}, {'|', "pipe"}]

Candidates in tie-break order.

CR = '\r'.ord.to_u8
GUESS_RECORDS = 20
LF = '\n'.ord.to_u8
QUOTE = '"'.ord.to_u8
USAGE = "usage: csv-shape-check file.csv [--delimiter \",\"]\nChecks the shape of a CSV file before an import. It does not judge the content of the cells. --delimiter takes , or ; or tab or | and skips the guess. Exit 0 no problem, 1 problems found, 2 unreadable or bad usage.\nMore: https://www.onegtmlab.dev/tool-directory/how-to/verify-emails"
VERSION = "1.0.0"

Class Method Summary

Class Method Detail

def self.analyze(bytes : Bytes, delimiter : UInt8 | Nil = nil) : Report #

Analyse the bytes of a CSV file. delimiter nil means guess it.


[View source]
def self.cli(args : Array(String), stdout : IO, stderr : IO) : Int32 #

Command line entry. Returns the exit code: 0 no problem, 1 problems found, 2 error.


[View source]
def self.delimiter_from(text : String) : UInt8 #

--delimiter value: "," ";" "tab" "|"


[View source]
def self.delimiter_name(d : UInt8) : String #

[View source]
def self.guess_delimiter(bytes : Bytes, offset : Int32) : Tuple(UInt8, Bool) #

The candidate whose field count is most consistent over the first 20 records. A candidate counts only when its most common field count is above one. Ties go to the earlier candidate (comma, semicolon, tab, pipe). When none qualifies the file looks like a single column and comma is returned.


[View source]
def self.line_ending_style(p : Parsed) : Tuple(String, Bool) #

[View source]
def self.parse(bytes : Bytes, offset : Int32, delim : UInt8, limit : Int32 | Nil = nil) : Parsed #

Read records from bytes starting at offset. Line numbers are physical lines (every LF, CRLF or lone CR starts a new line, also inside quotes). Line endings and blank lines are counted outside quotes only. When limit is set, reading stops after that many records.


[View source]