actions.js 6.9 KB
Newer Older
P
Phil Hughes 已提交
1 2 3 4 5 6 7 8 9 10
import $ from 'jquery';
import { sprintf, __ } from '~/locale';
import flash from '~/flash';
import { stripHtml } from '~/lib/utils/text_utility';
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';
import * as consts from './constants';
11
import { activityBarViews } from '../../../constants';
P
Phil Hughes 已提交
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
import eventHub from '../../../eventhub';

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

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

export const updateCommitAction = ({ commit }, commitAction) => {
  commit(types.UPDATE_COMMIT_ACTION, commitAction);
};

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

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

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

export const checkCommitStatus = ({ rootState }) =>
  service
    .getBranchData(rootState.currentProjectId, rootState.currentBranchId)
    .then(({ data }) => {
      const { id } = data.commit;
      const selectedBranch =
58
        rootState.projects[rootState.currentProjectId].branches[rootState.currentBranchId];
P
Phil Hughes 已提交
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78

      if (selectedBranch.workingReference !== id) {
        return true;
      }

      return false;
    })
    .catch(() =>
      flash(
        __('Error checking branch data. Please try again.'),
        'alert',
        document,
        null,
        false,
        true,
      ),
    );

export const updateFilesAfterCommit = (
  { commit, dispatch, state, rootState, rootGetters },
79
  { data },
P
Phil Hughes 已提交
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
) => {
  const selectedProject = rootState.projects[rootState.currentProjectId];
  const lastCommit = {
    commit_path: `${selectedProject.web_url}/commit/${data.id}`,
    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 },
  );

102 103
  rootState.stagedFiles.forEach(file => {
    const changedFile = rootState.changedFiles.find(f => f.path === file.path);
P
Phil Hughes 已提交
104 105

    commit(
106
      rootTypes.UPDATE_FILE_AFTER_COMMIT,
P
Phil Hughes 已提交
107
      {
108 109
        file,
        lastCommit,
P
Phil Hughes 已提交
110 111 112 113 114 115 116
      },
      { root: true },
    );

    commit(
      rootTypes.TOGGLE_FILE_CHANGED,
      {
117
        file,
P
Phil Hughes 已提交
118 119 120 121
        changed: false,
      },
      { root: true },
    );
P
Phil Hughes 已提交
122

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

125
    eventHub.$emit(`editor.update.model.content.${file.key}`, {
126 127 128
      content: file.content,
      changed: !!changedFile,
    });
P
Phil Hughes 已提交
129 130 131
  });
};

132
export const commitChanges = ({ commit, state, getters, dispatch, rootState, rootGetters }) => {
P
Phil Hughes 已提交
133
  const newBranch = state.commitAction !== consts.COMMIT_TO_CURRENT_BRANCH;
134 135
  const payload = createCommitPayload(getters.branchName, newBranch, state, rootState);
  const getCommitStatus = newBranch ? Promise.resolve(false) : dispatch('checkCommitStatus');
P
Phil Hughes 已提交
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156

  commit(types.UPDATE_LOADING, true);

  return getCommitStatus
    .then(
      branchChanged =>
        new Promise(resolve => {
          if (branchChanged) {
            // show the modal with a Bootstrap call
            $('#ide-create-branch-modal').modal('show');
          } else {
            resolve();
          }
        }),
    )
    .then(() => service.commit(rootState.currentProjectId, payload))
    .then(({ data }) => {
      commit(types.UPDATE_LOADING, false);

      if (!data.short_id) {
        flash(data.message, 'alert', document, null, false, true);
157
        return null;
P
Phil Hughes 已提交
158 159 160 161
      }

      dispatch('setLastCommitMessage', data);
      dispatch('updateCommitMessage', '');
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
      return dispatch('updateFilesAfterCommit', {
        data,
        branch: getters.branchName,
      })
        .then(() => {
          if (state.commitAction === consts.COMMIT_TO_NEW_BRANCH_MR) {
            dispatch(
              'redirectToUrl',
              createNewMergeRequestUrl(
                rootState.projects[rootState.currentProjectId].web_url,
                getters.branchName,
                rootState.currentBranchId,
              ),
              { root: true },
            );
          }
P
Phil Hughes 已提交
178

179
          commit(rootTypes.CLEAR_STAGED_CHANGES, null, { root: true });
A
André Luís 已提交
180 181 182 183

          setTimeout(() => {
            commit(rootTypes.SET_LAST_COMMIT_MSG, '', { root: true });
          }, 5000);
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
        .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 {
            dispatch('updateActivityBarView', activityBarViews.edit, { root: true });
            dispatch('updateViewer', 'editor', { root: true });

            router.push(
              `/project/${rootState.currentProjectId}/blob/${getters.branchName}/${
                rootGetters.activeFile.path
              }`,
            );
          }
        })
213 214 215 216 217
        .then(() => dispatch('updateCommitAction', consts.COMMIT_TO_CURRENT_BRANCH))
        .then(() => dispatch('refreshLastCommitData', {
          projectId: rootState.currentProjectId,
          branchId: rootState.currentBranchId,
        }, { root: true }));
P
Phil Hughes 已提交
218 219 220 221 222 223 224 225 226 227 228 229
    })
    .catch(err => {
      let errMsg = __('Error committing changes. Please try again.');
      if (err.response.data && err.response.data.message) {
        errMsg += ` (${stripHtml(err.response.data.message)})`;
      }
      flash(errMsg, 'alert', document, null, false, true);
      window.dispatchEvent(new Event('resize'));

      commit(types.UPDATE_LOADING, false);
    });
};
230 231 232

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