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

68.75% Statements 88/128
56.32% Branches 107/190
60.87% Functions 14/23
68.55% Lines 85/124

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              223x 223x   223x     223x   223x   223x 223x 223x                                                                                                     223x                     223x 3236x     223x     191x 187x     187x           187x 187x 187x   187x                 187x 109x         187x                             187x                               187x 48x 4x       187x         109x           109x             187x 48x                 187x 44x 25x       187x           57x 49x       187x                     187x     187x       187x                                             223x                                                             223x                         663x             663x 192x 24x 18x 18x                       168x 60x 60x                       471x 471x 1432x 338x 338x 338x 338x   338x 54x   284x     266x 266x 266x   266x   1094x 476x 476x                     902x 18x         663x                               223x                   18x 18x   18x 18x 18x 18x 18x 18x                 223x 1130x 1130x 1130x                                                                                            
/*
 * 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 { useParams } from 'react-router-dom'
 
import { debounce, defaultTo, get, isEmpty, isPlainObject } from 'lodash-es'
import type { PipelineConfig, PipelineInfoConfig } from 'services/cd-ng'
import type { VariableMergeServiceResponse, Failure } from 'services/pipeline-ng'
import { useMutateAsGet, useQueryParams, useDeepCompareEffect } from '@common/hooks'
import type { UseMutateAsGetReturn } from '@common/hooks/useMutateAsGet'
import { useCreateVariables } from 'services/pipeline-ng'
import type { GitQueryParams, PipelinePathProps } from '@common/interfaces/RouteInterfaces'
import { yamlParse, yamlStringify } from '@common/utils/YamlHelperMethods'
import { useGetYamlWithTemplateRefsResolved } from 'services/template-ng'
import { getRegexForSearch } from '../LogsContent/LogsState/utils'
 
export interface KVPair {
  [key: string]: string
}
export interface SearchResult {
  value: string
  type: 'key' | 'value'
  metaKeyId: string
  path?: string
}
export interface PipelineVariablesData {
  variablesPipeline: PipelineInfoConfig
  originalPipeline: PipelineInfoConfig
  metadataMap: Required<VariableMergeServiceResponse>['metadataMap']
  error?: UseMutateAsGetReturn<Failure | Error>['error'] | null
  initLoading: boolean
  loading: boolean
  onSearchInputChange?: (value: string) => void
  goToPrevSearchResult?: (value: string) => void
  goToNextSearchResult?: (value: string) => void
  metaKeyToPathMap?: KVPair[]
  searchText?: string
  searchIndex?: number | null
  searchResults?: SearchResult[]
  setPipeline: (pipeline: PipelineInfoConfig) => void
  setResolvedPipeline: (pipeline: PipelineInfoConfig) => void
}
export interface SearchMeta {
  searchText?: string
  pipelineMetaKeys?: PipelineMeta[]
  pipelineFqns?: PipelineMeta[]
  pipelineValues?: PipelineMeta[]
  searchResults?: SearchResult[]
  searchIndex?: number | null
}
 
export interface GetPathToMetaKeyMapParams {
  path?: string
  pipelineMetaKeys?: PipelineMeta[]
  pipelineFqns?: PipelineMeta[]
  pipelineValues?: PipelineMeta[]
  data: KVPair
  metaDataMap: any
  pipeline: PipelineInfoConfig
}
 
export interface PipelineMeta {
  value: string
  metaKeyId: string
}
export const PipelineVariablesContext = React.createContext<PipelineVariablesData>({
  variablesPipeline: {} as PipelineInfoConfig,
  originalPipeline: {} as PipelineInfoConfig,
  metadataMap: {},
  error: null,
  initLoading: true,
  loading: false,
  setPipeline: () => void 0,
  setResolvedPipeline: () => void 0
})
 
export function usePipelineVariables(): PipelineVariablesData {
  return React.useContext(PipelineVariablesContext)
}
 
export function PipelineVariablesContextProvider(
  props: React.PropsWithChildren<{ pipeline?: PipelineInfoConfig; enablePipelineTemplatesResolution?: boolean }>
): React.ReactElement {
  const { pipeline: pipelineFromProps, enablePipelineTemplatesResolution } = props
  const [originalPipeline, setOriginalPipeline] = React.useState<PipelineInfoConfig>(
    defaultTo(pipelineFromProps, {} as PipelineInfoConfig)
  )
  const [{ variablesPipeline, metadataMap }, setPipelineVariablesData] = React.useState<
    Pick<PipelineVariablesData, 'metadataMap' | 'variablesPipeline'>
  >({
    variablesPipeline: { name: '', identifier: '', stages: [] },
    metadataMap: {}
  })
  const { accountId, orgIdentifier, projectIdentifier } = useParams<PipelinePathProps>()
  const { repoIdentifier, branch } = useQueryParams<GitQueryParams>()
  const [resolvedPipeline, setResolvedPipeline] = React.useState<PipelineInfoConfig>(originalPipeline)
  const [{ searchText, searchResults, searchIndex, pipelineValues, pipelineFqns, pipelineMetaKeys }, setSearchMeta] =
    React.useState<SearchMeta>({
      searchText: '',
      pipelineMetaKeys: [],
      pipelineFqns: [],
      searchResults: [],
      pipelineValues: [],
      searchIndex: 0
    })
 
  const updateSearchMeta = (newState: SearchMeta): void => {
    setSearchMeta(oldState => ({
      ...oldState,
      ...newState
    }))
  }
  const { data, error, initLoading, loading } = useMutateAsGet(useCreateVariables, {
    body: yamlStringify({ pipeline: originalPipeline }) as unknown as void,
    requestOptions: {
      headers: {
        'content-type': 'application/yaml'
      }
    },
    queryParams: { accountIdentifier: accountId, orgIdentifier, projectIdentifier, repoIdentifier, branch },
    debounce: 1300
  })
 
  const {
    data: resolvedPipelineResponse,
    initLoading: initLoadingResolvedPipeline,
    loading: loadingResolvedPipeline
  } = useMutateAsGet(useGetYamlWithTemplateRefsResolved, {
    queryParams: {
      accountIdentifier: accountId,
      orgIdentifier,
      pipelineIdentifier: originalPipeline.identifier,
      projectIdentifier,
      repoIdentifier,
      branch,
      getDefaultFromOtherRepo: true
    },
    body: {
      originalEntityYaml: enablePipelineTemplatesResolution ? yamlStringify(originalPipeline) : ''
    },
    lazy: !(enablePipelineTemplatesResolution && !isEmpty(originalPipeline))
  })
 
  React.useEffect(() => {
    if (resolvedPipelineResponse?.data?.mergedPipelineYaml) {
      setResolvedPipeline(yamlParse(resolvedPipelineResponse.data.mergedPipelineYaml))
    }
  }, [resolvedPipelineResponse])
 
  React.useEffect(() => {
    const {
      pipelineFqns: updatedPipelineFqns,
      pipelineMetaKeys: updatedPipelineMetaKeys,
      pipelineValues: updatedPipelineValues
    } = getPathToMetaKeyMap({
      data: variablesPipeline as any,
      metaDataMap: metadataMap,
      pipeline: resolvedPipeline
    })
 
    updateSearchMeta({
      pipelineMetaKeys: updatedPipelineMetaKeys,
      pipelineFqns: updatedPipelineFqns,
      pipelineValues: updatedPipelineValues
    })
  }, [variablesPipeline, metadataMap, resolvedPipeline])
 
  React.useEffect(() => {
    setPipelineVariablesData({
      metadataMap: defaultTo(data?.data?.metadataMap, {}),
      variablesPipeline: defaultTo(
        yamlParse<PipelineConfig>(defaultTo(data?.data?.yaml, ''))?.pipeline,
        {} as PipelineInfoConfig
      )
    })
  }, [data?.data?.metadataMap, data?.data?.yaml])
 
  useDeepCompareEffect(() => {
    if (pipelineFromProps) {
      setOriginalPipeline(pipelineFromProps)
    }
  }, [pipelineFromProps])
 
  useDeepCompareEffect(() => {
    /**
     * update resolved pipeline to same value as original pipeline
     * when template resolution is not enabled,
     * as it is used by variables screen
     */
    if (!enablePipelineTemplatesResolution) {
      setResolvedPipeline(originalPipeline)
    }
  }, [originalPipeline, enablePipelineTemplatesResolution])
 
  const onSearchInputChange = debounce((searchKey: string) => {
    if (searchKey !== searchText) {
      const finalFound = findMatchedResultsInPipeline(pipelineFqns, pipelineValues, pipelineMetaKeys, searchKey)
      updateSearchMeta({
        searchText: searchKey,
        searchResults: finalFound,
        searchIndex: searchKey.length > 0 ? 0 : null
      })
    }
  }, 300)
 
  const goToPrevSearchResult = (): false | void =>
    (searchIndex as number) > 0 && updateSearchMeta({ searchIndex: (searchIndex as number) - 1 })
 
  const goToNextSearchResult = (): false | void =>
    (searchIndex as number) < (searchResults as [])?.length - 1 &&
    updateSearchMeta({ searchIndex: (searchIndex as number) + 1 })
 
  return (
    <PipelineVariablesContext.Provider
      value={{
        variablesPipeline,
        originalPipeline: resolvedPipeline,
        metadataMap,
        error,
        initLoading: initLoading || initLoadingResolvedPipeline,
        loading: loading || loadingResolvedPipeline,
        onSearchInputChange,
        searchResults,
        searchText,
        searchIndex,
        goToPrevSearchResult,
        goToNextSearchResult,
        setPipeline: setOriginalPipeline,
        setResolvedPipeline
      }}
    >
      {props.children}
    </PipelineVariablesContext.Provider>
  )
}
export const findMatchedResultsInPipeline = (
  pipelineFqns: PipelineMeta[] = [],
  pipelineValues: PipelineMeta[] = [],
  pipelineMetaKeys: PipelineMeta[] = [],
  needle: string
): SearchResult[] => {
  const finalFound: SearchResult[] = []
  pipelineFqns.forEach(({ value: fqn, metaKeyId }, index) => {
    const fqnParts = fqn ? defaultTo(fqn?.split('.'), '') : ''
    const path = defaultTo(pipelineMetaKeys?.[index]?.value, '')
    //removes pipeline tags from search as we are showing them in popover
 
    if (fqnParts.length && fqnParts[fqnParts.length - 1]?.toLowerCase()?.includes(needle.toLocaleLowerCase())) {
      finalFound.push({ value: fqnParts[fqnParts.length - 1], type: 'key', metaKeyId, path })
    }
    let valueString = defaultTo(pipelineValues?.[index]?.value, '')
 
    if (Array.isArray(valueString)) {
      valueString = valueString.map(item => (isPlainObject(item) ? JSON.stringify(item, null, 2) : item)).join(', ')
    }
    if (typeof valueString !== 'string') {
      valueString = `${valueString}`
    }
    if (valueString.length && valueString?.toLowerCase()?.includes(needle.toLocaleLowerCase())) {
      finalFound.push({ value: valueString, type: 'value', metaKeyId, path })
    }
  })
 
  return finalFound
}
 
