All files dsv.js

99.5% Statements 199/200
97.59% Branches 162/166
100% Functions 14/14
100% Lines 165/165

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 289 290 291 292 293 294 295 296 297 298 299 3001x                                         1701x                           1700x   1700x 1700x 1700x 1700x 1700x 1700x 1700x 1700x 1700x 1700x 1700x   1700x           1700x 1700x 6800x 6800x   1700x   1400x 1400x               1400x 1400x 1400x   1400x 1400x 1400x 1400x 1400x 1400x 1400x   1400x 15948x 15948x   15948x 14769x 14769x 14769x 14769x     15948x     1400x 1400x 1400x   1400x   1400x 15948x   15948x 15948x   15948x 15948x 15948x 15948x 15948x 15948x   15948x 1256238x   1256238x 190650x 190650x 46181x 4180x 4180x 2920x 4180x   42001x 37324x     144469x 5053x 5053x   139416x 134363x       1065588x 1050854x     1256238x 121270x 121270x 121270x   121270x 121270x   121270x     1256238x 1212x       15948x   15948x 100x     15948x 15948x 15948x 15948x   15948x 13851x 1100x 1100x 1100x 1100x 12751x 11706x   11706x   11706x 95304x 95304x 95304x     11706x   1045x         1400x       14734x 14734x 14734x 14734x   14734x       6313x 6313x 6313x 83137x 83137x 12626x 70511x 6313x 6313x   64198x 64198x     6313x 6313x       8423x 884x 884x 884x 884x   7539x         941x 941x 7612x 7612x 7612x   941x       2040x 2040x 14776x 14776x   2040x       1142x 1142x 9586x 9586x   1142x       1075x 1075x 7518x 7518x   1075x       1148x 1048x 1048x 1048x 9133x 9133x   1048x   100x             6800x 1200x 1200x 1200x 1200x   5600x  
module.exports = {
  name: 'dsv',
  desc: (
    'is a delimiter-separated values parser:\n\n' +
    '--pdelimiter, --delimiter, -D [char]\nDelimiter used to separate values.\n\n' +
    '--pquote, --quote, -Q [char]\nCharacter used to quote strings.\n\n' +
    '--pescape, --escape, -C [char]\nCharacter used to escape quote in strings.\n\n' +
    '--pheader, --header, -H [string]\nProvide a custom header as a JSON array string.\n\n' +
    '--pskip-header, --skip-header, -S [boolean]\nDo not interpret first line as header.\n\n' +
    '--pfixed-length, --fixed-length, -F [boolean]\nPost-processing #1: Controls, whether each line has the same number of values. Ignores all deviating lines while reporting errors.\n\n' +
    '--pskip-empty-values, --skip-empty-values, -E [boolean]\nPost-processing #2: Skip values that are empty strings.\n\n' +
    '--ptrim-whitespaces, --trim-whitespaces, -W [boolean]\nPost-processing #3: Trim whitespaces around values.\n\n' +
    '--pempty-as-null, --empty-as-null, -I [boolean]\nPost-processing #4: Treat empty fields as null.\n\n' +
    '--pskip-null, --skip-null, -N [boolean]\nPost-processing #5: Skip values that are null.\n\n' +
    '--pmissing-as-null, --missing-as-null, -M [boolean]\nPost-processing #6: Treat missing fields (if #values < #keys) as null.\n'
  ),
  func: dsv({}),
  dsv
}
 
