All files / modules/70-pipeline/components/PipelineInputSetForm PipelineInputSetForm.tsx

98.48% Statements 65/66
77.58% Branches 308/397
100% Functions 11/11
98.48% Lines 65/66

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              66x 66x 66x 66x 66x 66x             66x     66x 66x 66x 66x   66x 66x 66x 66x 66x 66x 66x           66x 66x 66x 66x 66x                             66x               66x                                 140x 140x                                                                                                       66x                                     140x 140x     140x                                                         66x                 275x 273x   273x 273x 273x           273x   247x 15x     273x   273x       137x 18x 119x 12x   107x     273x                                                                                                                                                                   124x 124x 116x   116x                       8x 7x 21x 21x                           1x             66x 275x 273x 273x 61x 30x         30x             273x    
/*
 * 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 { Layout, getMultiTypeFromValue, MultiTypeInputType, Text, Icon, IconName } from '@wings-software/uicore'
import { isEmpty, get, defaultTo } from 'lodash-es'
import { Color } from '@harness/design-system'
import cx from 'classnames'
import { useParams } from 'react-router-dom'
import type {
  DeploymentStageConfig,
  PipelineInfoConfig,
  StageElementConfig,
  StageElementWrapperConfig
} from 'services/cd-ng'
import { useStrings } from 'framework/strings'
import type { AllNGVariables } from '@pipeline/utils/types'
import type { StepViewType } from '@pipeline/components/AbstractSteps/Step'
import DelegateSelectorPanel from '@pipeline/components/PipelineSteps/AdvancedSteps/DelegateSelectorPanel/DelegateSelectorPanel'
import { FormMultiTypeDurationField } from '@common/components/MultiTypeDuration/MultiTypeDuration'
import { PubSubPipelineActions } from '@pipeline/factories/PubSubPipelineAction'
import { PipelineActions } from '@pipeline/factories/PubSubPipelineAction/types'
import type { AccountPathProps } from '@common/interfaces/RouteInterfaces'
import { useDeepCompareEffect } from '@common/hooks'
import { TEMPLATE_INPUT_PATH } from '@pipeline/utils/templateUtils'
import { StageInputSetForm } from './StageInputSetForm'
import { StageAdvancedInputSetForm } from './StageAdvancedInputSetForm'
import { CICodebaseInputSetForm } from './CICodebaseInputSetForm'
import { StepWidget } from '../AbstractSteps/StepWidget'
import factory from '../PipelineSteps/PipelineStepFactory'
import type {
  CustomVariablesData,
  CustomVariableInputSetExtraProps
} from '../PipelineSteps/Steps/CustomVariables/CustomVariableInputSet'
import type { AbstractStepFactory } from '../AbstractSteps/AbstractStepFactory'
import { StepType } from '../PipelineSteps/PipelineStepInterface'
import { getStageFromPipeline } from '../PipelineStudio/StepUtil'
import { useVariablesExpression } from '../PipelineStudio/PiplineHooks/useVariablesExpression'
import css from './PipelineInputSetForm.module.scss'
import stepCss from '@pipeline/components/PipelineSteps/Steps/Steps.module.scss'
 
export interface PipelineInputSetFormProps {
  originalPipeline: PipelineInfoConfig
  template: PipelineInfoConfig
  path?: string
  readonly?: boolean
  maybeContainerClass?: string
  viewType: StepViewType
  isRunPipelineForm?: boolean
  listOfSelectedStages?: string[]
  isRetryFormStageSelected?: boolean
  allowableTypes?: MultiTypeInputType[]
}
 
export const stageTypeToIconMap: Record<string, IconName> = {
  Deployment: 'cd-main',
  CI: 'ci-main',
  Pipeline: 'pipeline',
  Custom: 'pipeline-custom',
  Approval: 'approval-stage-icon'
}
 
export function StageFormInternal({
  allValues,
  path,
  template,
  readonly,
  viewType,
  stageClassName = '',
  allowableTypes
}: {
  allValues?: StageElementWrapperConfig
  template?: StageElementWrapperConfig
  path: string
  readonly?: boolean
  viewType: StepViewType
  stageClassName?: string
  allowableTypes: MultiTypeInputType[]
}): JSX.Element {
  const { getString } = useStrings()
  return (
    <div className={cx(css.topAccordion, stageClassName)}>
      {template?.stage?.variables && (
        <div id={`Stage.${allValues?.stage?.identifier}.Variables`} className={cx(css.accordionSummary)}>
          <Text font={{ weight: 'semi-bold' }} padding={{ top: 'medium', bottom: 'medium' }}>
            {getString('variablesText')}
          </Text>
          <div className={css.nestedAccordions}>
            <StepWidget<CustomVariablesData, CustomVariableInputSetExtraProps>
              factory={factory as unknown as AbstractStepFactory}
              initialValues={{
                variables: (allValues?.stage?.variables || []) as AllNGVariables[],
                canAddVariable: true
              }}
              allowableTypes={allowableTypes}
              type={StepType.CustomVariable}
              readonly={readonly}
              stepViewType={viewType}
              customStepProps={{
                template: { variables: template?.stage?.variables as AllNGVariables[] },
                path,
                allValues: { variables: (allValues?.stage?.variables || []) as AllNGVariables[] }
              }}
            />
          </div>
        </div>
      )}
      {template?.stage?.spec && (
        <StageInputSetForm
          stageIdentifier={allValues?.stage?.identifier}
          path={`${path}.spec`}
          deploymentStageTemplate={template?.stage?.spec as DeploymentStageConfig}
          deploymentStage={allValues?.stage?.spec as DeploymentStageConfig}
          readonly={readonly}
          viewType={viewType}
          allowableTypes={allowableTypes}
        />
      )}
      {(!isEmpty(template?.stage?.when) || !isEmpty(template?.stage?.delegateSelectors)) && (
        <StageAdvancedInputSetForm
          stageIdentifier={allValues?.stage?.identifier}
          path={path}
          deploymentStageTemplate={(template as StageElementWrapperConfig).stage}
          readonly={readonly}
          allowableTypes={allowableTypes}
          delegateSelectors={template?.stage?.delegateSelectors}
        />
      )}
    </div>
  )
}
 
export function StageForm({
  allValues,
  path,
  template,
  readonly,
  viewType,
  hideTitle = false,
  stageClassName = '',
  allowableTypes
}: {
  allValues?: StageElementWrapperConfig
  template?: StageElementWrapperConfig
  path: string
  readonly?: boolean
  viewType: StepViewType
  hideTitle?: boolean
  stageClassName?: string
  allowableTypes: MultiTypeInputType[]
}): JSX.Element {
  const isTemplateStage = !!template?.stage?.template
  const type = isTemplateStage
    ? (template?.stage?.template?.templateInputs as StageElementConfig)?.type
    : template?.stage?.type
  return (
    <div id={`Stage.${allValues?.stage?.identifier}`}>
      {!hideTitle && (
        <Layout.Horizontal spacing="small" padding={{ top: 'medium', left: 'large', right: 0, bottom: 0 }}>
          {type && <Icon name={stageTypeToIconMap[type]} size={18} />}
          <Text color={Color.BLACK_100} font={{ weight: 'semi-bold' }}>
            Stage: {defaultTo(allValues?.stage?.name, '')}
          </Text>
        </Layout.Horizontal>
      )}
      <StageFormInternal
        template={
          isTemplateStage ? { stage: template?.stage?.template?.templateInputs as StageElementConfig } : template
        }
        allValues={
          allValues?.stage?.template
            ? { stage: allValues?.stage?.template?.templateInputs as StageElementConfig }
            : allValues
        }
        path={isTemplateStage ? `${path}.${TEMPLATE_INPUT_PATH}` : path}
        readonly={readonly}
        viewType={viewType}
        allowableTypes={allowableTypes}
        stageClassName={stageClassName}
      />
    </div>
  )
}
 
export function PipelineInputSetFormInternal(props: PipelineInputSetFormProps): React.ReactElement {
  const {
    originalPipeline,
    template,
    path = '',
    readonly,
    viewType,
    maybeContainerClass = '',
    allowableTypes = [MultiTypeInputType.FIXED, MultiTypeInputType.EXPRESSION]
  } = props
  const { getString } = useStrings()
 
  const isTemplatePipeline = !!template.template
  const finalTemplate = isTemplatePipeline ? (template?.template?.templateInputs as PipelineInfoConfig) : template
  const finalPath = isTemplatePipeline
    ? !isEmpty(path)
      ? `${path}.template.templateInputs`
      : 'template.templateInputs'
    : path
 
  const isCloneCodebaseEnabledAtLeastAtOneStage = originalPipeline?.stages?.some(
    stage =>
      Object.is(get(stage, 'stage.spec.cloneCodebase'), true) ||
      stage.parallel?.some(parallelStage => Object.is(get(parallelStage, 'stage.spec.cloneCodebase'), true))
  )
 
  const { expressions } = useVariablesExpression()
 
  const isInputStageDisabled = (stageId: string): boolean => {
    /* In retry pipeline form all the fields are disabled until any stage is selected,
      and once the stage is selected, the stage before the selected stage should be disabled */
 
    if (props.isRetryFormStageSelected) {
      return !!props.listOfSelectedStages?.includes(stageId)
    } else if (props.isRetryFormStageSelected === false) {
      return !props.listOfSelectedStages?.length
    }
    return readonly as boolean
  }
 
  return (
    <Layout.Vertical spacing="medium" className={cx(css.container, maybeContainerClass)}>
      {getMultiTypeFromValue(finalTemplate?.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(finalPath) ? `${finalPath}.timeout` : 'timeout'}
            disabled={readonly}
          />
        </div>
      ) : null}
      {getMultiTypeFromValue(finalTemplate?.delegateSelectors) === MultiTypeInputType.RUNTIME ? (
        <div className={cx(stepCss.formGroup, stepCss.sm, stepCss.delegate)}>
          <DelegateSelectorPanel isReadonly={readonly || false} allowableTypes={allowableTypes} />
        </div>
      ) : null}
      {finalTemplate?.variables && finalTemplate?.variables?.length > 0 && (
        <>
          <Layout.Horizontal spacing="small" padding={{ top: 'medium', left: 'large', right: 0, bottom: 0 }}>
            <Text
              color={Color.BLACK_100}
              font={{ weight: 'semi-bold' }}
              icon={'pipeline-variables'}
              iconProps={{ size: 18, color: Color.PRIMARY_7 }}
            >
              {getString('customVariables.pipelineVariablesTitle')}
            </Text>
          </Layout.Horizontal>
          <StepWidget<CustomVariablesData, CustomVariableInputSetExtraProps>
            factory={factory as unknown as AbstractStepFactory}
            initialValues={{
              variables: (originalPipeline.variables || []) as AllNGVariables[],
              canAddVariable: true
            }}
            allowableTypes={allowableTypes}
            readonly={readonly}
            type={StepType.CustomVariable}
            stepViewType={viewType}
            customStepProps={{
              template: { variables: (finalTemplate?.variables || []) as AllNGVariables[] },
              path: finalPath,
              allValues: { variables: (originalPipeline?.variables || []) as AllNGVariables[] }
            }}
          />
        </>
      )}
      {isCloneCodebaseEnabledAtLeastAtOneStage &&
        getMultiTypeFromValue(finalTemplate?.properties?.ci?.codebase?.build as unknown as string) ===
          MultiTypeInputType.RUNTIME && (
          <>
            <Layout.Horizontal spacing="small" padding={{ top: 'medium', left: 'large', right: 0, bottom: 0 }}>
              <Text
                data-name="ci-codebase-title"
                color={Color.BLACK_100}
                font={{ weight: 'semi-bold' }}
                tooltipProps={{ dataTooltipId: 'ciCodebase' }}
              >
                {getString('ciCodebase')}
              </Text>
            </Layout.Horizontal>
            <div className={css.topAccordion}>
              <div className={css.accordionSummary}>
                <div className={css.nestedAccordions}>
                  <CICodebaseInputSetForm
                    path={finalPath}
                    readonly={readonly}
                    originalPipeline={props.originalPipeline}
                  />
                </div>
              </div>
            </div>
          </>
        )}
      <>
        {finalTemplate?.stages?.map((stageObj, index) => {
          const pathPrefix = !isEmpty(finalPath) ? `${finalPath}.` : ''
          if (stageObj.stage) {
            const allValues = getStageFromPipeline(stageObj?.stage?.identifier || '', originalPipeline)
 
            return (
              <Layout.Vertical key={stageObj?.stage?.identifier || index}>
                <StageForm
                  template={stageObj}
                  allValues={allValues}
                  path={`${pathPrefix}stages[${index}].stage`}
                  readonly={isInputStageDisabled(stageObj?.stage?.identifier)}
                  viewType={viewType}
                  allowableTypes={allowableTypes}
                />
              </Layout.Vertical>
            )
          } else if (stageObj.parallel) {
            return stageObj.parallel.map((stageP, indexp) => {
              const allValues = getStageFromPipeline(stageP?.stage?.identifier || '', originalPipeline)
              return (
                <Layout.Vertical key={`${stageObj?.stage?.identifier}-${stageP.stage?.identifier}-${indexp}`}>
                  <StageForm
                    template={stageP}
                    allValues={allValues}
                    path={`${pathPrefix}stages[${index}].parallel[${indexp}].stage`}
                    readonly={isInputStageDisabled(stageP?.stage?.identifier as string)}
                    viewType={viewType}
                    allowableTypes={allowableTypes}
                  />
                </Layout.Vertical>
              )
            })
          } else {
            return null
          }
        })}
      </>
    </Layout.Vertical>
  )
}
export function PipelineInputSetForm(props: PipelineInputSetFormProps): React.ReactElement {
  const [template, setTemplate] = React.useState(props.template)
  const accountPathProps = useParams<AccountPathProps>()
  useDeepCompareEffect(() => {
    if (props.isRunPipelineForm) {
      PubSubPipelineActions.publish(PipelineActions.RunPipeline, {
        pipeline: props.originalPipeline,
        accountPathProps,
        template: props.template
      }).then(data => {
        Iif (data.length > 0) {
          setTemplate(Object.assign(props.template, ...data))
        }
      })
    }
  }, [props?.template])
 
  return <PipelineInputSetFormInternal {...props} template={template} />
}