All files / modules/75-cd/components/PipelineSteps/K8sApply K8sApplyStep.tsx

92.86% Statements 91/98
65.4% Branches 259/396
77.78% Functions 21/27
92.86% Lines 91/98

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              97x 97x                   97x 97x 97x 97x 97x 97x   97x                   97x 97x 97x 97x   97x       97x 97x   97x 97x 97x   97x 97x                                                                                       97x                               6x 5x 5x   5x   5x         1x                 1x     3x                 3x                     6x                       14x 14x 14x                                                                                           13x     22x           66x                     1x                   1x                                                                                                                             97x 2x 2x 2x                                                                                                                                     97x 1x                   97x 97x   107x 107x 107x                           8x 8x 2x                   6x 1x               5x     1x             3x                   1x   1x 1x 1x 1x 1x   1x       1x 1x     1x 1x   1x       1x 1x         1x 1x                 1x 1x     1x 1x   1x         1x     1x       5x               4x                   2x                 2x         107x 107x 107x 107x   107x                        
/*
 * Copyright 2021 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 {
  Button,
  ButtonVariation,
  Formik,
  FormInput,
  getMultiTypeFromValue,
  IconName,
  Layout,
  MultiTypeInputType
} from '@wings-software/uicore'
import cx from 'classnames'
import { FieldArray, FormikErrors, FormikProps, yupToFormErrors } from 'formik'
import * as Yup from 'yup'
import { v4 as uuid } from 'uuid'
import { defaultTo, isEmpty } from 'lodash-es'
import { getNameAndIdentifierSchema } from '@pipeline/components/PipelineSteps/Steps/StepsValidateUtils'
 
import {
  StepFormikFowardRef,
  setFormikRef,
  StepProps,
  StepViewType,
  ValidateInputSetProps
} from '@pipeline/components/AbstractSteps/Step'
import type { K8sApplyStepInfo, StepElementConfig } from 'services/cd-ng'
 
import type { VariableMergeServiceResponse } from 'services/pipeline-ng'
import { VariablesListTable } from '@pipeline/components/VariablesListTable/VariablesListTable'
import { FormMultiTypeCheckboxField } from '@common/components'
import { ConfigureOptions } from '@common/components/ConfigureOptions/ConfigureOptions'
import { useStrings } from 'framework/strings'
 
import {
  FormMultiTypeDurationField,
  getDurationValidationSchema
} from '@common/components/MultiTypeDuration/MultiTypeDuration'
import MultiTypeFieldSelector from '@common/components/MultiTypeFieldSelector/MultiTypeFieldSelector'
import { useVariablesExpression } from '@pipeline/components/PipelineStudio/PiplineHooks/useVariablesExpression'
 
import { StepType } from '@pipeline/components/PipelineSteps/PipelineStepInterface'
import { PipelineStep } from '@pipeline/components/PipelineSteps/PipelineStep'
import List from '@common/components/List/List'
import type { StringsMap } from 'stringTypes'
import stepCss from '@pipeline/components/PipelineSteps/Steps/Steps.module.scss'
import pipelineVariableCss from '@pipeline/components/PipelineStudio/PipelineVariables/PipelineVariables.module.scss'
 
export interface K8sApplyData extends StepElementConfig {
  spec: Omit<K8sApplyStepInfo, 'skipDryRun' | 'skipSteadyStateCheck'> & {
    skipDryRun: boolean
    skipSteadyStateCheck?: boolean
  }
}
 
export interface K8sApplyVariableStepProps {
  initialValues: K8sApplyData
  stageIdentifier: string
  onUpdate?(data: K8sApplyFormData): void
  metadataMap: Required<VariableMergeServiceResponse>['metadataMap']
  variablesData: K8sApplyData
}
 
interface FilePathConfig {
  value: string
  id: string
}
interface K8sApplyFormData extends StepElementConfig {
  spec: {
    skipDryRun: boolean
    skipSteadyStateCheck?: boolean
    filePaths?: FilePathConfig[] | string
  }
}
 
interface K8sApplyProps {
  initialValues: K8sApplyData
  onUpdate?: (data: K8sApplyData) => void
  onChange?: (data: K8sApplyData) => void
  allowableTypes: MultiTypeInputType[]
  stepViewType?: StepViewType
  isNewStep?: boolean
  isDisabled?: boolean
  inputSetData?: {
    template?: K8sApplyData
    path?: string
  }
  readonly?: boolean
}
 
const formatData = (data: K8sApplyFormData): K8sApplyData => {
  return {
    ...data,
    spec: {
      ...data?.spec,
      skipDryRun: data?.spec?.skipDryRun,
      skipSteadyStateCheck: data?.spec?.skipSteadyStateCheck,
      filePaths:
        getMultiTypeFromValue(data?.spec?.filePaths as string) === MultiTypeInputType.RUNTIME
          ? data?.spec?.filePaths
          : ((data?.spec?.filePaths || []) as FilePathConfig[])?.map((item: FilePathConfig) => item.value)
    }
  }
}
 
function K8sApplyDeployWidget(props: K8sApplyProps, formikRef: StepFormikFowardRef<K8sApplyData>): React.ReactElement {
  const { initialValues, onUpdate, isNewStep = true, isDisabled, allowableTypes, onChange, stepViewType } = props
  const { getString } = useStrings()
  const defaultValueToReset = [{ value: '', id: uuid() }]
 
  const { expressions } = useVariablesExpression()
 
  return (
    <>
      <Formik<K8sApplyFormData>
        enableReinitialize={true}
        onSubmit={(values: K8sApplyFormData) => {
          const formData = {
            ...values,
            spec: {
              ...values.spec,
              skipDryRun: defaultTo(values?.spec?.skipDryRun, false),
              skipSteadyStateCheck: defaultTo(values?.spec?.skipSteadyStateCheck, false),
              filePaths: values?.spec?.filePaths
            }
          }
          onUpdate?.(formData)
        }}
        validate={(values: K8sApplyFormData) => {
          const formData = {
            ...values,
            spec: {
              ...values.spec,
              skipDryRun: defaultTo(values?.spec?.skipDryRun, false),
              skipSteadyStateCheck: defaultTo(values?.spec?.skipSteadyStateCheck, false),
              filePaths: values?.spec?.filePaths
            }
          }
          onChange?.(formData)
        }}
        formName="k8Apply"
        initialValues={initialValues}
        validationSchema={Yup.object().shape({
          ...getNameAndIdentifierSchema(getString, stepViewType),
          timeout: getDurationValidationSchema({ minimum: '10s' }).required(
            getString('validation.timeout10SecMinimum')
          ),
          spec: Yup.object().shape({
            filePaths: Yup.lazy(value =>
              getMultiTypeFromValue(value as boolean) === MultiTypeInputType.FIXED
                ? Yup.array(
                    Yup.object().shape({
                      value: Yup.string().required(getString('cd.pathCannotBeEmpty'))
                    })
                  ).required(getString('cd.filePathRequired'))
                : Yup.string()
            )
          })
        })}
      >
        {(formik: FormikProps<K8sApplyFormData>) => {
          const { values, setFieldValue } = formik
          setFormikRef(formikRef, formik)
          return (
            <>
              {stepViewType === StepViewType.Template ? null : (
                <div className={cx(stepCss.formGroup, stepCss.lg)}>
                  <FormInput.InputWithIdentifier
                    inputLabel={getString('name')}
                    isIdentifierEditable={isNewStep}
                    inputGroupProps={{
                      placeholder: getString('pipeline.stepNamePlaceholder'),
                      disabled: isDisabled
                    }}
                  />
                </div>
              )}
              <div className={cx(stepCss.formGroup, stepCss.sm)}>
                <FormMultiTypeDurationField
                  name="timeout"
                  disabled={isDisabled}
                  label={getString('pipelineSteps.timeoutLabel')}
                  multiTypeDurationProps={{ enableConfigureOptions: false, disabled: isDisabled, allowableTypes }}
                />
                {getMultiTypeFromValue(values.timeout) === MultiTypeInputType.RUNTIME && (
                  <ConfigureOptions
                    value={values.timeout as string}
                    type="String"
                    variableName="timeout"
                    showRequiredField={false}
                    showDefaultField={false}
                    showAdvanced={true}
                    onChange={value => {
                      setFieldValue('timeout', value)
                    }}
                    isReadonly={isDisabled}
                  />
                )}
              </div>
              <div className={stepCss.divider} />
              <div className={stepCss.formGroup}>
                <MultiTypeFieldSelector
                  defaultValueToReset={defaultValueToReset}
                  name={'spec.filePaths'}
                  label={getString('common.git.filePath')}
                  allowedTypes={allowableTypes}
                >
                  <FieldArray
                    name="spec.filePaths"
                    render={arrayHelpers => (
                      <Layout.Vertical>
                        {(values?.spec?.filePaths as FilePathConfig[])?.map((path: FilePathConfig, index: number) => (
                          <Layout.Horizontal key={path.id}>
                            <FormInput.MultiTextInput
                              label=""
                              placeholder={getString('cd.filePathPlaceholder')}
                              name={`spec.filePaths[${index}].value`}
                              multiTextInputProps={{
                                allowableTypes: allowableTypes.filter(item => item !== MultiTypeInputType.RUNTIME),
                                expressions,
                                textProps: { disabled: isDisabled }
                              }}
                              disabled={isDisabled}
                              style={{ width: '430px' }}
                            />
 
                            <Button
                              variation={ButtonVariation.ICON}
                              icon="main-trash"
                              onClick={() => arrayHelpers.remove(index)}
                              disabled={isDisabled}
                            />
                          </Layout.Horizontal>
                        ))}
                        <span>
                          <Button
                            variation={ButtonVariation.PRIMARY}
                            text={getString('addFileText')}
                            onClick={() => {
                              arrayHelpers.push({ value: '', id: uuid() })
                            }}
                            disabled={isDisabled}
                          />
                        </span>
                      </Layout.Vertical>
                    )}
                  />
                </MultiTypeFieldSelector>
              </div>
 
              <div className={cx(stepCss.formGroup, stepCss.md)}>
                <FormMultiTypeCheckboxField
                  name="spec.skipDryRun"
                  label={getString('pipelineSteps.skipDryRun')}
                  disabled={isDisabled}
                  multiTypeTextbox={{ expressions, allowableTypes }}
                />
                {getMultiTypeFromValue(values.spec?.skipDryRun) === MultiTypeInputType.RUNTIME && (
                  <ConfigureOptions
                    value={(values.spec.skipDryRun || '') as string}
                    type="String"
                    variableName="spec.skipDryRun"
                    showRequiredField={false}
                    showDefaultField={false}
                    showAdvanced={true}
                    onChange={value => {
                      setFieldValue('spec.skipDryRun', value)
                    }}
                    isReadonly={isDisabled}
                  />
                )}
              </div>
              <div className={cx(stepCss.formGroup, stepCss.md)}>
                <FormMultiTypeCheckboxField
                  name="spec.skipSteadyStateCheck"
                  disabled={isDisabled}
                  label={getString('pipelineSteps.skipSteadyStateCheck')}
                  multiTypeTextbox={{ expressions, allowableTypes }}
                />
                {getMultiTypeFromValue(values.spec?.skipSteadyStateCheck) === MultiTypeInputType.RUNTIME && (
                  <ConfigureOptions
                    value={(values.spec.skipSteadyStateCheck || '') as string}
                    type="String"
                    variableName="spec.skipSteadyStateCheck"
                    showRequiredField={false}
                    showDefaultField={false}
                    showAdvanced={true}
                    onChange={value => {
                      setFieldValue('spec.skipSteadyStateCheck', value)
                    }}
                    isReadonly={isDisabled}
                  />
                )}
              </div>
            </>
          )
        }}
      </Formik>
    </>
  )
}
 
const K8sApplyInputStep: React.FC<K8sApplyProps> = ({ inputSetData, readonly, allowableTypes }) => {
  const { getString } = useStrings()
  const { expressions } = useVariablesExpression()
  return (
    <>
      {getMultiTypeFromValue(inputSetData?.template?.timeout) === MultiTypeInputType.RUNTIME && (
        <div className={cx(stepCss.formGroup, stepCss.sm)}>
          <FormMultiTypeDurationField
            multiTypeDurationProps={{
              enableConfigureOptions: false,
              allowableTypes,
              expressions,
              disabled: readonly
            }}
            className={stepCss.checkbox}
            label={getString('pipelineSteps.timeoutLabel')}
            name={`${isEmpty(inputSetData?.path) ? '' : `${inputSetData?.path}.`}timeout`}
            disabled={readonly}
          />
        </div>
      )}
 
      {getMultiTypeFromValue(inputSetData?.template?.spec?.filePaths) === MultiTypeInputType.RUNTIME && (
        <div className={cx(stepCss.formGroup, stepCss.md)}>
          <List
            label={getString('filePaths')}
            name={`${isEmpty(inputSetData?.path) ? '' : `${inputSetData?.path}.`}spec.filePaths`}
            disabled={readonly}
            expressions={expressions}
            style={{ marginBottom: 'var(--spacing-small)' }}
            isNameOfArrayType
          />
        </div>
      )}
      {getMultiTypeFromValue(inputSetData?.template?.spec?.skipDryRun) === MultiTypeInputType.RUNTIME && (
        <div className={cx(stepCss.formGroup, stepCss.md)}>
          <FormMultiTypeCheckboxField
            multiTypeTextbox={{
              expressions,
              allowableTypes,
              disabled: readonly
            }}
            disabled={readonly}
            name={`${isEmpty(inputSetData?.path) ? '' : `${inputSetData?.path}.`}spec.skipDryRun`}
            className={stepCss.checkbox}
            label={getString('pipelineSteps.skipDryRun')}
            setToFalseWhenEmpty={true}
          />
        </div>
      )}
      {getMultiTypeFromValue(inputSetData?.template?.spec?.skipSteadyStateCheck) === MultiTypeInputType.RUNTIME && (
        <div className={cx(stepCss.formGroup, stepCss.md)}>
          <FormMultiTypeCheckboxField
            multiTypeTextbox={{
              expressions,
              allowableTypes,
              disabled: readonly
            }}
            disabled={readonly}
            name={`${isEmpty(inputSetData?.path) ? '' : `${inputSetData?.path}.`}spec.skipSteadyStateCheck`}
            className={stepCss.checkbox}
            label={getString('pipelineSteps.skipSteadyStateCheck')}
            setToFalseWhenEmpty={true}
          />
        </div>
      )}
    </>
  )
}
 
const K8sApplyVariableStep: React.FC<K8sApplyVariableStepProps> = ({ variablesData, metadataMap, initialValues }) => {
  return (
    <VariablesListTable
      className={pipelineVariableCss.variablePaddingL3}
      data={variablesData.spec}
      originalData={initialValues.spec}
      metadataMap={metadataMap}
    />
  )
}
 
const K8sApplyDeployWidgetWithRef = React.forwardRef(K8sApplyDeployWidget)
export class K8sApplyStep extends PipelineStep<K8sApplyData> {
  constructor() {
    super()
    this._hasStepVariables = true
    this._hasDelegateSelectionVisible = true
  }
  renderStep(props: StepProps<K8sApplyData>): JSX.Element {
    const {
      initialValues,
      onUpdate,
      stepViewType,
      inputSetData,
      formikRef,
      customStepProps,
      isNewStep,
      readonly,
      allowableTypes,
      onChange
    } = props
    if (stepViewType === StepViewType.InputSet || stepViewType === StepViewType.DeploymentForm) {
      return (
        <K8sApplyInputStep
          initialValues={initialValues}
          onUpdate={onUpdate}
          stepViewType={defaultTo(stepViewType, StepViewType.Edit)}
          inputSetData={inputSetData}
          readonly={!!inputSetData?.readonly}
          allowableTypes={allowableTypes}
        />
      )
    } else if (stepViewType === StepViewType.InputVariable) {
      return (
        <K8sApplyVariableStep
          {...(customStepProps as K8sApplyVariableStepProps)}
          initialValues={initialValues}
          onUpdate={data => onUpdate?.(formatData(data))}
        />
      )
    }
    return (
      <K8sApplyDeployWidgetWithRef
        initialValues={this.getInitialValues(initialValues)}
        onUpdate={data => onUpdate?.(this.processFormData(data))}
        isNewStep={isNewStep}
        stepViewType={stepViewType}
        readonly={!!inputSetData?.readonly}
        isDisabled={readonly}
        ref={formikRef}
        allowableTypes={allowableTypes}
        onChange={data => onChange?.(this.processFormData(data))}
      />
    )
  }
  validateInputSet({
    data,
    template,
    getString,
    viewType
  }: ValidateInputSetProps<K8sApplyData>): FormikErrors<K8sApplyData> {
    const isRequired = viewType === StepViewType.DeploymentForm || viewType === StepViewType.TriggerForm
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const errors = {} as any
    Eif (getMultiTypeFromValue(template?.timeout) === MultiTypeInputType.RUNTIME) {
      let timeoutSchema = getDurationValidationSchema({ minimum: '10s' })
      Eif (isRequired) {
        timeoutSchema = timeoutSchema.required(getString?.('validation.timeout10SecMinimum'))
      }
      const timeout = Yup.object().shape({
        timeout: timeoutSchema
      })
 
      try {
        timeout.validateSync(data)
      } catch (e) {
        /* istanbul ignore else */
        if (e instanceof Yup.ValidationError) {
          const err = yupToFormErrors(e)
 
          Object.assign(errors, err)
        }
      }
    }
    Eif (getMultiTypeFromValue(template?.spec?.filePaths) === MultiTypeInputType.RUNTIME) {
      let filePathSchema = Yup.object().shape({
        spec: Yup.object().shape({
          filePaths: Yup.array(Yup.string().trim()).ensure().nullable()
        })
      })
      Eif (isRequired) {
        filePathSchema = Yup.object().shape({
          spec: Yup.object().shape({
            filePaths: Yup.array(Yup.string().trim().required(getString?.('cd.pathCannotBeEmpty')))
              .required(getString?.('cd.filePathRequired'))
              .min(1, getString?.('cd.filePathRequired'))
              .ensure()
          })
        })
      }
      try {
        filePathSchema.validateSync(data)
      } catch (e) {
        /* istanbul ignore else */
        if (e instanceof Yup.ValidationError) {
          const err = yupToFormErrors(e)
 
          Object.assign(errors, err)
        }
      }
    }
    /* istanbul ignore else */
    Iif (isEmpty(errors.spec)) {
      delete errors.spec
    }
    return errors
  }
 
  private getInitialValues(initialValues: any): K8sApplyFormData {
    return {
      ...initialValues,
      spec: {
        ...initialValues.spec,
        filePaths:
          getMultiTypeFromValue(initialValues?.spec?.filePaths) === MultiTypeInputType.RUNTIME
            ? initialValues?.spec?.filePaths
            : initialValues?.spec?.filePaths?.length
            ? (initialValues?.spec?.filePaths || [])?.map((item: string) => ({
                value: item,
                id: uuid()
              }))
            : [{ value: '', id: uuid() }]
      }
    }
  }
 
  processFormData(data: any): K8sApplyData {
    return {
      ...data,
      spec: {
        ...data.spec,
        skipDryRun: data?.spec?.skipDryRun,
        skipSteadyStateCheck: data?.spec?.skipSteadyStateCheck,
        filePaths:
          getMultiTypeFromValue(data?.spec?.filePaths) === MultiTypeInputType.RUNTIME
            ? data?.spec?.filePaths
            : (data?.spec?.filePaths || [])?.map((item: FilePathConfig) => item.value)
      }
    }
  }
 
  protected type = StepType.K8sApply
  protected stepName = 'K8s Apply'
  protected stepIcon: IconName = 'code'
  protected stepDescription: keyof StringsMap = 'pipeline.stepDescription.K8sApply'
 
  protected defaultValues: K8sApplyData = {
    identifier: '',
    timeout: '10m',
    name: '',
    type: StepType.K8sApply,
    spec: {
      filePaths: [],
      skipDryRun: false,
      skipSteadyStateCheck: false
    }
  }
}