All files / marshallers dsv.js

85.88% Statements 152/177
76% Branches 114/150
100% Functions 11/11
85.33% Lines 128/150

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 2891x   1x                                           1301x                             1300x   1300x 1300x 1300x 1300x 1300x 1300x 1300x 1300x 1300x 1300x 1300x 1300x           1300x             1300x 1300x 6500x 6500x   1300x   1000x               1000x 1000x 1000x   1000x 1000x 1000x 1000x 1000x   1000x 10250x 10250x 4627x 4627x   10250x     1000x 1000x 1000x   1000x 100x 100x     1000x 700x 700x   700x 700x 700x 700x 700x     700x     1000x 1000x 1000x   1000x 508x 508x 508x     1000x   1000x 10250x 10250x   10250x 71534x 10250x     1000x       1000x 1000x   1000x 10142x   10142x   10142x 9198x 9198x   9198x 74210x 74210x 74210x       10142x   10142x 81043x   81043x     77422x 3621x           3621x   3621x 1498x 2123x 2123x                                                             10142x     1000x       508x 508x   508x 5454x   5454x   5454x 692x 692x 692x   692x   4762x       508x       1137x 1137x 8291x 8291x 8291x   1137x       1165x 1165x 10043x 10043x 10043x   1165x       1199x 1199x 12369x 12369x   1199x       1126x 1126x 1126x 10874x 10874x 7719x   1126x          
const handleMissingOption = require('../shared/handleMissingOption')
 
module.exports = {
  name: 'dsv',
  desc: (
    'is a delimiter-separated values marshaller:\n\n' +
    '--mrecord-separator, --record-separator, -R [char]\nCharacter used to separate records.\n\n' +
    '--mdelimiter, --delimiter, -D [char]\nDelimiter used to separate values.\n\n' +
    '--mquote, --quote, -Q [char]\nCharacter used to quote strings.\n\n' +
    '--mescape, --escape, -C [char]\nCharacter used to escape quote in strings.\n\n' +
    '--mheader, --header, -H [string]\nProvide a custom header as a JSON array string.\n\n' +
    '--mskip-header, --skip-header, -S [boolean]\nDo not print a header.\n\n' +
    '--mallow-list-values, --allow-list-values, -L [boolean]\nIf this flag is set, lists and objects are allowed in csv values. They are encoded as JSON.\n\n' +
    '--mfixed-length, --fixed-length, -F [boolean]\nPreprocessing #1: Controls, whether each line has the same number of values. Ignores all deviating lines while reporting errors.\n\n' +
    '--mtrim-whitespaces, --trim-whitespaces, -W [boolean]\nPreprocessing #2: Trim whitespaces around values.\n\n' +
    '--mempty-as-null, --empty-as-null, -I [boolean]\nPreprocessing #3: Treat empty fields as null.\n\n' +
    '--mskip-null, --skip-null, -N [boolean]\nPreprocessing #4: Skip values that are null.\n\n' +
    '--mmissing-as, --missing-as, -M [string]\nPreprocessing #5: Treat missing fields (if #values < #keys) as null.\n'
  ),
  func: dsv({}),
  dsv
}
 
