All files / modules/70-pipeline/components/WorkflowVariablesSelection WorkflowVariables.tsx

51.32% Statements 39/76
39.29% Branches 77/196
33.33% Functions 4/12
51.32% Lines 39/76

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              99x 99x 99x 99x   99x 99x 99x 99x           99x       99x 99x 99x                           99x                                     33x 33x   33x 33x 33x 33x   33x 33x 11x               33x 33x 33x                                                 33x 33x     33x 33x     33x                                   33x 33x       33x 33x   33x     33x 33x     33x                                       33x                                                                          
/*
 * 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 { Layout, Text } from '@wings-software/uicore'
import { defaultTo, set, get, isEmpty } from 'lodash-es'
import { Color } from '@harness/design-system'
import type { AllNGVariables as Variable } from '@pipeline/utils/types'
import { usePipelineContext } from '@pipeline/components/PipelineStudio/PipelineContext/PipelineContext'
import { StepType } from '@pipeline/components/PipelineSteps/PipelineStepInterface'
import { PredefinedOverrideSets } from '@pipeline/components/PredefinedOverrideSets/PredefinedOverrideSets'
import { usePipelineVariables } from '@pipeline/components/PipelineVariablesContext/PipelineVariablesContext'
import type {
  CustomVariablesData,
  CustomVariableEditableExtraProps
} from '@pipeline/components/PipelineSteps/Steps/CustomVariables/CustomVariableEditable'
 
import { useStrings } from 'framework/strings'
import type { DeploymentStageElementConfig } from '@pipeline/utils/pipelineTypes'
import type { StageElementWrapperConfig } from 'services/cd-ng'
import type { AbstractStepFactory } from '../AbstractSteps/AbstractStepFactory'
import { getFlattenedStages, getStageIndexFromPipeline } from '../PipelineStudio/StageBuilder/StageBuilderUtil'
import { StepViewType } from '../AbstractSteps/Step'
import { StepWidget } from '../AbstractSteps/StepWidget'
 
export interface WorkflowVariablesProps {
  isForOverrideSets?: boolean
  identifierName?: string
  isForPredefinedSets?: boolean
  overrideSetIdentifier?: string
  isPropagating?: boolean
  tabName?: string
  formName?: string
  factory: AbstractStepFactory
  readonly?: boolean
}
 
export default function WorkflowVariables({
  isForOverrideSets = false,
  identifierName,
  isForPredefinedSets = false,
  overrideSetIdentifier = '',
  isPropagating = false,
  tabName,
  formName,
  factory,
  readonly
}: WorkflowVariablesProps): JSX.Element {
  const {
    state: {
      pipeline,
      selectionState: { selectedStageId }
    },
    allowableTypes,
    getStageFromPipeline,
    updatePipeline
  } = usePipelineContext()
  const { getString } = useStrings()
 
  const { stage } = getStageFromPipeline<DeploymentStageElementConfig>(selectedStageId || '')
  const serviceConfig = stage?.stage?.spec?.serviceConfig || {}
  const parentStage = serviceConfig.useFromStage?.stage
  const { variablesPipeline, metadataMap } = usePipelineVariables()
 
  const [parentStageData, setParentStageData] = React.useState<StageElementWrapperConfig>()
  React.useEffect(() => {
    Iif (isEmpty(parentStageData) && parentStage) {
      const { stages } = getFlattenedStages(pipeline)
      const { index } = getStageIndexFromPipeline(pipeline, parentStage)
      setParentStageData(stages[index])
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [serviceConfig.useFromStage?.stage, pipeline])
 
  const stageSpec = defaultTo(serviceConfig.serviceDefinition?.spec, {})
  const predefinedSetsPath = defaultTo(serviceConfig.stageOverrides, {})
  const updateVariables = (vars: Variable[]): void => {
    if (stageSpec || predefinedSetsPath) {
      if (isPropagating) {
        predefinedSetsPath.variables = [...vars]
        updatePipeline(pipeline)
        return
      }
      if (!isForOverrideSets) {
        if (isForPredefinedSets) {
          predefinedSetsPath.variables = vars
        } else {
          stageSpec.variables = vars
        }
      } else {
        const overrideSets = stageSpec.variableOverrideSets || []
        overrideSets.forEach(variableSet => {
          if (variableSet?.overrideSet?.identifier === identifierName) {
            set(variableSet, 'overrideSet.variables', vars)
          }
        })
      }
    }
    updatePipeline(pipeline)
  }
 
  const getInitialValues = (): Variable[] => {
    Iif (isPropagating) {
      return get(predefinedSetsPath, 'variables', []) as Variable[]
    }
    Eif (!isForOverrideSets) {
      Iif (isForPredefinedSets) {
        return (predefinedSetsPath?.variables || []) as Variable[]
      }
      return (stageSpec?.variables || []) as Variable[]
    }
    if (isForPredefinedSets) {
      return (predefinedSetsPath?.variables || []) as Variable[]
    }
    const overrideSets = stageSpec.variableOverrideSets
    return defaultTo(
      overrideSets
        ?.map(variableSet => {
          if (variableSet?.overrideSet?.identifier === identifierName) {
            return variableSet.overrideSet?.variables
          }
        })
        .filter(x => x !== undefined)[0],
      []
    ) as Variable[]
  }
 
  const getYamlPropertiesForVariables = (): Variable[] => {
    const { stage: variablesStage } = getStageFromPipeline<DeploymentStageElementConfig>(
      parentStage || selectedStageId || '',
      variablesPipeline
    )
    const variablesServiceConfig = variablesStage?.stage?.spec?.serviceConfig || {}
    const variablesStageSpec = variablesServiceConfig.serviceDefinition?.spec
 
    Iif (isPropagating) {
      return get(predefinedSetsPath, 'variables', []) as Variable[]
    }
    Eif (!isForOverrideSets) {
      Iif (isForPredefinedSets) {
        return (predefinedSetsPath?.variables || []) as Variable[]
      }
      return (variablesStageSpec?.variables || []) as Variable[]
    }
    if (isForPredefinedSets) {
      return (variablesServiceConfig?.stageOverrides?.variables || []) as Variable[]
    }
 
    const overrideSets = variablesStageSpec?.variableOverrideSets
 
    return defaultTo(
      overrideSets
        ?.map(variableSet => {
          if (variableSet?.overrideSet?.identifier === identifierName) {
            return variableSet.overrideSet?.variables
          }
        })
        .filter(x => x !== undefined)[0],
      []
    ) as Variable[]
  }
 
  return (
    <Layout.Vertical style={{ borderRadius: '5px' }}>
      {isForPredefinedSets && <PredefinedOverrideSets context="VARIABLES" currentStage={stage} />}
 
      <section>
        {overrideSetIdentifier?.length === 0 && !isForOverrideSets && (
          <Text color={Color.GREY_500} style={{ fontSize: '13px' }}>
            {getString('workflowVariableInfo')}
          </Text>
        )}
        <StepWidget<CustomVariablesData, CustomVariableEditableExtraProps>
          factory={factory}
          stepViewType={StepViewType.StageVariable}
          initialValues={{
            variables: getInitialValues(),
            isPropagating,
            canAddVariable: !overrideSetIdentifier?.length
          }}
          allowableTypes={allowableTypes}
          readonly={readonly}
          type={StepType.CustomVariable}
          onUpdate={({ variables }: { variables: Variable[] }) => {
            updateVariables(variables)
          }}
          customStepProps={{
            tabName,
            formName,
            yamlProperties: getYamlPropertiesForVariables().map(
              variable => metadataMap[variable.value || '']?.yamlProperties || {}
            ),
            enableValidation: true
          }}
        />
      </section>
    </Layout.Vertical>
  )
}