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

64.71% Statements 44/68
29.73% Branches 11/37
26.67% Functions 4/15
65.67% Lines 44/67

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              13x 13x 13x 13x           13x             13x 13x 13x 13x   13x         13x 13x 13x 13x 13x     13x                   13x               5x 5x 5x 5x 5x 5x 5x 5x 5x     5x         3x         5x                             5x                           5x                                               5x       5x       5x 3x 3x                 3x                                   3x     5x                       5x               5x   5x 3x     5x                                                                            
/*
 * 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 { cloneDeep, isEqual, noop } from 'lodash-es'
import { MultiTypeInputType, VisualYamlSelectedView as SelectedView } from '@wings-software/uicore'
import {
  findAllByKey,
  getTemplateTypesByRef,
  PipelineContext,
  PipelineContextType
} from '@pipeline/components/PipelineStudio/PipelineContext/PipelineContext'
import {
  initialState,
  PipelineContextActions,
  PipelineReducer,
  PipelineViewData,
  TemplateViewData
} from '@pipeline/components/PipelineStudio/PipelineContext/PipelineActions'
import { useLocalStorage } from '@common/hooks'
import factory from '@pipeline/components/PipelineSteps/PipelineStepFactory'
import { stagesCollection } from '@pipeline/components/PipelineStudio/Stages/StagesCollection'
import { useStrings } from 'framework/strings'
import type { PipelineStageWrapper } from '@pipeline/utils/pipelineTypes'
import {
  getStageFromPipeline as _getStageFromPipeline,
  getStagePathFromPipeline as _getStagePathFromPipeline
} from '@pipeline/components/PipelineStudio/PipelineContext/helpers'
import type { PipelineInfoConfig, StageElementConfig, StageElementWrapperConfig } from 'services/cd-ng'
import { PipelineStages, PipelineStagesProps } from '@pipeline/components/PipelineStages/PipelineStages'
import { StageType } from '@pipeline/utils/stageHelpers'
import { useFeatureFlag } from '@common/hooks/useFeatureFlag'
import { FeatureFlag } from '@common/featureFlags'
import { useLicenseStore } from 'framework/LicenseStore/LicenseStoreContext'
import type { PipelineSelectionState } from '@pipeline/components/PipelineStudio/PipelineQueryParamState/usePipelineQueryParam'
import type { GetPipelineQueryParams } from 'services/pipeline-ng'
import { getScopeFromDTO } from '@common/components/EntityReference/EntityReference'
 
export interface TemplatePipelineProviderProps {
  queryParams: GetPipelineQueryParams
  initialValue: PipelineInfoConfig
  onUpdatePipeline: (pipeline: PipelineInfoConfig) => void
  contextType: PipelineContextType
  isReadOnly: boolean
}
 
export function TemplatePipelineProvider({
  queryParams,
  initialValue,
  onUpdatePipeline,
  isReadOnly,
  contextType,
  children
}: React.PropsWithChildren<TemplatePipelineProviderProps>): React.ReactElement {
  const allowableTypes = [MultiTypeInputType.FIXED, MultiTypeInputType.RUNTIME, MultiTypeInputType.EXPRESSION]
  const { licenseInformation } = useLicenseStore()
  const isCDEnabled = useFeatureFlag(FeatureFlag.CDNG_ENABLED) && !!licenseInformation['CD']
  const isCIEnabled = useFeatureFlag(FeatureFlag.CING_ENABLED) && !!licenseInformation['CI']
  const isSTOEnabled = useFeatureFlag(FeatureFlag.SECURITY_STAGE)
  const { getString } = useStrings()
  const [state, dispatch] = React.useReducer(PipelineReducer, initialState)
  const [view, setView] = useLocalStorage<SelectedView>('pipeline_studio_view', SelectedView.VISUAL)
  const setSchemaErrorView = React.useCallback(flag => {
    dispatch(PipelineContextActions.updateSchemaErrorsFlag({ schemaErrors: flag }))
  }, [])
  const getStageFromPipeline = React.useCallback(
    <T extends StageElementConfig = StageElementConfig>(
      stageId: string,
      pipeline?: PipelineInfoConfig
    ): PipelineStageWrapper<T> => {
      return _getStageFromPipeline(stageId, pipeline || state.pipeline)
    },
    [state.pipeline, state.pipeline?.stages]
  )
 
  const renderPipelineStage = (args: Omit<PipelineStagesProps, 'children'>) => {
    return (
      <PipelineStages {...args}>
        {stagesCollection.getStage(StageType.BUILD, isCIEnabled, getString)}
        {stagesCollection.getStage(StageType.DEPLOY, isCDEnabled, getString)}
        {stagesCollection.getStage(StageType.APPROVAL, true, getString)}
        {stagesCollection.getStage(StageType.FEATURE, false, getString)}
        {stagesCollection.getStage(StageType.SECURITY, isSTOEnabled, getString)}
        {stagesCollection.getStage(StageType.PIPELINE, false, getString)}
        {stagesCollection.getStage(StageType.CUSTOM, false, getString)}
        {stagesCollection.getStage(StageType.Template, false, getString)}
      </PipelineStages>
    )
  }
 
  const updatePipeline = async (pipelineArg: PipelineInfoConfig | ((p: PipelineInfoConfig) => PipelineInfoConfig)) => {
    let pipeline = pipelineArg
    if (typeof pipelineArg === 'function') {
      if (state.pipeline) {
        pipeline = pipelineArg(state.pipeline)
      } else {
        pipeline = {} as PipelineInfoConfig
      }
    }
    const isUpdated = !isEqual(state.originalPipeline, pipeline)
    await dispatch(PipelineContextActions.success({ error: '', pipeline: pipeline as PipelineInfoConfig, isUpdated }))
    onUpdatePipeline?.(pipeline as PipelineInfoConfig)
  }
 
  const updateStage = React.useCallback(
    async (newStage: StageElementConfig) => {
      function _updateStages(stages: StageElementWrapperConfig[]): StageElementWrapperConfig[] {
        return stages.map(node => {
          if (node.stage?.identifier === newStage.identifier) {
            return { stage: newStage }
          } else if (node.parallel) {
            return {
              parallel: _updateStages(node.parallel)
            }
          }
 
          return node
        })
      }
 
      return updatePipeline(originalPipeline => ({
        ...originalPipeline,
        stages: _updateStages(originalPipeline.stages || [])
      }))
    },
    [updatePipeline]
  )
 
  const updatePipelineView = React.useCallback((data: PipelineViewData) => {
    dispatch(PipelineContextActions.updatePipelineView({ pipelineView: data }))
  }, [])
 
  const updateTemplateView = React.useCallback((data: TemplateViewData) => {
    dispatch(PipelineContextActions.updateTemplateView({ templateView: data }))
  }, [])
 
  const fetchPipeline = async () => {
    const templateRefs = findAllByKey('templateRef', initialValue)
    dispatch(
      PipelineContextActions.success({
        error: '',
        pipeline: initialValue,
        originalPipeline: cloneDeep(initialValue),
        isBEPipelineUpdated: false,
        isUpdated: false
      })
    )
    Iif (templateRefs.length > 0) {
      dispatch(
        PipelineContextActions.setTemplateTypes({
          templateTypes: await getTemplateTypesByRef(
            {
              accountIdentifier: queryParams.accountIdentifier,
              orgIdentifier: queryParams.orgIdentifier,
              projectIdentifier: queryParams.projectIdentifier,
              templateListType: 'Stable',
              repoIdentifier: queryParams.repoIdentifier,
              branch: queryParams.branch,
              getDefaultFromOtherRepo: true
            },
            templateRefs
          )
        })
      )
    }
    dispatch(PipelineContextActions.initialized())
  }
 
  const setSelection = (selectedState: PipelineSelectionState) => {
    dispatch(
      PipelineContextActions.updateSelectionState({
        selectionState: {
          selectedStageId: selectedState.stageId as string,
          selectedStepId: selectedState.stepId as string,
          selectedSectionId: selectedState.sectionId as string
        }
      })
    )
  }
 
  const getStagePathFromPipeline = React.useCallback(
    (stageId: string, prefix = '', pipeline?: PipelineInfoConfig) => {
      const localPipeline = pipeline || state.pipeline
      return _getStagePathFromPipeline(stageId, prefix, localPipeline)
    }, // eslint-disable-next-line react-hooks/exhaustive-deps
    [state.pipeline, state.pipeline?.stages]
  )
 
  const scope = getScopeFromDTO(queryParams)
 
  React.useEffect(() => {
    fetchPipeline()
  }, [initialValue])
 
  return (
    <PipelineContext.Provider
      value={{
        state,
        view,
        contextType,
        allowableTypes,
        setView,
        scope,
        runPipeline: noop,
        stepsFactory: factory,
        setSchemaErrorView,
        stagesMap: stagesCollection.getAllStagesAttributes(getString),
        getStageFromPipeline,
        renderPipelineStage,
        fetchPipeline: Promise.resolve,
        updateGitDetails: Promise.resolve,
        updateEntityValidityDetails: Promise.resolve,
        updatePipeline,
        updateStage,
        updatePipelineView,
        updateTemplateView,
        pipelineSaved: noop,
        deletePipelineCache: Promise.resolve,
        isReadonly: isReadOnly,
        setYamlHandler: noop,
        setSelectedStageId: noop,
        setSelectedStepId: noop,
        setSelectedSectionId: noop,
        setSelection,
        getStagePathFromPipeline,
        setTemplateTypes: noop
      }}
    >
      {children}
    </PipelineContext.Provider>
  )
}