function dsv (defaults) {
  return argv => {
    const {
      verbose,
      mrecordSeparator,      recordSeparator,      R,
      mdelimiter,            delimiter,            D,
      mquote,                quote,                Q,
      mescape,               escape,               C,
      mheader,               header,               H,
      mskipHeader,           skipHeader,           S,
      mallowListValues,      allowListValues,      L,
      mfixedLength,          fixedLength,          F,
      mtrimWhitespaces,      trimWhitespaces,      W,
      memptyAsNull,          emptyAsNull,          I,
      mskipNull,             skipNull,             N,
      mnullAs,               nullAs,               A
    } = argv
 
    const _recordSeparator = mrecordSeparator      || recordSeparator      || R || defaults.recordSeparator
    const _delimiter       = mdelimiter            || delimiter            || D || defaults.delimiter
    const _quote           = mquote                || quote                || Q || defaults.quote
    const _escape          = mescape               || escape               || C || defaults.escape
    const _header          = mheader               || header               || H || defaults.header
    const _skipHeader      = mskipHeader           || skipHeader           || S || defaults.skipHeader      || false
    const _allowListValues = mallowListValues      || allowListValues      || L || defaults.allowListValues || false
    const _fixedLength     = mfixedLength          || fixedLength          || F || defaults.fixedLength     || false
    const _trimWhitespaces = mtrimWhitespaces      || trimWhitespaces      || W || defaults.trimWhitespaces || false
    const _emptyAsNull     = memptyAsNull          || emptyAsNull          || I || defaults.emptyAsNull     || false
    const _skipNull        = mskipNull             || skipNull             || N || defaults.skipNull        || false
    const _nullAs          = typeof mnullAs         !== 'undefined' ? mnullAs :
                             typeof nullAs          !== 'undefined' ? nullAs  :
                             typeof A               !== 'undefined' ? A       :
                             typeof defaults.nullAs !== 'undefined' ? defaults.nullAs
                                                                    : undefined
 
    const missingOptions = [
      handleMissingOption(_recordSeparator, 'mrecordSeparator, recordSeparator or R', argv),
      handleMissingOption(_delimiter,       'mdelimiter, delimiter or D',             argv),
      handleMissingOption(_quote,           'mquote, quote or Q',                     argv),
      handleMissingOption(_escape,          'mescape, escape or C',                   argv),
      handleMissingOption(_header,          'mheader, header or H',                   argv)
    ]
    let err      = []
    for (let i = 0; i < missingOptions.length; i++) {
      const errs = missingOptions[i]
      err        = err.concat(errs)
    }
    if (err.length > 0) return () => ({err, str: ''})
 
    let keys                = JSON.parse(_header)
 
    // skipHeader | header || addProvidedHeader | headerIsSet | ignoreDataHeader
    // true       | [...]  || false             | true        | true
    // true       | []     || false             | true        | true
    // false      | [...]  || true              | false       | false
    // false      | []     || false             | false       | false
 
    const addProvidedHeader = !_skipHeader && keys.length > 0
    let headerIsSet         = _skipHeader
    const fillMissingValues = typeof _nullAs !== 'undefined'
 
    const preprocessingFs   = []
    if (_trimWhitespaces)  preprocessingFs.push(removeWhitespaces)
    if (_emptyAsNull)      preprocessingFs.push(emptyToNull)
    if (_skipNull)         preprocessingFs.push(removeNulls)
    if (fillMissingValues) preprocessingFs.push(replaceNulls)
 
    const preprocessingF = record => {
      let record2 = record
      for (let i = 0; i < preprocessingFs.length; i++) {
        const f   = preprocessingFs[i]
        record2   = f(record2)
      }
      return record2
    }
 
    return jsons => {
      let err     = []
      let records = []
 
      if (!headerIsSet && addProvidedHeader) {
        records.push(keys)
        headerIsSet = true
      }
 
      if (!headerIsSet) {
        Eif (jsons.length > 0) {
          const json = jsons[0]
 
          Iif (Array.isArray(json)) keys = json
          else Iif (json === null)  keys = []
          else Eif (typeof json === 'object') {
            keys                        = Object.keys(json)
            records.push(keys)
          } else keys                   = []
        }
        headerIsSet = true
      }
 
      let res = jsonsToRecords(jsons)
      Iif (res.err.length > 0) err = err.concat(res.err)
      records = records.concat(res.records)
 
      if (_fixedLength) {
        res     = controlFixedLength(records)
        if (res.err.length > 0) err = err.concat(res.err)
        records = res.records
      }
      
      let str = ''
 
      for (let i = 0; i < records.length; i++) {
        let record = records[i]
        record     = preprocessingF(record)
 
        str += record[0]
        for (let i = 1; i < record.length; i++) str += _delimiter + record[i]
        str += _recordSeparator
      }
 
      return ({err, str})
    }
 
    function jsonsToRecords (jsons) {
      const err     = []
      const records = []
      
      for (let i = 0; i < jsons.length; i++) {
        const json = jsons[i]
 
        let record = []
 
        if (Array.isArray(json)) record = json
        else Eif (typeof json === 'object' && json !== null) {
          const keys = Object.keys(json)
 
          for (let j = 0; j < keys.length; j++) {
            const key = keys[j]
            const value = json[key]
            record.push(value)
          }
        }
 
        const record2 = []
 
        for (let j = 0; j < record.length; j++) {
          const field = record[j]
 
          if (typeof field === 'string') {
            // add quotes to records?
            // escape quotes in records?
            record2.push(field)
          } else Iif (typeof field === 'number') {
            if (Number.isNaN(field)) {
              record2.push(null)
            } else {
              record2.push(field.toString())
            }
          } else Iif (typeof field === 'boolean') {
            record2.push(field.toString())
          } else if (typeof field === 'undefined') {
            record2.push(null)
          } else Eif (field === null) {
            record2.push(null)
          } else if (Array.isArray(field)) {
            if (_allowListValues) {
              // in case of string values
              // add quotes to records?
              // escape quotes in records?
            } else {
              const msg  = {msg: 'Arrays are not allowed as fields'}
              const line = verbose > 0 ? {line: -1}                    : {}
              const info = verbose > 1 ? {info: JSON.stringify(field)} : {}
              err.push(Object.assign(msg, line, info))
            }
          } else if (typeof field === 'object') {
            if (_allowListValues) {
              // in case of string values
              // add quotes to records?
              // escape quotes in records?
            } else {
              const msg  = {msg: 'Objects are not allowed as fields'}
              const line = verbose > 0 ? {line: -1}                    : {}
              const info = verbose > 1 ? {info: JSON.stringify(field)} : {}
              err.push(Object.assign(msg, line, info))
            }
          } else {
            const msg  = {msg: 'Type not allowed as field'}
            const line = verbose > 0 ? {line: -1}                                      : {}
            const info = verbose > 1 ? {info: `${field.toString()} (${typeof field})`} : {}
            err.push(Object.assign(msg, line, info))
          }
        }
 
        records.push(record2)
      }
 
      return {err: [], records}
    }
 
    function controlFixedLength (records) {
      const err      = []
      const records2 = []
 
      for (let i = 0; i < records.length; i++) {
        const record = records[i]
 
        if (keys.length === 0) keys = record
 
        if (headerIsSet && keys.length !== record.length) {
          const msg  = {msg: 'Number of values does not match number of headers'}
          const line = verbose > 0 ? {line: -1}                                                             : {}
          const info = verbose > 1 ? {info: `values [${record.join(',')}] and headers [${keys.join(',')}]`} : {}
          
          err.push(Object.assign(msg, line, info))
        } else {
          records2.push(record)
        }
      }
 
      return {err, records: records2}
    }
 
    function removeWhitespaces (record) {
      const record2 = []
      for (let i = 0; i < record.length; i++) {
        const value  = record[i]
        const value2 = value.replace(/^\s+|\s+$/g, '')
        record2.push(value2)
      }
      return record2
    }
 
    function emptyToNull (record) {
      const record2 = []
      for (let i = 0; i < record.length; i++) {
        const value  = record[i]
        const value2 = value === '' ? null : value
        record2.push(value2)
      }
      return record2
    }
 
    function removeNulls (record) {
      const record2 = []
      for (let i = 0; i < record.length; i++) {
        const value = record[i]
        if (value !== null && typeof value !== 'undefined') record2.push(value)
      }
      return record2
    }
 
    function replaceNulls (record) {
      Eif (headerIsSet) {
        const record2 = []
        for (let i = 0; i < keys.length; i++) {
          const value = record[i]
          if (value === null || typeof value === 'undefined') record2.push(_nullAs)
          else record2.push(value)
        }
        return record2
      }
      return record
    }
  }
}