All files / modules/70-pipeline/components/PipelineStudio/PipelineCanvas/PipelineErrors PipelineErrors.tsx

100% Statements 115/115
80.6% Branches 108/134
100% Functions 31/31
100% Lines 105/105

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 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332              9x 9x 9x 9x 9x 9x     9x 9x 9x 9x 9x                               37x 49x 17x 64x 66x   9x 15x 15x         9x 14x                 37x 37x 3x   34x 34x 15x   19x 19x     37x         9x       14x   14x 19x   34x 34x 17x 17x 17x 17x   4x   13x 13x     34x         14x                   38x 38x 12x   26x   34x     1x                               38x 38x 14x   24x 26x 26x 26x 26x       34x     1x                 24x                   38x 38x 38x 38x   38x                                   30x 30x 24x     6x           9x   1x             9x           25x   25x   25x 3x   23x 22x 27x   22x 22x 5x 5x 2x     3x 2x       1x   5x   17x 7x     10x 6x       4x       25x                           30x       38x                         15x 15x 1x   14x 14x   14x                                                               9x  
/*
 * Copyright 2022 Harness Inc. All rights reserved.
 * Use of this source code is governed by the PolyForm Shield 1.0.0 license
 * that can be found in the licenses directory at the root of this repository, also available at
 * https://polyformproject.org/wp-content/uploads/2020/06/PolyForm-Shield-1.0.0.txt.
 */
 
import React from 'react'
import { get } from 'lodash-es'
import { Classes, Dialog } from '@blueprintjs/core'
import cx from 'classnames'
import { Text } from '@harness/uicore'
import { Color } from '@harness/design-system'
import type { YamlSchemaErrorDTO, NodeErrorInfo } from 'services/pipeline-ng'
import type { StringsMap } from 'stringTypes'
import { useStrings } from 'framework/strings'
import stepFactory from '@pipeline/components/PipelineSteps/PipelineStepFactory'
import { stageTypeToIconMap } from '@pipeline/components/PipelineInputSetForm/PipelineInputSetForm'
import PipelineErrorCard from './PipelineErrorCard'
import css from './PipelineErrors.module.scss'
 
type gotoViewWithDetails = (args: { stageId?: string; stepId?: string }) => void
 
export interface PropsInterface {
  errors: YamlSchemaErrorDTO[]
  gotoViewWithDetails: gotoViewWithDetails
  onClose: () => void
}
 
interface StageErrorsType {
  stageErrors: YamlSchemaErrorDTO[]
  errorsByStep: Record<string, YamlSchemaErrorDTO[]>
  stepIds: string[]
}
 
const isPipelineError = (item: YamlSchemaErrorDTO): boolean => !item.stageInfo && !item.stepInfo
const isStageError = (item: YamlSchemaErrorDTO): boolean => !!item.stageInfo && !item.stepInfo
const isStepError = (item: YamlSchemaErrorDTO): boolean => !!item.stageInfo && !!item.stepInfo
const getNameFromItem = (item: NodeErrorInfo = {}) => item.name || item.identifier || item.fqn
const getIdentifierFromItem = (item?: NodeErrorInfo) => item?.identifier || ''
 
const addToErrorsByStage = (errorsByStage: Record<string, YamlSchemaErrorDTO[]>, item: YamlSchemaErrorDTO) => {
  const identifier = getIdentifierFromItem(item.stageInfo)
  return isStageError(item)
    ? [item, ...(errorsByStage[identifier] || [])]
    : [...(errorsByStage[identifier] || []), item]
}
 
const getAdaptedErrors = (schemaErrors: YamlSchemaErrorDTO[]) =>
  schemaErrors.reduce(
    (
      accum: {
        stageIds: string[]
        errorsByStage: Record<string, YamlSchemaErrorDTO[]>
        pipelineErrors: Array<YamlSchemaErrorDTO>
      },
      item: YamlSchemaErrorDTO
    ) => {
      const errorsByStage = accum.errorsByStage
      if (isPipelineError(item)) {
        accum.pipelineErrors.push(item)
      } else {
        const identifier = getIdentifierFromItem(item.stageInfo)
        if (errorsByStage[identifier]) {
          errorsByStage[identifier] = addToErrorsByStage(errorsByStage, item)
        } else {
          errorsByStage[identifier] = [item]
          accum.stageIds.push(identifier)
        }
      }
      return accum
    },
    { stageIds: [], errorsByStage: {}, pipelineErrors: [] }
  )
 
