All files / modules/70-pipeline/components/PipelineStudio StepUtil.ts

76.19% Statements 160/210
60.57% Branches 507/837
84.62% Functions 22/26
75.37% Lines 153/203

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 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566              96x 96x 96x 96x 96x 96x 96x 96x 96x 96x                       96x   96x 96x   96x   96x   96x 96x   96x 261x         96x 56x 56x 47x 27x 20x   20x               56x     96x       149x 149x 149x 191x 121x 70x 42x 78x 13x         149x                         96x             2x 2x 2x 2x 2x           2x       2x                     96x             2x 2x 2x 2x             2x                                                                     2x                     96x             14x                           14x       14x 14x 14x 14x                       14x 3x 3x           3x         14x 1x 1x           1x       14x       13x 13x           13x       14x               14x 12x 12x             12x 1x     12x 11x 11x             11x           14x 1x             1x       14x 1x             1x         14x                               96x           64x 64x 60x     64x                   64x         4x 2x             4x       1x             4x       1x     4x                     64x     96x               60x                           60x                 60x 1x 1x 1x   1x       1x 1x     1x 1x   1x         60x 48x 48x   48x 38x     60x 12x 12x 12x             12x 1x     12x                                             60x       96x 202x     97x 46x 51x 51x     46x           96x 151x 151x 151x 46x     46x     151x 151x 151x 151x 46x   151x     96x 5x   5x     5x                 5x    
/*
 * 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 { FormikErrors, yupToFormErrors } from 'formik'
import { getMultiTypeFromValue, MultiTypeInputType } from '@wings-software/uicore'
import isEmpty from 'lodash-es/isEmpty'
import has from 'lodash-es/has'
import * as Yup from 'yup'
import set from 'lodash-es/set'
import reduce from 'lodash-es/reduce'
import isObject from 'lodash-es/isObject'
import memoize from 'lodash-es/memoize'
import get from 'lodash-es/get'
import type {
  StageElementConfig,
  ExecutionWrapperConfig,
  PipelineInfoConfig,
  DeploymentStageConfig,
  Infrastructure,
  StageElementWrapperConfig,
  StepElementConfig
} from 'services/cd-ng'
 
import type { UseStringsReturn } from 'framework/strings'
import { getDurationValidationSchema } from '@common/components/MultiTypeDuration/MultiTypeDuration'
import type { TemplateStepNode } from 'services/pipeline-ng'
import factory from '../PipelineSteps/PipelineStepFactory'
import { StepType } from '../PipelineSteps/PipelineStepInterface'
// eslint-disable-next-line no-restricted-imports
import '@cd/components/PipelineSteps'
// eslint-disable-next-line no-restricted-imports
import '@ci/components/PipelineSteps'
// eslint-disable-next-line no-restricted-imports
import '@sto-steps/components/PipelineSteps'
import { StepViewType } from '../AbstractSteps/Step'
 
export const clearRuntimeInput = (template: PipelineInfoConfig): PipelineInfoConfig => {
  return JSON.parse(
    JSON.stringify(template || {}).replace(/"<\+input>.?(?:allowedValues\((.*?)\)|regex\((.*?)\))?"/g, '""')
  )
}
 
export function getStepFromStage(stepId: string, steps?: ExecutionWrapperConfig[]): ExecutionWrapperConfig | undefined {
  let responseStep: ExecutionWrapperConfig | undefined = undefined
  steps?.forEach(item => {
    if (item.step?.identifier === stepId) {
      responseStep = item
    } else Iif (item.stepGroup?.identifier === stepId) {
      responseStep = item
    } else Iif (item.parallel) {
      return item.parallel.forEach(node => {
        if (node.step?.identifier === stepId || node.stepGroup?.identifier === stepId) {
          responseStep = node
        }
      })
    }
  })
  return responseStep
}
 
export function getStageFromPipeline(
  stageId: string,
  pipeline?: PipelineInfoConfig
): StageElementWrapperConfig | undefined {
  Eif (pipeline?.stages) {
    let responseStage: StageElementWrapperConfig | undefined = undefined
    pipeline.stages.forEach(item => {
      if (item.stage && item.stage.identifier === stageId) {
        responseStage = item
      } else if (item.parallel) {
        return item.parallel.forEach(node => {
          if (node.stage?.identifier === stageId) {
            responseStage = node
          }
        })
      }
    })
    return responseStage
  }
  return
}
 
export interface ValidateStepProps {
  step: StepElementConfig | TemplateStepNode
  template?: StepElementConfig | TemplateStepNode
  originalStep?: ExecutionWrapperConfig
  getString?: UseStringsReturn['getString']
  viewType: StepViewType
}
 
export const validateStep = ({
  step,
  template,
  originalStep,
  getString,
  viewType
}: ValidateStepProps): FormikErrors<StepElementConfig> => {
  const errors = {}
  const isTemplateStep = !!(originalStep?.step as unknown as TemplateStepNode)?.template
  const stepType = isTemplateStep ? StepType.Template : (originalStep?.step as StepElementConfig)?.type
  const pipelineStep = factory.getStep(stepType)
  const errorResponse = pipelineStep?.validateInputSet({
    data: step,
    template: template,
    getString,
    viewType
  })
  Iif (!isEmpty(errorResponse)) {
    const suffix = isTemplateStep ? '.template.templateInputs' : ''
    set(errors, `step${suffix}`, errorResponse)
  }
  return errors
}
 
export interface ValidateStepsProps {
  steps: ExecutionWrapperConfig[]
  template?: ExecutionWrapperConfig[]
  originalSteps?: ExecutionWrapperConfig[]
  getString?: UseStringsReturn['getString']
  viewType: StepViewType
}
 
const validateSteps = ({
  steps,
  template,
  originalSteps,
  getString,
  viewType
}: ValidateStepsProps): FormikErrors<ExecutionWrapperConfig> => {
  const errors = {}
  steps.forEach((stepObj, index) => {
    Eif (stepObj.step) {
      const errorResponse = validateStep({
        step: stepObj.step,
        template: template?.[index].step,
        originalStep: getStepFromStage(stepObj.step.identifier, originalSteps),
        getString,
        viewType
      })
      Iif (!isEmpty(errorResponse)) {
        set(errors, `steps[${index}]`, errorResponse)
      }
    } else if (stepObj.parallel) {
      stepObj.parallel.forEach((stepParallel, indexP) => {
        if (stepParallel.step) {
          const errorResponse = validateStep({
            step: stepParallel.step,
            template: template?.[index]?.parallel?.[indexP]?.step,
            originalStep: getStepFromStage(stepParallel.step.identifier, originalSteps),
            getString,
            viewType
          })
          if (!isEmpty(errorResponse)) {
            set(errors, `steps[${index}].parallel[${indexP}]`, errorResponse)
          }
        }
      })
    } else if (stepObj.stepGroup) {
      const originalStepGroup = getStepFromStage(stepObj.stepGroup.identifier, originalSteps)
      if (stepObj.stepGroup.steps) {
        const errorResponse = validateSteps({
          steps: stepObj.stepGroup.steps,
          template: template?.[index]?.stepGroup?.steps,
          originalSteps: originalStepGroup?.stepGroup?.steps,
          getString,
          viewType
        })
        if (!isEmpty(errorResponse)) {
          set(errors, `steps[${index}].stepGroup.steps`, errorResponse)
        }
      }
    }
  })
 
  return errors
}
 
interface ValidateStageProps {
  stage: StageElementConfig
  template?: StageElementConfig
  viewType: StepViewType
  originalStage?: StageElementConfig
  getString?: UseStringsReturn['getString']
}
 
export const validateStage = ({
  stage,
  template,
  viewType,
  originalStage,
  getString
}: ValidateStageProps): FormikErrors<StageElementConfig> => {
  Iif (originalStage?.template) {
    const errors = validateStage({
      stage: stage.template?.templateInputs as StageElementConfig,
      template: template?.template?.templateInputs as StageElementConfig,
      viewType,
      originalStage: originalStage.template.templateInputs as StageElementConfig,
      getString
    })
    if (!isEmpty(errors)) {
      return set({}, 'template.templateInputs', errors)
    } else {
      return {}
    }
  } else {
    const errors = {}
 
    // Validation for infrastructure namespace
    // For CD spec is DeploymentStageConfig
    const stageConfig = stage.spec as DeploymentStageConfig | undefined
    const templateStageConfig = template?.spec as DeploymentStageConfig | undefined
    const originalStageConfig = originalStage?.spec as DeploymentStageConfig | undefined
    Iif (
      isEmpty((stageConfig?.infrastructure as Infrastructure)?.spec?.namespace) &&
      getMultiTypeFromValue((templateStageConfig?.infrastructure as Infrastructure)?.spec?.namespace) ===
        MultiTypeInputType.RUNTIME
    ) {
      set(
        errors,
        'spec.infrastructure.spec.namespace',
        getString?.('fieldRequired', { field: getString?.('pipelineSteps.build.infraSpecifications.namespace') })
      )
    }
 
    if (stage.type === 'Deployment' && templateStageConfig?.serviceConfig?.serviceRef) {
      const step = factory.getStep(StepType.DeployService)
      const errorsResponse = step?.validateInputSet({
        data: stageConfig?.serviceConfig,
        template: templateStageConfig?.serviceConfig,
        getString,
        viewType
      })
      Iif (!isEmpty(errorsResponse)) {
        set(errors, 'spec.serviceConfig', errorsResponse)
      }
    }
 
    if (stage.type === 'Deployment' && templateStageConfig?.infrastructure?.environmentRef) {
      const step = factory.getStep(StepType.DeployEnvironment)
      const errorsResponse = step?.validateInputSet({
        data: stageConfig?.infrastructure,
        template: templateStageConfig?.infrastructure,
        getString,
        viewType
      })
      Iif (!isEmpty(errorsResponse)) {
        set(errors, 'spec.infrastructure', errorsResponse)
      }
    }
    if (
      stageConfig?.infrastructure?.infrastructureDefinition?.spec &&
      originalStageConfig?.infrastructure?.infrastructureDefinition?.type
    ) {
      const step = factory.getStep(originalStageConfig.infrastructure.infrastructureDefinition.type)
      const errorsResponse = step?.validateInputSet({
        data: stageConfig?.infrastructure?.infrastructureDefinition?.spec,
        template: templateStageConfig?.infrastructure?.infrastructureDefinition?.spec,
        getString,
        viewType
      })
      Iif (!isEmpty(errorsResponse)) {
        set(errors, 'spec.infrastructure.infrastructureDefinition.spec', errorsResponse)
      }
    }
    Iif (stage?.variables) {
      const step = factory.getStep(StepType.CustomVariable)
      const errorsResponse: any = step?.validateInputSet({ data: stage, template, getString, viewType })
 
      if (!isEmpty(errorsResponse)) {
        set(errors, 'variables', errorsResponse?.variables)
      }
    }
    if (originalStageConfig?.serviceConfig?.serviceDefinition?.type === 'Kubernetes') {
      const step = factory.getStep(StepType.K8sServiceSpec)
      const errorsResponse = step?.validateInputSet({
        data: stageConfig?.serviceConfig?.serviceDefinition?.spec,
        template: templateStageConfig?.serviceConfig?.serviceDefinition?.spec,
        getString,
        viewType
      })
 
      if (!isEmpty(errorsResponse)) {
        set(errors, 'spec.serviceConfig.serviceDefinition.spec', errorsResponse)
      }
 
      if (originalStageConfig?.serviceConfig?.serviceDefinition?.spec?.variables) {
        const currentStep = factory.getStep(StepType.CustomVariable)
        const stepErrorsResponse = currentStep?.validateInputSet({
          data: stageConfig?.serviceConfig?.serviceDefinition?.spec,
          template: templateStageConfig?.serviceConfig?.serviceDefinition?.spec,
          getString,
          viewType
        })
 
        Iif (!isEmpty(stepErrorsResponse)) {
          set(errors, 'spec.serviceConfig.serviceDefinition.spec', stepErrorsResponse)
        }
      }
    }
 
    if (stageConfig?.execution?.steps) {
      const errorsResponse = validateSteps({
        steps: stageConfig.execution.steps as ExecutionWrapperConfig[],
        template: templateStageConfig?.execution?.steps,
        originalSteps: originalStageConfig?.execution?.steps,
        getString,
        viewType
      })
      Iif (!isEmpty(errorsResponse)) {
        set(errors, 'spec.execution', errorsResponse)
      }
    }
    if (stageConfig?.execution?.rollbackSteps) {
      const errorsResponse = validateSteps({
        steps: stageConfig.execution.rollbackSteps as ExecutionWrapperConfig[],
        template: templateStageConfig?.execution?.rollbackSteps,
        originalSteps: originalStageConfig?.execution?.rollbackSteps,
        getString,
        viewType
      })
      Iif (!isEmpty(errorsResponse)) {
        set(errors, 'spec.execution.rollbackSteps', errorsResponse)
      }
    }
 
    return errors
  }
}
 
interface ValidatePipelineProps {
  pipeline: PipelineInfoConfig
  template: PipelineInfoConfig
  viewType: StepViewType
  originalPipeline?: PipelineInfoConfig
  getString?: UseStringsReturn['getString']
  path?: string
}
 
/**
 * Validation for CI Codebase
 */
