All files / app/assets/javascripts/vue_merge_request_widget/stores mr_widget_store.js

96.74% Statements 238/246
87.39% Branches 104/119
91.3% Functions 21/23
96.73% Lines 237/245

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                              8x   8x 8x       108x 108x   108x 108x 108x 108x   108x 108x 108x   108x 108x 108x   108x   108x 108x 108x       108x 108x       201x   201x   201x 1x     201x   201x 201x 201x 201x 201x   201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x   201x 189x 189x 189x 189x 189x   189x                       201x 201x 201x 201x 201x 201x 201x 201x 201x 201x     201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x     201x 201x 201x   201x 201x 201x 201x   201x 201x 201x 201x 201x 201x 201x   201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x   201x   201x 189x   189x 189x 189x 189x   189x       120x 120x   120x   120x 120x 120x 120x   120x 120x 120x 120x   120x       120x 120x     120x 120x 120x 120x 120x 120x 120x 120x 120x 120x   120x       60x 60x   60x       321x           108x 108x 108x 108x 108x       385x   385x 29x   356x   215x 215x   7x 7x   134x       385x         125x 125x 125x 125x 125x 125x 125x 125x 125x 125x 125x 125x 125x 125x 125x 125x 125x 125x 125x 125x 125x 125x 125x 125x 125x 125x 125x 125x 125x 125x 125x 125x     125x 125x 125x 125x     125x 125x   125x 125x       4x               201x 12x     189x                     579x 189x     390x                 378x 189x     189x       352x   143x 3x   140x 14x   126x 4x   122x 50x     72x       201x       9x 9x   9x         5x       7x       3x                 385x 170x   215x     385x     385x 385x         385x 215x     385x                      
import getStateKey from 'ee_else_ce/vue_merge_request_widget/stores/get_state_key';
import { STATUS_CLOSED, STATUS_MERGED, STATUS_OPEN } from '~/issues/constants';
import { formatDate, getTimeago, timeagoLanguageCode } from '~/lib/utils/datetime_utility';
import { machine } from '~/lib/utils/finite_state_machine';
import { badgeState } from '~/merge_requests/components/merge_request_header.vue';
import {
  MTWPS_MERGE_STRATEGY,
  MT_MERGE_STRATEGY,
  MWCP_MERGE_STRATEGY,
  MWPS_MERGE_STRATEGY,
  STATE_MACHINE,
  stateToTransitionMap,
} from '../constants';
import { stateKey } from './state_maps';
 
const { format } = getTimeago();
 
const { states } = STATE_MACHINE;
const { IDLE } = states;
 
export default class MergeRequestStore {
  constructor(data) {
    this.sha = data.diff_head_sha;
    this.gitlabLogo = data.gitlabLogo;
 
    this.apiApprovalsPath = data.api_approvals_path;
    this.apiApprovePath = data.api_approve_path;
    this.apiUnapprovePath = data.api_unapprove_path;
    this.hasApprovalsAvailable = data.has_approvals_available;
 
    this.stateMachine = machine(STATE_MACHINE.definition);
    this.machineValue = this.stateMachine.value;
    this.mergeDetailsCollapsed =
      !window.gon?.features?.mergeBlockedComponent && window.innerWidth < 768;
    this.mergeError = data.mergeError;
    this.multipleApprovalRulesAvailable = data.multiple_approval_rules_available || false;
    this.id = data.id;
 
    this.setPaths(data);
 
    this.setData(data);
    this.initCodeQualityReport(data);
    this.setGitpodData(data);
  }
 
  initCodeQualityReport(data) {
    this.blobPath = data.blob_path;
    this.codeQuality = data.codequality_reports_path;
  }
 
