actions.js 7.0 KB
Newer Older
P
Phil Hughes 已提交
1 2 3 4 5 6 7 8
import $ from 'jquery';
import { sprintf, __ } from '~/locale';
import flash from '~/flash';
import * as rootTypes from '../../mutation_types';
import { createCommitPayload, createNewMergeRequestUrl } from '../../utils';
import router from '../../../ide_router';
import service from '../../../services';
import * as types from './mutation_types';
S
Sam Bigelow 已提交
9
import consts from './constants';
10
import { leftSidebarViews } from '../../../constants';
P
Phil Hughes 已提交
11 12 13 14 15 16 17 18 19 20
import eventHub from '../../../eventhub';

export const updateCommitMessage = ({ commit }, message) => {
  commit(types.UPDATE_COMMIT_MESSAGE, message);
};

export const discardDraft = ({ commit }) => {
  commit(types.UPDATE_COMMIT_MESSAGE, '');
};

21
export const updateCommitAction = ({ commit, getters }, commitAction) => {
S
Sam Bigelow 已提交
22 23 24
  commit(types.UPDATE_COMMIT_ACTION, {
    commitAction,
  });
25
  commit(types.TOGGLE_SHOULD_CREATE_MR, !getters.shouldHideNewMrOption);
S
Sam Bigelow 已提交
26 27 28 29
};

export const toggleShouldCreateMR = ({ commit }) => {
  commit(types.TOGGLE_SHOULD_CREATE_MR);
P
Phil Hughes 已提交
30 31 32 33 34 35
};

export const updateBranchName = ({ commit }, branchName) => {
  commit(types.UPDATE_NEW_BRANCH_NAME, branchName);
};

S
Sam Bigelow 已提交
36 37
export const setLastCommitMessage = ({ commit, rootGetters }, data) => {
  const { currentProject } = rootGetters;
P
Phil Hughes 已提交
38 39
  const commitStats = data.stats
    ? sprintf(__('with %{additions} additions, %{deletions} deletions.'), {
40 41 42
        additions: data.stats.additions,
        deletions: data.stats.deletions,
      })
P
Phil Hughes 已提交
43 44 45 46
    : '';
  const commitMsg = sprintf(
    __('Your changes have been committed. Commit %{commitId} %{commitStats}'),
    {
47
      commitId: `<a href="${currentProject.web_url}/-/commit/${data.short_id}" class="commit-sha">${data.short_id}</a>`,
P
Phil Hughes 已提交
48 49 50 51 52 53 54 55
      commitStats,
    },
    false,
  );

  commit(rootTypes.SET_LAST_COMMIT_MSG, commitMsg, { root: true });
};

S
Sam Bigelow 已提交
56 57
export const updateFilesAfterCommit = ({ commit, dispatch, rootState, rootGetters }, { data }) => {
  const selectedProject = rootGetters.currentProject;
P
Phil Hughes 已提交
58
  const lastCommit = {
59
    commit_path: `${selectedProject.web_url}/-/commit/${data.id}`,
P
Phil Hughes 已提交
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
    commit: {
      id: data.id,
      message: data.message,
      authored_date: data.committed_date,
      author_name: data.committer_name,
    },
  };

  commit(
    rootTypes.SET_BRANCH_WORKING_REFERENCE,
    {
      projectId: rootState.currentProjectId,
      branchId: rootState.currentBranchId,
      reference: data.id,
    },
    { root: true },
  );

78 79
  rootState.stagedFiles.forEach(file => {
    const changedFile = rootState.changedFiles.find(f => f.path === file.path);
P
Phil Hughes 已提交
80 81

    commit(
82
      rootTypes.UPDATE_FILE_AFTER_COMMIT,
P
Phil Hughes 已提交
83
      {
84 85
        file,
        lastCommit,
P
Phil Hughes 已提交
86 87 88 89 90 91 92
      },
      { root: true },
    );

    commit(
      rootTypes.TOGGLE_FILE_CHANGED,
      {
93
        file,
P
Phil Hughes 已提交
94 95 96 97
        changed: false,
      },
      { root: true },
    );
P
Phil Hughes 已提交
98

99
    dispatch('updateTempFlagForEntry', { file, tempFile: false }, { root: true });
P
Phil Hughes 已提交
100

101
    eventHub.$emit(`editor.update.model.content.${file.key}`, {
102
      content: file.content,
103
      changed: Boolean(changedFile),
104
    });
P
Phil Hughes 已提交
105 106 107
  });
};