function dsv (defaults) {
  return argv => {
    const {
      verbose,
      pdelimiter,       delimiter,       D,
      pquote,           quote,           Q,
      pescape,          escape,          C,
      pheader,          header,          H,
      pskipHeader,      skipHeader,      S,
      pfixedLength,     fixedLength,     F,
      pskipEmptyValues, skipEmptyValues, E,
      ptrimWhitespaces, trimWhitespaces, W,
      pemptyAsNull,     emptyAsNull,     I,
      pskipNull,        skipNull,        N,
      pmissingAsNull,   missingAsNull,   M
    } = argv
 
    const _delimiter       = pdelimiter       || delimiter       || D || defaults.delimiter
    const _quote           = pquote           || quote           || Q || defaults.quote
    const _escape          = pescape          || escape          || C || defaults.escape
    const _header          = pheader          || header          || H || defaults.header
    const _skipHeader      = pskipHeader      || skipHeader      || S || defaults.skipHeader      || false
    const _fixedLength     = pfixedLength     || fixedLength     || F || defaults.fixedLength     || false
    const _skipEmptyValues = pskipEmptyValues || skipEmptyValues || E || defaults.skipEmptyValues || false
    const _trimWhitespaces = ptrimWhitespaces || trimWhitespaces || W || defaults.trimWhitespaces || false
    const _emptyAsNull     = pemptyAsNull     || emptyAsNull     || I || defaults.emptyAsNull     || false
    const _skipNull        = pskipNull        || skipNull        || N || defaults.skipNull        || false
    const _missingAsNull   = pmissingAsNull   || missingAsNull   || M || defaults.missingAsNull   || false
  
    const missingOptions = [
      handleMissingOption(_delimiter, 'pdelimiter, delimiter or D', argv),
      handleMissingOption(_quote,     'pquote, quote or Q',         argv),
      handleMissingOption(_escape,    'pescape, escape or C',       argv),
      handleMissingOption(_header,    'pheader, 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, jsons: []})
 
    let keys               = JSON.parse(_header)
    let keysLength         = keys.length
 
    // skipHeader | header || return type | keys            | data header   || headerIsSet | ignoreDataHeader | returnTypeObject
    // true       | [...]  || JSON object | provided header | ignore        || true        | true             | true
    // true       | []     || JSON array  | none            | ignore        || true        | true             | false
    // false      | [...]  || JSON object | provided header | treat as data || true        | false            | true
    // false      | []     || JSON object | data header     | treat as keys || false       | false            | true
 
    let headerIsSet        =  _skipHeader || keysLength > 0
    let ignoreDataHeader   =  _skipHeader
    const returnTypeObject = !_skipHeader || keysLength > 0
 
    const postProcessingFs = []
    if (_fixedLength)     postProcessingFs.push(controlFixedLength)
    if (_skipEmptyValues) postProcessingFs.push(removeEmptyValues)
    if (_trimWhitespaces) postProcessingFs.push(removeWhitespaces)
    if (_emptyAsNull)     postProcessingFs.push(emptyToNull)
    if (_skipNull)        postProcessingFs.push(removeNulls)
    if (_missingAsNull)   postProcessingFs.push(missingToNull)
 
    const postProcessingF = (values, line) => {
      let err     = []
      let values2 = values
 
      for (let i = 0; i < postProcessingFs.length; i++) {
        const f   = postProcessingFs[i]
        const res = f(values2, line)
        if (res.err.length > 0) err = err.concat(res.err)
        values2   = res.values
      }
 
      return {err, values: values2}
    }
 
    return (tokens, lines) => {
      let err       = []
      const jsons   = []
 
      const start   = ignoreDataHeader ? 1 : 0
 
      for (let i = start; i < tokens.length; i++) {
        const token = tokens[i]
        
        let values  = []
        let from    = 0
 
        let inQuote          = false
        let mayBeEscaped     = false
        let isEscaped        = false
        let valueFound       = false
        let hasQuotes        = false
        let hasEscapedQuotes = false
 
        for (let at = 0; at < (token || '').length; at++) {
          const ch  = token.charAt(at)
 
          if (inQuote) {
                                        hasQuotes        = true
            if (_quote === _escape) {
              if (mayBeEscaped) {
                                        mayBeEscaped     = false
                if (ch === _quote)      hasEscapedQuotes = true
                else                    inQuote          = false
                if (ch === _delimiter)  valueFound       = true
              } else {
                if (ch === _escape)     mayBeEscaped     = true
                else Iif (ch === _quote) inQuote          = false
              }
            } else {
              if (isEscaped) {
                                        isEscaped        = false
                Eif (ch === _quote)      hasEscapedQuotes = true
              } else {
                if (ch === _escape)     isEscaped        = true
                else if (ch === _quote) inQuote          = false
              }
            }
          } else {
            if (ch === _quote)          inQuote          = true
            else if (ch === _delimiter) valueFound       = true
          }
 
          if (valueFound || at === token.length - 1) {
            let value  = token.slice(from, valueFound ? at : at + 1)
            valueFound = false
            from       = at + 1
 
            if (hasQuotes)        value = removeQuotes(value)
            if (hasEscapedQuotes) value = removeEscapedQuotes(value)
 
            values.push(value)
          }
 
          if (at === token.length - 1 && ch === _delimiter) {
            values.push('')
          }
        }
 
        if (token === '') values.push(token)
 
        if (keysLength === 0 && !returnTypeObject) {
          keysLength = values.length
        }
 
        const line = verbose > 0 ? lines[i] : undefined
        const res  = postProcessingF(values, line)
        if (res.err.length > 0) err = err.concat(res.err)
        values     = res.values
 
        if (values.length > 0) {
          if (!headerIsSet) {
            keys             = values
            keysLength       = keys.length
            headerIsSet      = true
            ignoreDataHeader = false
          } else if (returnTypeObject) {
            const json    = {}
            
            const until   = Math.min(keysLength, values.length)
  
            for (let j = 0; j < until; j++) {
              const key   = keys[j]
              const value = values[j]
              json[key]   = value
            }
  
            jsons.push(json)
          } else {
            jsons.push(values)
          }
        }
      }
 
      return {err, jsons}
    }
 
    function removeQuotes (value) {
      let value2 = value
      const len  = value.length
      Eif (len > 0 && value[0] === _quote && value[len - 1] === _quote) {
        value2   = value.slice(1, len - 1)
      }
      return value2
    }
 
    function removeEscapedQuotes (value) {
      let lastCh  = ''
      let value2  = ''
      for (let at = 0; at < value.length; at++) {
        const ch  = value[at]
        if (lastCh === '') {
          lastCh  = ch
        } else if (lastCh === _escape && ch === _quote) {
          value2 += ch
          lastCh  = ''
        } else {
          value2 += lastCh
          lastCh  = ch
        }
      }
      value2     += lastCh
      return value2
    }
 
    function controlFixedLength (values, lineNo) {
      if (headerIsSet && keysLength !== values.length) {
        const msg  = {msg: 'Number of values does not match number of headers'}
        const line = verbose > 0 ? {line: lineNo}                                                         : {}
        const info = verbose > 1 ? {info: `values [${values.join(',')}] and headers [${keys.join(',')}]`} : {}
        return {err: [Object.assign(msg, line, info)], values: []}
      } else {
        return {err: [], values}
      }
    }
    
    function removeWhitespaces (values) {
      let values2    = []
      for (let i = 0; i < values.length; i++) {
        const value  = values[i]
        const value2 = value.replace(/^\s+|\s+$/g, '')
        values2.push(value2)
      }
      return {err: [], values: values2}
    }
 
    function removeEmptyValues (values) {
      const values2 = []
      for (let i = 0; i < values.length; i++) {
        const value = values[i]
        if (value !== '') values2.push(value)
      }
      return {err: [], values: values2}
    }
    
    function emptyToNull (values) {
      const values2 = []
      for (let i = 0; i < values.length; i++) {
        const value = values[i]
        values2.push(value === '' ? null : value)
      }
      return {err: [], values: values2}
    }
 
    function removeNulls (values) {
      const values2 = []
      for (let i = 0; i < values.length; i++) {
        const value = values[i]
        Eif (value !== null) values2.push(value)
      }
      return {err: [], values: values2}
    }
    
    function missingToNull (values) {
      if (headerIsSet) {
        const len     = values.length
        const values2 = []
        for (let i = 0; i < keysLength; i++) {
          const value = i < len ? values[i] : null
          values2.push(value)
        }
        return {err: [], values: values2}
      } else {
        return {err: [], values}
      }
    }
  }
}
 
function handleMissingOption (field, options, argv) {
  if (typeof field === 'undefined') {
    const msg  = {msg: `Please provide ${options} option`}
    const line = argv.verbose > 0 ? {line: -1}                   : {}
    const info = argv.verbose > 1 ? {info: JSON.stringify(argv)} : {}
    return [Object.assign(msg, line, info)]
  }
  return []
}