const getAdaptedErrorsForStep = (
  stageIds: string[],
  errorsByStage: Record<string, YamlSchemaErrorDTO[]>
): Record<string, StageErrorsType> => {
  const updatedErrorsByStage: Record<string, StageErrorsType> = {}
 
  stageIds.forEach((stepId: string) => {
    updatedErrorsByStage[stepId] = errorsByStage[stepId]?.reduce(
      (accum: StageErrorsType, item: YamlSchemaErrorDTO) => {
        const { stageErrors, errorsByStep, stepIds } = accum
        if (isStageError(item)) {
          stageErrors.push(item)
        } else Eif (isStepError(item)) {
          const identifier = getIdentifierFromItem(item.stepInfo)
          if (errorsByStep[identifier]) {
            // push to existing object
            errorsByStep[identifier].push(item)
          } else {
            errorsByStep[identifier] = [item]
            stepIds.push(identifier)
          }
        }
        return accum
      },
      { stageErrors: [], errorsByStep: {}, stepIds: [] }
    )
  })
  return updatedErrorsByStage
}
 
function StageErrorCard({
  errors,
  gotoViewWithDetails
}: {
  errors: YamlSchemaErrorDTO[]
  gotoViewWithDetails: gotoViewWithDetails
}): React.ReactElement | null {
  const { getString } = useStrings()
  if (errors.length === 0) {
    return null
  }
  return (
    <PipelineErrorCard
      errors={errors.map(err => err?.message).filter(e => e) as string[]}
      icon={stageTypeToIconMap[errors[0].stageInfo?.type || '']}
      onClick={() => {
        gotoViewWithDetails({ stageId: errors[0].stageInfo?.identifier })
      }}
      buttonText={getString('pipeline.errorFramework.fixStage')}
    />
  )
}
 
function StepErrorCard({
  stepIds,
  errorsByStep,
  gotoViewWithDetails
}: {
  stepIds: string[]
  errorsByStep: Record<string, YamlSchemaErrorDTO[]>
  gotoViewWithDetails: gotoViewWithDetails
}): React.ReactElement | null {
  const { getString } = useStrings()
  if (stepIds.length === 0) {
    return null
  }
  const renderStepError = (stepId: string): React.ReactElement => {
    const stepErrors = errorsByStep[stepId] || []
    const stepName = getNameFromItem(stepErrors[0]?.stepInfo)
    const stepTitle = `${getString('pipeline.execution.stepTitlePrefix')} ${stepName}`
    return (
      <PipelineErrorCard
        key={stepId || stepName}
        title={stepTitle}
        errors={stepErrors.map(err => err.message).filter(e => e) as string[]}
        icon={stepFactory.getStepIcon(get(stepErrors[0], 'stepInfo.type', ''))}
        onClick={() => {
          gotoViewWithDetails({
            stageId: stepErrors[0]?.stageInfo?.identifier || '',
            stepId: stepErrors[0]?.stepInfo?.identifier || ''
          })
        }}
        buttonText={getString('pipeline.errorFramework.fixStep')}
      />
    )
  }
  return <>{stepIds.map(renderStepError)}</>
}
 
function StageErrors({
  errors,
  gotoViewWithDetails
}: {
  errors: StageErrorsType
  gotoViewWithDetails: gotoViewWithDetails
}): React.ReactElement {
  const { stepIds, errorsByStep, stageErrors } = errors
  const { getString } = useStrings()
  const stageInfo = stageErrors.length ? stageErrors[0].stageInfo : errorsByStep[stepIds[0]]?.[0]?.stageInfo
  const stageName = stageInfo ? getNameFromItem(stageInfo) : ''
 
  return (
    <>
      <Text color={Color.BLACK} font={{ weight: 'semi-bold', size: 'normal' }} margin={{ bottom: 'medium' }}>
        {getString('pipeline.execution.stageTitlePrefix')} {stageName}
      </Text>
      <StageErrorCard gotoViewWithDetails={gotoViewWithDetails} errors={stageErrors} />
      <StepErrorCard gotoViewWithDetails={gotoViewWithDetails} errorsByStep={errorsByStep} stepIds={stepIds} />
    </>
  )
}
 
function PipelineError({
  errors,
  gotoViewWithDetails
}: {
  errors: Array<YamlSchemaErrorDTO>
  gotoViewWithDetails: gotoViewWithDetails
}): React.ReactElement | null {
  const { getString } = useStrings()
  if (errors.length === 0) {
    return null
  }
 
  return (
    <>
      <Text color={Color.BLACK} font={{ weight: 'semi-bold', size: 'normal' }} margin={{ bottom: 'medium' }}>
        {getString('common.pipeline')}
      </Text>
      <PipelineErrorCard
        errors={errors.map(e => e.message).filter(e => e) as string[]}
        icon="pipeline"
        onClick={() => gotoViewWithDetails({})}
        buttonText={getString('pipeline.errorFramework.fixErrors')}
      />
    </>
  )
}
 