  setData(data, isRebased) {
    this.initApprovals();
 
    this.updateStatusState(data.state);
 
    if (isRebased) {
      this.sha = data.diff_head_sha;
    }
 
    const pipelineStatus = data.pipeline ? data.pipeline.details.status : null;
 
    this.squash = data.squash;
    this.squashIsEnabledByDefault = data.squash_enabled_by_default;
    this.squashIsReadonly = data.squash_readonly;
    this.enableSquashBeforeMerge = this.enableSquashBeforeMerge || true;
    this.squashIsSelected = data.squash_readonly ? data.squash_on_merge : data.squash;
 
    this.iid = data.iid;
    this.title = data.title;
    this.targetBranch = data.target_branch;
    this.targetBranchSha = data.target_branch_sha;
    this.sourceBranch = data.source_branch;
    this.sourceBranchProtected = data.source_branch_protected;
    this.conflictsDocsPath = data.conflicts_docs_path;
    this.commitMessage = data.default_merge_commit_message;
    this.shortMergeCommitSha = data.short_merged_commit_sha;
    this.mergeCommitSha = data.merged_commit_sha;
    this.commitMessageWithDescription = data.default_merge_commit_message_with_description;
    this.divergedCommitsCount = data.diverged_commits_count;
    this.pipeline = data.pipeline || {};
    this.pipelineCoverageDelta = data.pipeline_coverage_delta;
    this.buildsWithCoverage = data.builds_with_coverage;
    this.mergePipeline = data.merge_pipeline || {};
    this.deployments = this.deployments || data.deployments || [];
    this.postMergeDeployments = this.postMergeDeployments || [];
    this.commits = data.commits_without_merge_commits || [];
    this.squashCommitMessage = data.default_squash_commit_message;
    this.rebaseInProgress = data.rebase_in_progress;
    this.mergeRequestDiffsPath = data.diffs_path;
    this.approvalsWidgetType = data.approvals_widget_type;
    this.mergeRequestWidgetPath = data.merge_request_widget_path;
 
    if (data.issues_links) {
      const links = data.issues_links;
      const { closing } = links;
      const mentioned = links.mentioned_but_not_closing;
      const assignToMe = links.assign_to_closing;
      const unassignedCount = links.assign_to_closing_count;
 
      Iif (closing || mentioned || unassignedCount) {
        this.relatedLinks = {
          closing,
          mentioned,
          assignToMe,
          closingCount: links.closing_count,
          mentionedCount: links.mentioned_count,
          unassignedCount: links.assign_to_closing_count,
        };
      }
    }
 
    this.updatedAt = data.updated_at;
    this.metrics = MergeRequestStore.buildMetrics(data.metrics);
    this.setToAutoMergeBy = MergeRequestStore.formatUserObject(data.merge_user || {});
    this.mergeUserId = data.merge_user_id;
    this.currentUserId = gon.current_user_id;
    this.sourceBranchRemoved = !data.source_branch_exists;
    this.shouldRemoveSourceBranch = data.remove_source_branch || false;
    this.autoMergeStrategy = data.auto_merge_strategy;
    this.availableAutoMergeStrategies = data.available_auto_merge_strategies;
    this.preferredAutoMergeStrategy = MergeRequestStore.getPreferredAutoMergeStrategy(
      this.availableAutoMergeStrategies,
    );
    this.ffOnlyEnabled = data.ff_only_enabled;
    this.ffMergePossible = data.ff_merge_possible;
    this.isRemovingSourceBranch = this.isRemovingSourceBranch || false;
    this.mergeRequestState = data.state;
    this.isOpen = this.mergeRequestState === STATUS_OPEN;
    this.latestSHA = data.diff_head_sha;
    this.isMergeAllowed = data.mergeable || false;
    this.mergeOngoing = data.merge_ongoing;
    this.allowCollaboration = data.allow_collaboration;
    this.sourceProjectId = data.source_project_id;
    this.targetProjectId = data.target_project_id;
 
    // CI related
    this.hasCI = data.has_ci;
    this.ciStatus = data.ci_status;
    this.isPipelinePassing =
      this.ciStatus === 'success' || this.ciStatus === 'success-with-warnings';
    this.isPipelineSkipped = this.ciStatus === 'skipped';
    this.pipelineDetailedStatus = pipelineStatus;
    this.isPipelineActive = data.pipeline ? data.pipeline.active : false;
    this.isPipelineBlocked =
      data.only_allow_merge_if_pipeline_succeeds && pipelineStatus?.group === 'manual';
    this.faviconOverlayPath = data.favicon_overlay_path;
    this.terraformReportsPath = data.terraform_reports_path;
    this.testResultsPath = data.test_reports_path;
    this.accessibilityReportPath = data.accessibility_report_path;
    this.exposedArtifactsPath = data.exposed_artifacts_path;
    this.cancelAutoMergePath = data.cancel_auto_merge_path;
    this.canCancelAutomaticMerge = Boolean(data.cancel_auto_merge_path);
 
    this.newBlobPath = data.new_blob_path;
    this.sourceBranchPath = data.source_branch_path;
    this.sourceBranchLink = data.source_branch_with_namespace_link;
    this.rebasePath = data.rebase_path;
    this.targetBranchPath = data.target_branch_commits_path;
    this.targetBranchTreePath = data.target_branch_tree_path;
    this.conflictResolutionPath = data.conflict_resolution_path;
    this.removeWIPPath = data.remove_wip_path;
    this.createIssueToResolveDiscussionsPath = data.create_issue_to_resolve_discussions_path;
    this.mergePath = data.merge_path;
    this.mergeCommitPath = data.merged_commit_path;
    this.canPushToSourceBranch = data.can_push_to_source_branch;
 
    const currentUser = data.current_user;
 
    this.cherryPickInForkPath = currentUser.cherry_pick_in_fork_path;
    this.revertInForkPath = currentUser.revert_in_fork_path;
 
    this.canRemoveSourceBranch = currentUser.can_remove_source_branch || false;
    this.canCreateIssue = currentUser.can_create_issue || false;
    this.canCherryPickInCurrentMR = currentUser.can_cherry_pick_on_current_merge_request || false;
    this.canRevertInCurrentMR = currentUser.can_revert_on_current_merge_request || false;
 
    this.setState();
  }
 