export function getPathToMetaKeyMap({
  path = '',
  pipelineMetaKeys = [],
  data,
  metaDataMap,
  pipelineFqns = [],
  pipelineValues = [],
  pipeline
}: GetPathToMetaKeyMapParams): {
  pipelineMetaKeys: PipelineMeta[]
  pipelineFqns: PipelineMeta[]
  pipelineValues: PipelineMeta[]
} {
  Iif (!data) {
    return {
      pipelineMetaKeys,
      pipelineFqns,
      pipelineValues
    }
  }
  if (Array.isArray(data)) {
    if (path.includes('variables')) {
      for (let index = data.length - 1; index >= 0; index--) {
        Eif (Array.isArray(data[index]) || typeof data[index] === 'object') {
          getPathToMetaKeyMap({
            path: `${path}[${index}]`,
            pipelineFqns,
            pipelineMetaKeys,
            data: data[index],
            metaDataMap,
            pipeline,
            pipelineValues
          })
        }
      }
    } else {
      data?.forEach((item, index) => {
        Eif (Array.isArray(item) || typeof item === 'object') {
          getPathToMetaKeyMap({
            path: `${path}[${index}]`,
            pipelineFqns,
            pipelineMetaKeys,
            data: item,
            metaDataMap,
            pipeline,
            pipelineValues
          })
        }
      })
    }
  } else Eif (typeof data === 'object') {
    Object.entries(data).forEach(([key, value]) => {
      if (typeof value === 'string' && metaDataMap[value]) {
        const metaKeyId = value
        const { yamlProperties, yamlOutputProperties } = metaDataMap[value]
        const yamlProps = defaultTo(yamlProperties, yamlOutputProperties)
        const updatedPath = `${path.trim().length === 0 ? '' : `${path}.`}${key}`
 
        if (updatedPath.includes('__uuid')) {
          return
        }
        if (path.includes('variables')) {
          //
        } else {
          pipelineFqns.push({ value: yamlProps?.fqn, metaKeyId })
          pipelineMetaKeys.push({ metaKeyId, value: updatedPath })
          const valueAtPath = get(pipeline, updatedPath)
 
          pipelineValues.push({ value: valueAtPath, metaKeyId })
        }
      } else if (typeof value === 'object') {
        const updatedPath = `${path.trim().length === 0 ? '' : `${path}.`}${key}`
        return getPathToMetaKeyMap({
          path: updatedPath,
          pipelineFqns,
          pipelineMetaKeys,
          data: value as KVPair,
          metaDataMap,
          pipeline,
          pipelineValues
        })
      }
 
      if (typeof value === 'string' && metaDataMap[value] && path.includes('variables')) {
        updateSpecialFields({ value, path, metaDataMap, pipelineFqns, pipelineMetaKeys, pipelineValues, pipeline, key })
      }
    })
  }
 
  return {
    pipelineMetaKeys,
    pipelineFqns,
    pipelineValues
  }
}
export interface UpdateSpecialFieldParams {
  value: string
  path: string
  metaDataMap: unknown
  pipelineFqns: PipelineMeta[]
  pipelineMetaKeys: PipelineMeta[]
  pipelineValues: PipelineMeta[]
  pipeline: PipelineInfoConfig
  key: string
}
const updateSpecialFields = ({
  value,
  path,
  metaDataMap,
  pipelineFqns,
  pipelineMetaKeys,
  pipelineValues,
  pipeline,
  key
}: UpdateSpecialFieldParams): void => {
  const metaKeyId = value
  const { yamlProperties, yamlOutputProperties } = (metaDataMap as any)?.[value]
 
  const yamlProps = defaultTo(yamlProperties, yamlOutputProperties)
  const updatedPath = `${path.trim().length === 0 ? '' : `${path}.`}${key}`
  pipelineFqns.unshift({ value: yamlProps?.fqn, metaKeyId })
  pipelineMetaKeys.unshift({ metaKeyId, value: updatedPath })
  const valueAtPath = get(pipeline, updatedPath)
  pipelineValues.unshift({ value: valueAtPath, metaKeyId })
}
export interface GetTextWithSearchMarkersProps {
  txt?: string
  searchText?: string
  searchIndices?: number[]
  className?: string
}
 