export const validateCICodebase = ({
  pipeline,
  template,
  originalPipeline,
  getString
}: ValidatePipelineProps): FormikErrors<PipelineInfoConfig> => {
  const errors = {}
  const shouldValidateCICodebase = originalPipeline?.stages?.some(stage =>
    Object.is(get(stage, 'stage.spec.cloneCodebase'), true)
  )
 
  Iif (
    shouldValidateCICodebase &&
    has(originalPipeline, 'properties') &&
    has(originalPipeline?.properties, 'ci') &&
    isEmpty(get(originalPipeline, 'properties.ci.codebase.build')) &&
    getString
  ) {
    set(errors, 'properties.ci.codebase', getString('fieldRequired', { field: getString('ciCodebase') }))
  }
 
  if (
    shouldValidateCICodebase &&
    getMultiTypeFromValue((template as PipelineInfoConfig)?.properties?.ci?.codebase?.build as unknown as string) ===
      MultiTypeInputType.RUNTIME
  ) {
    if (isEmpty(pipeline?.properties?.ci?.codebase?.build?.type)) {
      set(
        errors,
        'properties.ci.codebase.build.type',
        getString?.('fieldRequired', { field: getString?.('pipeline.ciCodebase.buildType') })
      )
    }
 
    if (
      pipeline?.properties?.ci?.codebase?.build?.type === 'branch' &&
      isEmpty(pipeline?.properties?.ci?.codebase?.build?.spec?.branch)
    ) {
      set(
        errors,
        'properties.ci.codebase.build.spec.branch',
        getString?.('fieldRequired', { field: getString?.('gitBranch') })
      )
    }
 
    if (
      pipeline?.properties?.ci?.codebase?.build?.type === 'tag' &&
      isEmpty(pipeline?.properties?.ci?.codebase?.build?.spec?.tag)
    ) {
      set(errors, 'properties.ci.codebase.build.spec.tag', getString?.('fieldRequired', { field: getString('gitTag') }))
    }
 
    Iif (
      pipeline?.properties?.ci?.codebase?.build?.type === 'PR' &&
      isEmpty(pipeline?.properties?.ci?.codebase?.build?.spec?.number)
    ) {
      set(
        errors,
        'properties.ci.codebase.build.spec.number',
        getString?.('fieldRequired', { field: getString?.('pipeline.gitPullRequestNumber') })
      )
    }
  }
  return errors
}
 