  setGraphqlData(project) {
    const { mergeRequest } = project;
    const pipeline = mergeRequest.headPipeline;
 
    this.updateStatusState(mergeRequest.state);
 
    this.issuableId = mergeRequest.id;
    this.projectArchived = project.archived;
    this.onlyAllowMergeIfPipelineSucceeds = project.onlyAllowMergeIfPipelineSucceeds;
    this.allowMergeOnSkippedPipeline = project.allowMergeOnSkippedPipeline;
 
    this.autoMergeEnabled = mergeRequest.autoMergeEnabled;
    this.canBeMerged = mergeRequest.mergeStatus === 'can_be_merged';
    this.canMerge = mergeRequest.userPermissions.canMerge;
    this.ciStatus = pipeline?.status.toLowerCase();
 
    Iif (pipeline?.warnings && this.ciStatus === 'success') {
      this.ciStatus = `${this.ciStatus}-with-warnings`;
    }
 
    this.commitsCount = mergeRequest.commitCount;
    this.branchMissing =
      mergeRequest.detailedMergeStatus !== 'NOT_OPEN' &&
      (!mergeRequest.sourceBranchExists || !mergeRequest.targetBranchExists);
    this.hasConflicts = mergeRequest.conflicts;
    this.hasMergeableDiscussionsState = mergeRequest.mergeableDiscussionsState === false;
    this.mergeError = mergeRequest.mergeError;
    this.mergeStatus = mergeRequest.mergeStatus;
    this.isPipelineFailed = this.ciStatus === 'failed' || this.ciStatus === 'canceled';
    this.isSHAMismatch = this.sha !== mergeRequest.diffHeadSha;
    this.shouldBeRebased = mergeRequest.shouldBeRebased;
    this.draft = mergeRequest.draft;
    this.mergeRequestState = mergeRequest.state;
    this.detailedMergeStatus = mergeRequest.detailedMergeStatus;
 
    this.setState();
  }
 