export const getFieldsLabel = (
  pipelineErrors: Array<YamlSchemaErrorDTO>,
  stageIds: string[],
  updatedErrorsByStage: Record<string, StageErrorsType>,
  getString: (str: keyof StringsMap, vars?: Record<string, any> | undefined) => string
) => {
  let str = ''
 
  const hasPipelineErrors = pipelineErrors.length
  // if only pipeline errors
  if (hasPipelineErrors && stageIds.length === 0) {
    str = getString('pipeline.errorFramework.header12')
  } else {
    const hasStageErrors = stageIds.some((stageId: string) => updatedErrorsByStage[stageId].stageErrors.length)
    const hasStepErrors = stageIds.some(
      (stageId: string) => Object.keys(updatedErrorsByStage[stageId]?.errorsByStep || {}).length
    )
    const errorInSingleStage = stageIds.length === 1
    if (hasPipelineErrors) {
      let stringToAppend = ''
      if (hasStageErrors && hasStepErrors) {
        stringToAppend = errorInSingleStage
          ? getString('pipeline.errorFramework.header1')
          : getString('pipeline.errorFramework.header2')
      } else if (hasStageErrors) {
        stringToAppend = errorInSingleStage
          ? getString('pipeline.errorFramework.header3')
          : getString('pipeline.errorFramework.header4')
      } else {
        stringToAppend = getString('pipeline.errorFramework.header5')
      }
      str = getString('pipeline.errorFramework.header6', { stringToAppend })
    } else {
      if (hasStageErrors && hasStepErrors) {
        str = errorInSingleStage
          ? getString('pipeline.errorFramework.header7')
          : getString('pipeline.errorFramework.header8')
      } else if (hasStageErrors) {
        str = errorInSingleStage
          ? getString('pipeline.errorFramework.header9')
          : getString('pipeline.errorFramework.header10')
      } else {
        str = getString('pipeline.errorFramework.header11')
      }
    }
  }
  return str || getString('pipeline.errorFramework.header12')
}
 
function PipelineErrorContent({
  stageIds,
  pipelineErrors,
  gotoViewWithDetails,
  updatedErrorsByStage
}: {
  stageIds: string[]
  pipelineErrors: Array<YamlSchemaErrorDTO>
  gotoViewWithDetails: gotoViewWithDetails
  updatedErrorsByStage: Record<string, StageErrorsType>
}) {
  return (
    <div className={css.pipelineErrorList}>
      <PipelineError errors={pipelineErrors} gotoViewWithDetails={gotoViewWithDetails} />
      {stageIds.map((stageId: string) => {
        return (
          <StageErrors key={stageId} gotoViewWithDetails={gotoViewWithDetails} errors={updatedErrorsByStage[stageId]} />
        )
      })}
    </div>
  )
}
 
function PipelineErrors({
  errors: schemaErrors,
  gotoViewWithDetails,
  onClose
}: PropsInterface): React.ReactElement | null {
  const { getString } = useStrings()
  if (!schemaErrors || !schemaErrors.length) {
    return null
  }
  const { stageIds, errorsByStage, pipelineErrors } = getAdaptedErrors(schemaErrors)
  const updatedErrorsByStage = getAdaptedErrorsForStep(stageIds, errorsByStage)
 
  return (
    <Dialog
      isOpen={true}
      enforceFocus={false}
      canEscapeKeyClose={false}
      canOutsideClickClose={false}
      onClose={onClose}
      title={
        <Text
          font={{ size: 'medium', weight: 'bold' }}
          color={Color.BLACK}
          icon="warning-icon"
          iconProps={{ size: 20, padding: { right: 'small' } }}
        >
          {getString('pipeline.errorFramework.pipelineErrorsTitle', {
            fields: getFieldsLabel(pipelineErrors, stageIds, updatedErrorsByStage, getString)
          })}
        </Text>
      }
      isCloseButtonShown
      className={cx(css.errorDialog, Classes.DIALOG)}
    >
      <PipelineErrorContent
        stageIds={stageIds}
        pipelineErrors={pipelineErrors}
        gotoViewWithDetails={gotoViewWithDetails}
        updatedErrorsByStage={updatedErrorsByStage}
      />
    </Dialog>
  )
}
 
export default PipelineErrors