export const validatePipeline = ({
  pipeline,
  template,
  originalPipeline,
  viewType,
  getString,
  path
}: ValidatePipelineProps): FormikErrors<PipelineInfoConfig> => {
  Iif (template.template) {
    const errors = validatePipeline({
      pipeline: pipeline.template?.templateInputs as PipelineInfoConfig,
      template: template.template?.templateInputs as PipelineInfoConfig,
      viewType,
      originalPipeline: originalPipeline?.template?.templateInputs as PipelineInfoConfig,
      getString
    })
    if (!isEmpty(errors)) {
      return set({}, 'template.templateInputs', errors)
    } else {
      return {}
    }
  } else {
    const errors = validateCICodebase({
      pipeline,
      template,
      originalPipeline,
      viewType,
      getString,
      path
    })
 
    if (getMultiTypeFromValue(template?.timeout) === MultiTypeInputType.RUNTIME) {
      let timeoutSchema = getDurationValidationSchema({ minimum: '10s' })
      Eif (viewType === StepViewType.DeploymentForm) {
        timeoutSchema = timeoutSchema.required(getString?.('validation.timeout10SecMinimum'))
      }
      const timeout = Yup.object().shape({
        timeout: timeoutSchema
      })
 
      try {
        timeout.validateSync(pipeline)
      } catch (e) {
        /* istanbul ignore else */
        if (e instanceof Yup.ValidationError) {
          const err = yupToFormErrors(e)
 
          Object.assign(errors, err)
        }
      }
    }
 
    if (pipeline?.variables) {
      const step = factory.getStep(StepType.CustomVariable)
      const errorsResponse: any = step?.validateInputSet({ data: pipeline, template, getString, viewType })
 
      if (!isEmpty(errorsResponse)) {
        set(errors, 'variables', errorsResponse.variables)
      }
    }
    pipeline.stages?.forEach((stageObj, index) => {
      Eif (stageObj.stage) {
        const originalStage = getStageFromPipeline(stageObj.stage.identifier, originalPipeline)
        const errorsResponse = validateStage({
          stage: stageObj.stage as StageElementConfig,
          template: template?.stages?.[index]?.stage,
          originalStage: originalStage?.stage,
          getString,
          viewType
        })
        if (!isEmpty(errorsResponse)) {
          set(errors, `${isEmpty(path) ? '' : `${path}.`}stages[${index}].stage`, errorsResponse)
        }
      }
      Iif (stageObj.parallel) {
        stageObj.parallel.forEach((stageP, indexP: number) => {
          if (stageP.stage) {
            const originalStage = getStageFromPipeline(stageP.stage.identifier, originalPipeline)
            const errorsResponse = validateStage({
              stage: stageP.stage as StageElementConfig,
              template: template?.stages?.[index].parallel?.[indexP]?.stage,
              originalStage: originalStage?.stage,
              getString,
              viewType
            })
            if (!isEmpty(errorsResponse)) {
              set(
                errors,
                `${isEmpty(path) ? '' : `${path}.`}stages[${index}].parallel[${indexP}].stage`,
                errorsResponse
              )
            }
          }
        })
      }
    })
 
    return errors
  }
}
 
