summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/ide/lib/errors.js
blob: f975034a8723110188248ecc78f0bec7a090a978 (plain)
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
import { escape } from 'lodash';
import { __ } from '~/locale';
import consts from '../stores/modules/commit/constants';

const CODEOWNERS_REGEX = /Push.*protected branches.*CODEOWNERS/;
const BRANCH_CHANGED_REGEX = /changed.*since.*start.*edit/;
const BRANCH_ALREADY_EXISTS = /branch.*already.*exists/;

const createNewBranchAndCommit = (store) =>
  store
    .dispatch('commit/updateCommitAction', consts.COMMIT_TO_NEW_BRANCH)
    .then(() => store.dispatch('commit/commitChanges'));

export const createUnexpectedCommitError = (message) => ({
  title: __('Unexpected error'),
  messageHTML: escape(message) || __('Could not commit. An unexpected error occurred.'),
});

export const createCodeownersCommitError = (message) => ({
  title: __('CODEOWNERS rule violation'),
  messageHTML: escape(message),
  primaryAction: {
    text: __('Create new branch'),
    callback: createNewBranchAndCommit,
  },
});

export const createBranchChangedCommitError = (message) => ({
  title: __('Branch changed'),
  messageHTML: `${escape(message)}<br/><br/>${__('Would you like to create a new branch?')}`,
  primaryAction: {
    text: __('Create new branch'),
    callback: createNewBranchAndCommit,
  },
});

export const branchAlreadyExistsCommitError = (message) => ({
  title: __('Branch already exists'),
  messageHTML: `${escape(message)}<br/><br/>${__(
    'Would you like to try auto-generating a branch name?',
  )}`,
  primaryAction: {
    text: __('Create new branch'),
    callback: (store) =>
      store.dispatch('commit/addSuffixToBranchName').then(() => createNewBranchAndCommit(store)),
  },
});

export const parseCommitError = (e) => {
  const { message } = e?.response?.data || {};

  if (!message) {
    return createUnexpectedCommitError();
  }

  if (CODEOWNERS_REGEX.test(message)) {
    return createCodeownersCommitError(message);
  } else if (BRANCH_CHANGED_REGEX.test(message)) {
    return createBranchChangedCommitError(message);
  } else if (BRANCH_ALREADY_EXISTS.test(message)) {
    return branchAlreadyExistsCommitError(message);
  }

  return createUnexpectedCommitError(message);
};