  setGraphqlSubscriptionData(data) {
    this.detailedMergeStatus = data.detailedMergeStatus;
    this.commitsCount = data.commitCount;
 
    this.setState();
  }
 
  updateStatusState(state) {
    Iif (this.mergeRequestState !== state && badgeState.updateStatus) {
      badgeState.updateStatus();
    }
  }
 
  setGitpodData(data) {
    this.showGitpodButton = data.show_gitpod_button;
    this.gitpodUrl = data.gitpod_url;
    this.gitpodEnabled = data.gitpod_enabled;
    this.userPreferencesGitpodPath = data.user_preferences_gitpod_path;
    this.userProfileEnableGitpodPath = data.user_profile_enable_gitpod_path;
  }
 
  setState() {
    Iif (this.mergeOngoing) {
      this.state = 'merging';
    } else if (this.isOpen) {
      this.state = getStateKey.call(this);
    } else {
      switch (this.mergeRequestState) {
        case STATUS_MERGED:
          this.state = STATUS_MERGED;
          break;
        case STATUS_CLOSED:
          this.state = STATUS_CLOSED;
          break;
        default:
          this.state = null;
      }
    }
 
    this.translateStateToMachine();
  }
 
  setPaths(data) {
    // Paths are set on the first load of the page and not auto-refreshed
    this.squashBeforeMergeHelpPath = data.squash_before_merge_help_path;
    this.mrTroubleshootingDocsPath = data.mr_troubleshooting_docs_path;
    this.ciTroubleshootingDocsPath = data.ci_troubleshooting_docs_path;
    this.pipelineMustSucceedDocsPath = data.pipeline_must_succeed_docs_path;
    this.mergeRequestBasicPath = data.merge_request_basic_path;
    this.mergeRequestWidgetPath = data.merge_request_widget_path;
    this.mergeRequestCachedWidgetPath = data.merge_request_cached_widget_path;
    this.emailPatchesPath = data.email_patches_path;
    this.plainDiffPath = data.plain_diff_path;
    this.mergeCheckPath = data.merge_check_path;
    this.mergeActionsContentPath = data.commit_change_content_path;
    this.targetProjectFullPath = data.target_project_full_path;
    this.sourceProjectFullPath = data.source_project_full_path;
    this.mergeRequestPipelinesHelpPath = data.merge_request_pipelines_docs_path;
    this.conflictsDocsPath = data.conflicts_docs_path;
    this.reviewingDocsPath = data.reviewing_and_managing_merge_requests_docs_path;
    this.ciEnvironmentsStatusPath = data.ci_environments_status_path;
    this.codeCoverageCheckHelpPagePath = data.code_coverage_check_help_page_path;
    this.licenseComplianceDocsPath = data.license_compliance_docs_path;
    this.eligibleApproversDocsPath = data.eligible_approvers_docs_path;
    this.mergeImmediatelyDocsPath = data.merge_immediately_docs_path;
    this.approvalsHelpPath = data.approvals_help_path;
    this.mergeRequestAddCiConfigPath = data.merge_request_add_ci_config_path;
    this.pipelinesEmptySvgPath = data.pipelines_empty_svg_path;
    this.humanAccess = data.human_access;
    this.newPipelinePath = data.new_project_pipeline_path;
    this.sourceProjectDefaultUrl = data.source_project_default_url;
    this.userCalloutsPath = data.user_callouts_path;
    this.suggestPipelineFeatureId = data.suggest_pipeline_feature_id;
    this.isDismissedSuggestPipeline = data.is_dismissed_suggest_pipeline;
    this.securityReportsDocsPath = data.security_reports_docs_path;
    this.securityConfigurationPath = data.security_configuration_path;
 
    // code quality
    const blobPath = data.blob_path || {};
    this.headBlobPath = blobPath.head_path || '';
    this.baseBlobPath = blobPath.base_path || '';
    this.codequalityReportsPath = data.codequality_reports_path;
 
    // Security reports
    this.sastComparisonPath = data.sast_comparison_path;
    this.secretDetectionComparisonPath = data.secret_detection_comparison_path;
 
    this.sastComparisonPathV2 = data.new_sast_comparison_path;
    this.secretDetectionComparisonPathV2 = data.new_secret_detection_comparison_path;
  }
 
