All files / modules/75-ci/components/PipelineStudio/BuildStageSpecifications BuildStageSpecifications.tsx

86% Statements 86/100
62.65% Branches 104/166
65% Functions 13/20
86.73% Lines 85/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              3x 3x 3x 3x 3x 3x 3x   3x 3x 3x 3x     3x         3x 3x 3x 3x 3x 3x 3x   3x 3x 3x 3x 3x   3x               3x 16x   16x                       16x   16x   16x   16x                 16x 16x   16x 16x 16x 16x 16x   16x               16x   16x                     16x   16x   16x 4x 4x     16x     2x 2x 1x   1x               16x 1x 1x 1x 1x   1x 1x   1x     1x     1x     1x     1x   1x           1x     1x     1x     1x     1x       1x 1x         16x   1x       16x               16x 4x 3x       16x   16x                       17x 17x 17x 17x                                             1x                                                                                                                                                                                                              
/*
 * 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, { useEffect } from 'react'
import * as yup from 'yup'
import { Accordion, Card, Formik, FormikForm, Switch, Text, MultiTypeInputType } from '@wings-software/uicore'
import { v4 as nameSpace, v5 as uuid } from 'uuid'
import { cloneDeep, debounce, defaultTo, isEqual, uniqBy } from 'lodash-es'
import cx from 'classnames'
import { produce } from 'immer'
import type { FormikProps } from 'formik'
import { NameIdDescriptionTags } from '@common/components/NameIdDescriptionTags/NameIdDescriptionTags'
import { StepViewType } from '@pipeline/components/AbstractSteps/Step'
import { StepType } from '@pipeline/components/PipelineSteps/PipelineStepInterface'
import { StepWidget } from '@pipeline/components/AbstractSteps/StepWidget'
import type { AllNGVariables } from '@pipeline/utils/types'
import type { NGVariable, StageElementConfig, StringNGVariable } from 'services/cd-ng'
import { usePipelineContext } from '@pipeline/components/PipelineStudio/PipelineContext/PipelineContext'
import type {
  CustomVariableEditableExtraProps,
  CustomVariablesData
} from '@pipeline/components/PipelineSteps/Steps/CustomVariables/CustomVariableEditable'
import { usePipelineVariables } from '@pipeline/components/PipelineVariablesContext/PipelineVariablesContext'
import { useStrings } from 'framework/strings'
import { loggerFor } from 'framework/logging/logging'
import { ModuleName } from 'framework/types/ModuleName'
import { NameSchema } from '@common/utils/Validation'
import MultiTypeList from '@common/components/MultiTypeList/MultiTypeList'
import { useVariablesExpression } from '@pipeline/components/PipelineStudio/PiplineHooks/useVariablesExpression'
import type { BuildStageElementConfig } from '@pipeline/utils/pipelineTypes'
import { StageErrorContext } from '@pipeline/context/StageErrorContext'
import ErrorsStripBinded from '@pipeline/components/ErrorsStrip/ErrorsStripBinded'
import { isContextTypeNotStageTemplate } from '@pipeline/components/PipelineStudio/PipelineUtils'
import { BuildTabs } from '../CIPipelineStagesUtils'
import css from './BuildStageSpecifications.module.scss'
 
const logger = loggerFor(ModuleName.CD)
 
export interface Variable {
  name: string
  type: string
  value?: string
}
 
export default function BuildStageSpecifications({ children }: React.PropsWithChildren<unknown>): JSX.Element {
  const { variablesPipeline, metadataMap } = usePipelineVariables()
 
  const { getString } = useStrings()
 
  const {
    state: {
      selectionState: { selectedStageId }
    },
    getStageFromPipeline,
    updateStage,
    stepsFactory,
    contextType,
    allowableTypes,
    isReadonly
  } = usePipelineContext()
 
  const scrollRef = React.useRef<HTMLDivElement | null>(null)
 
  const { stage } = getStageFromPipeline<BuildStageElementConfig>(selectedStageId || '')
 
  const getInitialValues = (): {
    identifier: string
    name: string
    description: string
    tags?: { [key: string]: string }
    cloneCodebase: boolean
    sharedPaths: string[]
    variables: NGVariable[]
  } => {
    const pipelineData = stage?.stage || null
    const spec = stage?.stage?.spec || null
 
    const identifier = pipelineData?.identifier || ''
    const name = pipelineData?.name || ''
    const description = pipelineData?.description || ''
    const tags = pipelineData?.tags
    const cloneCodebase = !!spec?.cloneCodebase
    const sharedPaths =
      typeof spec?.sharedPaths === 'string'
        ? spec?.sharedPaths
        : spec?.sharedPaths
            ?.filter((path: string) => !!path)
            ?.map((_value: string) => ({
              id: uuid('', nameSpace()),
              value: _value
            })) || []
    const variables = pipelineData?.variables || []
 
    return {
      identifier,
      name,
      description,
      tags,
      cloneCodebase,
      sharedPaths: sharedPaths as any,
      variables
    }
  }
 
  const { subscribeForm, unSubscribeForm } = React.useContext(StageErrorContext)
 
  const formikRef = React.useRef<FormikProps<unknown> | null>(null)
 
  React.useEffect(() => {
    subscribeForm({ tab: BuildTabs.OVERVIEW, form: formikRef })
    return () => unSubscribeForm({ tab: BuildTabs.OVERVIEW, form: formikRef })
  }, [])
 
  const validationSchema = yup.object().shape({
    ...(isContextTypeNotStageTemplate(contextType) && { name: NameSchema() }),
    sharedPaths: yup.lazy(value => {
      Eif (Array.isArray(value)) {
        return yup.array().test('valuesShouldBeUnique', getString('validation.uniqueValues'), list => {
          Iif (!list) return true
 
          return uniqBy(list, 'value').length === list.length
        })
      } else {
        return yup.string()
      }
    })
  })
 
  const handleValidate = (values: any): void => {
    Eif (stage?.stage) {
      const prevStageData = cloneDeep(stage.stage)
      const newStageData = produce(stage.stage, (stageData: any) => {
        const spec = stageData.spec
 
        stageData.identifier = values.identifier
        stageData.name = values.name
 
        Iif (values.description) {
          stageData.description = values.description
        } else {
          delete stageData.description
        }
 
        Iif (values.tags) {
          stageData.tags = values.tags
        } else {
          delete stageData.tags
        }
 
        spec.cloneCodebase = values.cloneCodebase
 
        Iif (values.sharedPaths && values.sharedPaths.length > 0) {
          spec.sharedPaths =
            typeof values.sharedPaths === 'string'
              ? values.sharedPaths
              : values.sharedPaths.map((listValue: { id: string; value: string }) => listValue.value)
        } else {
          delete spec.sharedPaths
        }
 
        Iif (values.variables && values.variables.length > 0) {
          stageData.variables = values.variables
        } else {
          delete stageData.variables
        }
 
        Iif (values.skipCondition) {
          stageData.skipCondition = values.skipCondition
        } else {
          delete stageData.skipCondition
        }
      })
 
      Eif (!isEqual(prevStageData, newStageData)) {
        updateStage(newStageData as unknown as StageElementConfig)
      }
    }
  }
 
  const debounceHandleValidate = React.useRef(
    debounce((values: any) => {
      return handleValidate(values)
    }, 500)
  ).current
 
  const handleStepWidgetUpdate = React.useCallback(
    debounce((values: StageElementConfig): void => {
      updateStage({ ...stage?.stage, ...values })
    }, 300),
    [stage?.stage, updateStage]
  )
 
  // Cleanup debounce
  useEffect(() => {
    return () => {
      debounceHandleValidate.flush()
    }
  }, [])
 
  const { expressions } = useVariablesExpression()
 
  return (
    <div className={css.wrapper}>
      <ErrorsStripBinded domRef={scrollRef as React.MutableRefObject<HTMLElement | undefined>} />
      <div className={css.contentSection} ref={scrollRef}>
        <Formik
          initialValues={getInitialValues()}
          validationSchema={validationSchema}
          validate={debounceHandleValidate}
          formName="ciBuildStage"
          onSubmit={values => logger.info(JSON.stringify(values))}
        >
          {formik => {
            const { values: formValues, setFieldValue } = formik
            window.dispatchEvent(new CustomEvent('UPDATE_ERRORS_STRIP', { detail: BuildTabs.OVERVIEW }))
            formikRef.current = formik
            return (
              <>
                <div className={css.tabHeading} id="stageDetails">
                  {getString('stageDetails')}
                </div>
                <Card className={cx(css.sectionCard)} disabled={isReadonly}>
                  <FormikForm>
                    {isContextTypeNotStageTemplate(contextType) && (
                      <NameIdDescriptionTags
                        formikProps={formik}
                        identifierProps={{
                          isIdentifierEditable: false,
                          inputGroupProps: { disabled: isReadonly }
                        }}
                        descriptionProps={{ disabled: isReadonly }}
                        tagsProps={{ disabled: isReadonly }}
                      />
                    )}
 
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                      <Switch
                        checked={formValues.cloneCodebase}
                        label={getString('cloneCodebaseLabel')}
                        onChange={e => setFieldValue('cloneCodebase', e.currentTarget.checked)}
                        disabled={isReadonly}
                        tooltipProps={{ tooltipId: 'cloneCodebase' }}
                      />
                    </div>
                  </FormikForm>
                </Card>
 
                <div className={css.tabHeading} id="sharedPaths">
                  {getString('pipelineSteps.build.stageSpecifications.sharedPaths')}
                </div>
                <Card disabled={isReadonly} className={cx(css.sectionCard)}>
                  <FormikForm className={cx(css.fields, css.contentCard)}>
                    <MultiTypeList
                      name="sharedPaths"
                      multiTextInputProps={{
                        expressions,
                        allowableTypes: [MultiTypeInputType.FIXED, MultiTypeInputType.EXPRESSION]
                      }}
                      multiTypeFieldSelectorProps={{
                        label: (
                          <Text tooltipProps={{ dataTooltipId: 'stageSpecificationsSharedPaths' }}>
                            {getString('pipelineSteps.build.stageSpecifications.sharedPaths')}
                          </Text>
                        ),
                        allowedTypes: [
                          MultiTypeInputType.FIXED,
                          MultiTypeInputType.EXPRESSION,
                          MultiTypeInputType.RUNTIME
                        ]
                      }}
                      disabled={isReadonly}
                    />
                  </FormikForm>
                </Card>
 
                <Accordion className={css.accordionTitle} activeId="">
                  <Accordion.Panel
                    id="advanced"
                    addDomId={true}
                    summary={
                      <div
                        className={css.tabHeading}
                        id="advanced"
                        style={{ paddingLeft: 'var(--spacing-small)', marginBottom: 0 }}
                      >
                        {getString('advancedTitle')}
                      </div>
                    }
                    details={
                      <Card
                        className={(css.sectionCard, css.sectionCardVariables)}
                        id="variables"
                        style={{ width: '100%' }}
                      >
                        <div className={css.tabSubHeading}>{getString('pipeline.stageVariables')}</div>
                        <Text style={{ color: 'var(--grey-500)', lineHeight: '24px' }}>
                          {getString('workflowVariableInfo')}
                        </Text>
                        <div className={css.stageSection}>
                          <div className={css.stageDetails}>
                            <StepWidget<CustomVariablesData, CustomVariableEditableExtraProps>
                              factory={stepsFactory}
                              readonly={isReadonly}
                              initialValues={{
                                variables: ((stage?.stage as StageElementConfig)?.variables || []) as AllNGVariables[],
                                canAddVariable: true
                              }}
                              allowableTypes={allowableTypes}
                              type={StepType.CustomVariable}
                              stepViewType={StepViewType.StageVariable}
                              onUpdate={({ variables }: CustomVariablesData) => {
                                handleStepWidgetUpdate({ ...stage?.stage, variables } as StageElementConfig)
                              }}
                              customStepProps={{
                                formName: 'addEditStageCustomVariableForm',
                                yamlProperties: defaultTo(
                                  getStageFromPipeline<BuildStageElementConfig>(
                                    stage?.stage?.identifier || '',
                                    variablesPipeline
                                  )?.stage?.stage?.variables?.map?.(
                                    variable =>
                                      metadataMap[(variable as StringNGVariable).value || '']?.yamlProperties || {}
                                  ),
                                  []
                                )
                              }}
                            />
                          </div>
                        </div>
                      </Card>
                    }
                  />
                </Accordion>
              </>
            )
          }}
        </Formik>
        {children}
      </div>
    </div>
  )
}