108
export const commitChanges = ({ commit, state, getters, dispatch, rootState, rootGetters }) => {
109 110 111
  // Pull commit options out because they could change
  // During some of the pre and post commit processing
  const { shouldCreateMR, isCreatingNewBranch, branchName } = getters;
P
Phil Hughes 已提交
112
  const newBranch = state.commitAction !== consts.COMMIT_TO_CURRENT_BRANCH;
P
Phil Hughes 已提交
113 114 115
  const stageFilesPromise = rootState.stagedFiles.length
    ? Promise.resolve()
    : dispatch('stageAllChanges', null, { root: true });
P
Phil Hughes 已提交
116 117 118

  commit(types.UPDATE_LOADING, true);

P
Phil Hughes 已提交
119
  return stageFilesPromise
120 121
    .then(() => {
      const payload = createCommitPayload({
122
        branch: branchName,
123 124 125 126
        newBranch,
        getters,
        state,
        rootState,
P
Paul Slaughter 已提交
127
        rootGetters,
128 129 130 131
      });

      return service.commit(rootState.currentProjectId, payload);
    })
P
Phil Hughes 已提交
132 133 134 135 136
    .then(({ data }) => {
      commit(types.UPDATE_LOADING, false);

      if (!data.short_id) {
        flash(data.message, 'alert', document, null, false, true);
137
        return null;
P
Phil Hughes 已提交
138 139
      }

140 141 142 143 144 145 146 147 148 149 150
      if (!data.parent_ids.length) {
        commit(
          rootTypes.TOGGLE_EMPTY_STATE,
          {
            projectPath: rootState.currentProjectId,
            value: false,
          },
          { root: true },
        );
      }

P
Phil Hughes 已提交
151 152
      dispatch('setLastCommitMessage', data);
      dispatch('updateCommitMessage', '');
153 154
      return dispatch('updateFilesAfterCommit', {
        data,
155
        branch: branchName,
156 157
      })
        .then(() => {
158 159 160 161 162 163
          commit(rootTypes.CLEAR_STAGED_CHANGES, null, { root: true });

          setTimeout(() => {
            commit(rootTypes.SET_LAST_COMMIT_MSG, '', { root: true });
          }, 5000);

164
          if (shouldCreateMR) {
S
Sam Bigelow 已提交
165
            const { currentProject } = rootGetters;
166
            const targetBranch = isCreatingNewBranch
S
Sam Bigelow 已提交
167 168 169
              ? rootState.currentBranchId
              : currentProject.default_branch;

170 171
            dispatch(
              'redirectToUrl',
172
              createNewMergeRequestUrl(currentProject.web_url, branchName, targetBranch),
173 174 175 176
              { root: true },
            );
          }
        })
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
        .then(() => {
          if (rootGetters.lastOpenedFile) {
            dispatch(
              'openPendingTab',
              {
                file: rootGetters.lastOpenedFile,
              },
              { root: true },
            )
              .then(changeViewer => {
                if (changeViewer) {
                  dispatch('updateViewer', 'diff', { root: true });
                }
              })
              .catch(e => {
                throw e;
              });
          } else {
195
            dispatch('updateActivityBarView', leftSidebarViews.edit.name, { root: true });
196 197
            dispatch('updateViewer', 'editor', { root: true });

198 199
            if (rootGetters.activeFile) {
              router.push(
200
                `/project/${rootState.currentProjectId}/blob/${branchName}/-/${rootGetters.activeFile.path}`,
201 202
              );
            }
203 204
          }
        })
205
        .then(() => dispatch('updateCommitAction', consts.COMMIT_TO_CURRENT_BRANCH))
206 207 208 209 210 211 212 213 214 215
        .then(() =>
          dispatch(
            'refreshLastCommitData',
            {
              projectId: rootState.currentProjectId,
              branchId: rootState.currentBranchId,
            },
            { root: true },
          ),
        );
P
Phil Hughes 已提交
216 217
    })
    .catch(err => {
218 219 220
      if (err.response.status === 400) {
        $('#ide-create-branch-modal').modal('show');
      } else {
221 222 223
        dispatch(
          'setErrorMessage',
          {
224
            text: __('An error occurred while committing your changes.'),
225 226 227 228 229 230 231 232
            action: () =>
              dispatch('commitChanges').then(() =>
                dispatch('setErrorMessage', null, { root: true }),
              ),
            actionText: __('Please try again'),
          },
          { root: true },
        );
233
        window.dispatchEvent(new Event('resize'));
P
Phil Hughes 已提交
234 235 236 237 238
      }

      commit(types.UPDATE_LOADING, false);
    });
};
239 240 241

// prevent babel-plugin-rewire from generating an invalid default during karma tests
export default () => {};