const getErrorsFlatten = memoize((errors: any): string[] => {
  return reduce(
    errors,
    (result: string[], value: any) => {
      if (typeof value === 'string') {
        result.push(value)
      } else Eif (isObject(value)) {
        return result.concat(getErrorsFlatten(value as any))
      }
 
      return result
    },
    []
  )
})
 
export const getErrorsList = memoize((errors: any): { errorStrings: string[]; errorCount: number } => {
  const errorList = getErrorsFlatten(errors)
  const errorCountMap: { [key: string]: number } = {}
  errorList.forEach(error => {
    Iif (errorCountMap[error]) {
      errorCountMap[error]++
    } else {
      errorCountMap[error] = 1
    }
  })
  const mapEntries = Object.entries(errorCountMap)
  const errorStrings = mapEntries.map(([key, count]) => `${key}  (${count})`)
  let errorCount = 0
  mapEntries.forEach(([_unused, count]) => {
    errorCount += count
  })
  return { errorStrings, errorCount }
})
 
export const validateCICodebaseConfiguration = ({ pipeline, getString }: Partial<ValidatePipelineProps>): string => {
  const shouldValidateCICodebase = pipeline?.stages?.some(
    stage =>
      Object.is(get(stage, 'stage.spec.cloneCodebase'), true) ||
      stage.parallel?.some(parallelStage => Object.is(get(parallelStage, 'stage.spec.cloneCodebase'), true))
  )
  Iif (
    shouldValidateCICodebase &&
    !has(pipeline, 'properties') &&
    !has(pipeline?.properties, 'ci') &&
    isEmpty(get(pipeline, 'properties.ci.codebase.build')) &&
    getString
  ) {
    return getString?.('pipeline.runPipeline.ciCodebaseConfig')
  }
  return ''
}