export function getTextWithSearchMarkers(props: GetTextWithSearchMarkersProps): string {
  const { searchText, txt, className } = props
  Eif (!searchText) {
    return defaultTo(txt, '')
  }
 
  if (!txt) {
    return ''
  }
 
  const searchRegex = getRegexForSearch(searchText)
  let match: RegExpExecArray | null
  const chunks: Array<{ start: number; end: number }> = []
 
  while ((match = searchRegex.exec(txt)) !== null) {
    if (searchRegex.lastIndex > match.index) {
      chunks.push({
        start: match.index,
        end: searchRegex.lastIndex
      })
 
      if (match.index === searchRegex.lastIndex) {
        searchRegex.lastIndex++
      }
    }
  }
 
  let highlightedString = txt
 
  chunks.forEach(chunk => {
    const startShift = highlightedString.length - txt.length
 
    const openMarkTags = `${highlightedString.slice(
      0,
      chunk.start + startShift
    )}<mark  class="${className}"  ${'data-current-search-result="true"'}>${highlightedString.slice(
      chunk.start + startShift
    )}`
 
    const endShift = openMarkTags.length - txt.length
    const closeMarkTags = `${openMarkTags.slice(0, chunk.end + endShift)}</mark>${openMarkTags.slice(
      chunk.end + endShift
    )}`
 
    highlightedString = closeMarkTags
  })
 
  return highlightedString
}