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

86.36% Statements 57/66
90.14% Branches 64/71
64.71% Functions 11/17
86.36% Lines 57/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 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385              22x 22x 22x 22x 22x 22x   22x 22x 22x 22x 22x 22x               22x 22x       22x 22x 22x   22x                                                                 90x                                   90x                           6x 3x                           3x                   22x                         91x                     90x 90x     90x         90x 90x 90x   90x               2x 2x         90x 90x   90x   90x               90x         6x 6x 6x 6x               6x               2x       2x       2x       90x     90x 75x     90x                     90x                                               90x       90x                     19x 19x     86x                                                                                                                                                                                                  
/*
 * 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 { Button, Popover, ButtonProps, useConfirmationDialog, getErrorInfoFromErrorObject } from '@harness/uicore'
import { useModalHook } from '@harness/use-modal'
import { Dialog, IDialogProps, Intent, Menu, MenuItem } from '@blueprintjs/core'
import { Link, useLocation, matchPath } from 'react-router-dom'
import { defaultTo } from 'lodash-es'
 
import { HandleInterruptQueryParams, useHandleInterrupt, useHandleStageInterrupt } from 'services/pipeline-ng'
import routes from '@common/RouteDefinitions'
import { useToaster } from '@common/exports'
import RbacButton from '@rbac/components/Button/Button'
import RbacMenuItem from '@rbac/components/MenuItem/MenuItem'
import {
  isExecutionComplete,
  isExecutionActive,
  isExecutionPaused,
  isExecutionPausing,
  ExecutionStatus,
  isRetryPipelineAllowed
} from '@pipeline/utils/statusHelpers'
import { getFeaturePropsForRunPipelineButton } from '@pipeline/utils/runPipelineUtils'
import { useStrings } from 'framework/strings'
import type { StringKeys } from 'framework/strings'
 
import type { GitQueryParams, PipelineType } from '@common/interfaces/RouteInterfaces'
import RetryPipeline from '../RetryPipeline/RetryPipeline'
import { useRunPipelineModal } from '../RunPipelineModal/useRunPipelineModal'
import css from './ExecutionActions.module.scss'
 
const commonButtonProps: ButtonProps = {
  minimal: true,
  small: true,
  tooltipProps: {
    isDark: true
  },
  withoutBoxShadow: true
}
 
export interface ExecutionActionsProps {
  executionStatus?: ExecutionStatus
  params: PipelineType<{
    orgIdentifier: string
    projectIdentifier: string
    pipelineIdentifier: string
    executionIdentifier: string
    accountId: string
    stagesExecuted?: string[]
  }> &
    GitQueryParams
  refetch?(): Promise<void>
  noMenu?: boolean
  stageId?: string
  stageName?: string
  canEdit?: boolean
  canExecute?: boolean
  canRetry?: boolean
  modules?: string[]
  showEditButton?: boolean
  isPipelineInvalid?: boolean
}
 
function getValidExecutionActions(canExecute: boolean, executionStatus?: ExecutionStatus) {
  return {
    canAbort: isExecutionActive(executionStatus) && canExecute,
    canPause:
      isExecutionActive(executionStatus) &&
      !isExecutionPaused(executionStatus) &&
      !isExecutionPausing(executionStatus) &&
      canExecute,
    canRerun: isExecutionComplete(executionStatus) && canExecute,
    canResume: isExecutionPaused(executionStatus) && canExecute
  }
}
 
function getActionTexts(stageId?: string): {
  abortText: StringKeys
  pauseText: StringKeys
  rerunText: StringKeys
  resumeText: StringKeys
} {
  return {
    abortText: stageId ? 'pipeline.execution.actions.abortStage' : 'pipeline.execution.actions.abortPipeline',
    pauseText: stageId ? 'pipeline.execution.actions.pauseStage' : 'pipeline.execution.actions.pausePipeline',
    rerunText: stageId ? 'pipeline.execution.actions.rerunStage' : 'pipeline.execution.actions.rerunPipeline',
    resumeText: stageId ? 'pipeline.execution.actions.resumeStage' : 'pipeline.execution.actions.resumePipeline'
  }
}
 
function getSuccessMessage(
  getString: (key: StringKeys, vars?: Record<string, any>) => string,
  interruptType: HandleInterruptQueryParams['interruptType'],
  stageId?: string,
  stageName?: string
): string {
  if (stageId) {
    return interruptType === 'AbortAll'
      ? getString('pipeline.execution.stageActionMessages.abortedMessage', {
          stageName
        })
      : interruptType === 'Pause'
      ? getString('pipeline.execution.stageActionMessages.pausedMessage', {
          stageName
        })
      : interruptType === 'Resume'
      ? getString('pipeline.execution.stageActionMessages.resumedMessage', {
          stageName
        })
      : ''
  } else {
    return interruptType === 'AbortAll'
      ? getString('pipeline.execution.pipelineActionMessages.abortedMessage')
      : interruptType === 'Pause'
      ? getString('pipeline.execution.pipelineActionMessages.pausedMessage')
      : interruptType === 'Resume'
      ? getString('pipeline.execution.pipelineActionMessages.resumedMessage')
      : ''
  }
}
 
export default function ExecutionActions(props: ExecutionActionsProps): React.ReactElement {
  const {
    executionStatus,
    params,
    noMenu,
    stageId,
    canEdit = true,
    canExecute = true,
    stageName,
    canRetry = false,
    modules,
    showEditButton = true,
    isPipelineInvalid
  } = props
  const {
    orgIdentifier,
    executionIdentifier,
    accountId,
    projectIdentifier,
    pipelineIdentifier,
    module,
    branch,
    repoIdentifier,
    stagesExecuted
  } = params
  const { mutate: interrupt } = useHandleInterrupt({
    planExecutionId: executionIdentifier
  })
  const { mutate: stageInterrupt } = useHandleStageInterrupt({
    planExecutionId: executionIdentifier,
    nodeExecutionId: defaultTo(stageId, '')
  })
 
  const { showSuccess, showError, clear } = useToaster()
  const { getString } = useStrings()
  const location = useLocation()
 
  const { openDialog: openAbortDialog } = useConfirmationDialog({
    cancelButtonText: getString('cancel'),
    contentText: getString('pipeline.execution.dialogMessages.abortExecution'),
    titleText: getString('pipeline.execution.dialogMessages.abortTitle'),
    confirmButtonText: getString('confirm'),
    intent: Intent.WARNING,
    onCloseDialog: async isConfirmed => {
      // istanbul ignore else
      if (isConfirmed) {
        abortPipeline()
      }
    }
  })
 
  const { canAbort, canPause, canRerun, canResume } = getValidExecutionActions(canExecute, executionStatus)
  const { abortText, pauseText, rerunText, resumeText } = getActionTexts(stageId)
 
  const interruptMethod = stageId ? stageInterrupt : interrupt
 
  const executionPipelineViewRoute = routes.toExecutionPipelineView({
    orgIdentifier,
    pipelineIdentifier,
    executionIdentifier,
    projectIdentifier,
    accountId,
    module
  })
  const isExecutionPipelineViewPage = !!matchPath(location.pathname, {
    path: executionPipelineViewRoute
  })
 
  async function executeAction(interruptType: HandleInterruptQueryParams['interruptType']): Promise<void> {
    clear()
    try {
      const successMessage = getSuccessMessage(getString, interruptType, stageId, stageName)
      await interruptMethod({} as never, {
        queryParams: {
          orgIdentifier,
          accountIdentifier: accountId,
          projectIdentifier,
          interruptType
        }
      })
      showSuccess(successMessage)
    } catch (e) {
      const errorMessage = getErrorInfoFromErrorObject(e)
      showError(errorMessage)
    }
  }
 
  async function abortPipeline(): Promise<void> {
    await executeAction('AbortAll')
  }
 
  async function pausePipeline(): Promise<void> {
    await executeAction('Pause')
  }
 
  async function resumePipeline(): Promise<void> {
    await executeAction('Resume')
  }
 
  /*--------------------------------------Retry Pipeline---------------------------------------------*/
  const retryPipeline = (): void => {
    showRetryPipelineModal()
  }
  const showRetryPipeline = (): boolean => {
    return isRetryPipelineAllowed(executionStatus) && canRetry
  }
 
  const DIALOG_PROPS: IDialogProps = {
    isOpen: true,
    usePortal: true,
    autoFocus: true,
    canEscapeKeyClose: false,
    canOutsideClickClose: false,
    enforceFocus: false,
    className: css.runPipelineDialog,
    style: { width: 872, height: 'fit-content', overflow: 'auto' }
  }
 
  const [showRetryPipelineModal, hideRetryPipelineModal] = useModalHook(() => {
    const onClose = (): void => {
      hideRetryPipelineModal()
    }
 
    return (
      <Dialog onClose={onClose} {...DIALOG_PROPS}>
        <div className={css.modalContent}>
          <RetryPipeline
            onClose={onClose}
            executionIdentifier={executionIdentifier}
            pipelineIdentifier={pipelineIdentifier}
            modules={modules}
          />
          <Button minimal icon="cross" onClick={onClose} className={css.crossIcon} />
        </div>
      </Dialog>
    )
  }, [pipelineIdentifier, executionIdentifier])
 
  /*--------------------------------------Retry Pipeline---------------------------------------------*/
 
  /*--------------------------------------Run Pipeline---------------------------------------------*/
 
  const reRunPipeline = (): void => {
    openRunPipelineModal()
  }
 
  const { openRunPipelineModal } = useRunPipelineModal({
    pipelineIdentifier,
    executionId: executionIdentifier,
    repoIdentifier,
    branch,
    stagesExecuted
  })
 
  /*--------------------------------------Run Pipeline---------------------------------------------*/
 
  function killEvent(e: React.MouseEvent<HTMLDivElement>): void {
    e.preventDefault()
    e.stopPropagation()
  }
 
  return (
    <div className={css.main} onClick={killEvent}>
      {canResume ? (
        <Button
          icon="play"
          tooltip={getString(resumeText)}
          onClick={resumePipeline}
          {...commonButtonProps}
          disabled={!canExecute}
        />
      ) : null}
      {!stageId && canRerun ? (
        <RbacButton
          icon="repeat"
          tooltip={isPipelineInvalid ? getString('pipeline.cannotRunInvalidPipeline') : getString(rerunText)}
          onClick={reRunPipeline}
          {...commonButtonProps}
          disabled={!canExecute || isPipelineInvalid}
          featuresProps={getFeaturePropsForRunPipelineButton({ modules, getString })}
        />
      ) : null}
      {canPause ? (
        <Button
          icon="pause"
          tooltip={getString(pauseText)}
          onClick={pausePipeline}
          {...commonButtonProps}
          disabled={!canExecute}
        />
      ) : null}
      {canAbort ? (
        <Button
          icon="stop"
          tooltip={getString(abortText)}
          onClick={openAbortDialog}
          {...commonButtonProps}
          disabled={!canExecute}
        />
      ) : null}
      {noMenu ? null : (
        <Popover position="bottom-right" minimal>
          <Button icon="more" {...commonButtonProps} className={css.more} />
          <Menu>
            {!isExecutionPipelineViewPage && (
              <Link
                className="bp3-menu-item"
                target="_blank"
                to={executionPipelineViewRoute}
                onClick={e => e.stopPropagation()}
              >
                {getString('pipeline.openInNewTab')}
              </Link>
            )}
            {showEditButton ? (
              <Link
                className={`bp3-menu-item${!canEdit ? ' bp3-disabled' : ''}`}
                to={routes.toPipelineStudio({
                  orgIdentifier,
                  projectIdentifier,
                  pipelineIdentifier,
                  accountId,
                  module,
                  branch,
                  repoIdentifier
                })}
                onClick={e => !canEdit && e.preventDefault()}
              >
                {getString('editPipeline')}
              </Link>
            ) : null}
            {stageId ? null : (
              <RbacMenuItem
                featuresProps={getFeaturePropsForRunPipelineButton({ modules, getString })}
                text={getString(rerunText)}
                disabled={!canRerun || isPipelineInvalid}
                onClick={reRunPipeline}
              />
            )}
            <MenuItem text={getString(pauseText)} onClick={pausePipeline} disabled={!canPause} />
            <MenuItem text={getString(abortText)} onClick={openAbortDialog} disabled={!canAbort} />
            <MenuItem text={getString(resumeText)} onClick={resumePipeline} disabled={!canResume} />
            {showRetryPipeline() && (
              <RbacMenuItem
                featuresProps={getFeaturePropsForRunPipelineButton({ modules, getString })}
                text={getString('pipeline.retryPipeline')}
                onClick={retryPipeline}
                data-testid="retry-pipeline-menu"
                disabled={isPipelineInvalid}
              />
            )}
            {/* {stageId ? null : <MenuItem text={getString('pipeline.execution.actions.downloadLogs')} disabled />} */}
          </Menu>
        </Popover>
      )}
    </div>
  )
}