All files / gulpfile.ts/lib utils.ts

65.48% Statements 55/84
14.29% Branches 4/28
72.73% Functions 16/22
66.67% Lines 48/72

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 2062x 2x 2x 2x 2x 2x 2x 2x 2x   14x 4x     2x   2x                         2x 1x           3x       2x 1x 1x 1x 1x 1x 1x   1x                       4x       2x                                                                                                     2x     2x           2x 1x 1x               1x     1x           6x 4x           2x 1x                                   2x   2x   2x       2x     2x   1x   2x 2x               2x   1x               1x    
import { codeFrameColumns } from '@babel/code-frame'
import chalk from 'chalk'
import * as deepmerge from 'deepmerge'
import * as fs from 'fs'
import * as notify from 'gulp-notify'
import * as ImportLazy from 'import-lazy'
import * as logSymbols from 'log-symbols'
import * as os from 'os'
import * as path from 'path'
 
export const pathToUrl = (...args: string[]) => {
  return path.join(...args).replace(/\\/g, '/')
}
 
const colors = new chalk.constructor({ enabled: true })
 
export const errorDisplayHelper = {
  error: {
    messageColor: colors.red,
    severityText: 'error',
    symbol: logSymbols.error,
  },
  warning: {
    messageColor: colors.yellow,
    severityText: 'warning',
    symbol: logSymbols.warning,
  },
}
 
export const getFrameColumns = (rawLines: any, message: any) => {
  return codeFrameColumns(
    rawLines,
    { start: { line: message.line, column: message.character } },
    { highlightCode: true }
  )
    .split('\n')
    .map((str: string) => `  ${str}`)
    .join(os.EOL)
}
 
export const getWbMessage = ({
  frame,
  fullMessage,
  symbol,
  messageColor,
  severityText,
  ruleName,
}: any) => {
  return [
    [
      messageColor.bold(`Type ${severityText}: `),
      fullMessage,
      '  ',
      symbol,
      messageColor.underline(ruleName),
    ].join(' '),
    frame && '',
    frame,
    frame && '',
  ]
    .filter(e => !!e || e === '')
    .join(os.EOL)
}
 
export const esWbformatter = ({ basePath }: any) => (results: any) => {
  if (!results || !results.length) {
    return ''
  }
 
  let errorCount = 0
  let warningCount = 0
 
  const filesOutput = results.map((result: any) => {
    if (!result.messages || !result.messages.length) {
      return
    }
 
    const rawLines = fs.readFileSync(result.filePath, 'utf8')
    const numLines = rawLines.split('\n').length - 1
 
    const messagesOutput = result.messages.map((message: any) => {
      const isError = message.severity === 2
      const selector = isError ? 'error' : 'warning'
      const { messageColor, severityText, symbol } = errorDisplayHelper[selector]
      isError ? warningCount++ : errorCount++
      // ESLint goes a bit crazy at times
      // If the current line returned in the message is more, we simply don't generate a code frame
      const generateFrame = message.line <= numLines
      return getWbMessage({
        frame: generateFrame && getFrameColumns(rawLines, message),
        fullMessage: message.message,
        messageColor,
        ruleName: `ES ${message.ruleId}`,
        severityText,
        symbol,
      })
    })
    const filename = chalk.underline(path.relative(basePath, result.filePath))
    return [filename, messagesOutput.join(os.EOL)].join(os.EOL)
  })
 
  const finalOutput = [
    '',
    filesOutput.filter((s: any) => s).join(os.EOL),
    errorCount && chalk.red(`Error/s: ${errorCount}`),
    warningCount && chalk.yellow(`Warning/s: ${warningCount}`),
    '',
  ]
    .filter(Boolean)
    .join(os.EOL)
 
  return errorCount + warningCount > 0 ? finalOutput : ''
}
 
/** Provides empty defaults for empty objects or arrays */
const getEmptyTarget = (value: any) => (Array.isArray(value) ? [] : {})
 
/** Normalises objects for merge. */
const clone = (value: any, options: any) => deepmerge(getEmptyTarget(value), value, options)
 
/**
 * Recursively combines two objects.
 * Nested arrays are merged as well.
 */
export const arrayMerge = (target: any, source: any, options: any) => {
  const destination = target.slice()
  source.forEach((e: any, i: any) => {
    if (typeof destination[i] === 'undefined') {
      const cloneRequested = options.clone !== false
      const shouldClone = cloneRequested && options.isMergeableObject(e)
      destination[i] = shouldClone ? clone(e, options) : e
    } else if (options.isMergeableObject(e)) {
      destination[i] = deepmerge(target[i], e, options)
    } else if (target.indexOf(e) === -1) {
      destination.push(e)
    }
  })
  return destination
}
 
/**
 * Finds the first valid object from a list of arguments.
 */
export const getFirstValidObject = (...objs: any[]) => {
  return objs.find(obj => typeof obj === 'object')
}
 
/**
 * Handles gulp errors.
 */
export const handleErrors = function(this: any, errorObject: any) {
  notify
    .onError(
      errorObject
        .toString()
        .split(': ')
        .join(':\n')
    )
    .apply(this, arguments)
  // Keep gulp from hanging on this task
  if (this.emit === 'function') {
    this.emit('end')
  }
}
 
/**
 * Adds displayNames to functions.
 * Useful for debugging.
 */
export const setDisplayName = (fun: any, name: string) => {
  if (['function', 'object'].includes(typeof fun)) {
    fun.displayName = name
  }
  return fun
}
 
/** Lazily imports packages */
export const sureLazyImport = ImportLazy(require)
 
/** Checks if a folder is a child of the specified parent */
export const isChildOf = (child: string, parent: string) => {
  if (child === parent) {
    return false
  }
  const parentTokens = parent.split(path.sep).filter(i => i.length)
  return parentTokens.every((t, i) => child.split('/')[i] === t)
}
 
/**
 * Checks if gulp tasks exist.
 * If not, throws an error to notify the user to specify the right config.
 * Also sets the displayName for logging
 */
export const checkAndLabel = (fun: any, name: string) => {
  if (typeof fun !== 'function') {
    throw Error(
      chalk.red(
        `Please ensure that the alternative task for ${chalk.yellow(
          name
        )} returns a function that either returns a gulp stream, or manually calls a callback() to signal completion.`
      )
    )
  }
  setDisplayName(fun, name)
}