  get isNothingToMergeState() {
    return this.state === stateKey.nothingToMerge;
  }
 
  get isMergedState() {
    return this.state === stateKey.merged;
  }
 
  static buildMetrics(metrics) {
    if (!metrics) {
      return {};
    }
 
    return {
      mergedBy: MergeRequestStore.formatUserObject(metrics.merged_by),
      closedBy: MergeRequestStore.formatUserObject(metrics.closed_by),
      mergedAt: formatDate(metrics.merged_at),
      closedAt: formatDate(metrics.closed_at),
      readableMergedAt: MergeRequestStore.getReadableDate(metrics.merged_at),
      readableClosedAt: MergeRequestStore.getReadableDate(metrics.closed_at),
    };
  }
 
  static formatUserObject(user) {
    if (!user) {
      return {};
    }
 
    return {
      name: user.name || '',
      username: user.username || '',
      webUrl: user.web_url || '',
      avatarUrl: user.avatar_url || '',
    };
  }
 
  static getReadableDate(date) {
    if (!date) {
      return '';
    }
 
    return format(date, timeagoLanguageCode);
  }
 
  static getPreferredAutoMergeStrategy(availableAutoMergeStrategies) {
    if (availableAutoMergeStrategies === undefined) return undefined;
 
    if (availableAutoMergeStrategies.includes(MTWPS_MERGE_STRATEGY)) {
      return MTWPS_MERGE_STRATEGY;
    }
    if (availableAutoMergeStrategies.includes(MT_MERGE_STRATEGY)) {
      return MT_MERGE_STRATEGY;
    }
    if (availableAutoMergeStrategies.includes(MWCP_MERGE_STRATEGY)) {
      return MWCP_MERGE_STRATEGY;
    }
    if (availableAutoMergeStrategies.includes(MWPS_MERGE_STRATEGY)) {
      return MWPS_MERGE_STRATEGY;
    }
 
    return undefined;
  }
 
  initApprovals() {
    this.isApproved = this.isApproved || false;
  }
 
  setApprovals(data) {
    this.isApproved = data.approved || false;
    this.approvals = true;
 
    this.setState();
  }
 
  // eslint-disable-next-line class-methods-use-this
  get hasMergeChecksFailed() {
    return false;
  }
 
  get isApprovalNeeded() {
    return this.hasApprovalsAvailable ? !this.isApproved : false;
  }
 
  get preventMerge() {
    return this.isApprovalNeeded;
  }
 
  // Because the state machine doesn't yet handle every state and transition,
  //    some use-cases will need to force a state that can't be reached by
  //    a known transition. This is undesirable long-term (as it subverts
  //    the intent of a state machine), but is necessary until the machine
  //    can handle all possible combinations. (unsafeForce)
  transitionStateMachine({ transition, state, unsafeForce = false } = {}) {
    if (unsafeForce && state) {
      this.stateMachine.value = state;
    } else {
      this.stateMachine.send(transition);
    }
 
    this.machineValue = this.stateMachine.value;
  }
  translateStateToMachine() {
    const transition = stateToTransitionMap[this.state];
    let transitionOptions = {
      state: IDLE,
      unsafeForce: true,
    };
 
    if (transition) {
      transitionOptions = { transition };
    }
 
    this.transitionStateMachine(transitionOptions);
  }
 
  toggleMergeDetails(val = !this.mergeDetailsCollapsed) {
    if (window.gon?.features?.mergeBlockedComponent) {
      return;
    }
 
    this.mergeDetailsCollapsed = val;
  }
}