actions.js 6.4 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.'), {
L
Lukas Eipert 已提交
34 35 36
        additions: data.stats.additions, // eslint-disable-line indent-legacy
        deletions: data.stats.deletions, // eslint-disable-line indent-legacy
      }) // eslint-disable-line indent-legacy
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
      commitStats,
    },
    false,
  );

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

L
Lukas Eipert 已提交
52
export const updateFilesAfterCommit = ({ commit, dispatch, rootState }, { data }) => {
P
Phil Hughes 已提交
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
  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 },
  );

74 75
  rootState.stagedFiles.forEach(file => {
    const changedFile = rootState.changedFiles.find(f => f.path === file.path);
P
Phil Hughes 已提交
76 77

    commit(
78
      rootTypes.UPDATE_FILE_AFTER_COMMIT,
P
Phil Hughes 已提交
79
      {
80 81
        file,
        lastCommit,
P
Phil Hughes 已提交
82 83 84 85 86 87 88
      },
      { root: true },
    );

    commit(
      rootTypes.TOGGLE_FILE_CHANGED,
      {
89
        file,
P
Phil Hughes 已提交
90 91 92 93
        changed: false,
      },
      { root: true },
    );
P
Phil Hughes 已提交
94

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

97
    eventHub.$emit(`editor.update.model.content.${file.key}`, {
98 99 100
      content: file.content,
      changed: !!changedFile,
    });
P
Phil Hughes 已提交
101 102 103
  });
};

104
export const commitChanges = ({ commit, state, getters, dispatch, rootState, rootGetters }) => {
P
Phil Hughes 已提交
105
  const newBranch = state.commitAction !== consts.COMMIT_TO_CURRENT_BRANCH;
P
Phil Hughes 已提交
106 107 108
  const stageFilesPromise = rootState.stagedFiles.length
    ? Promise.resolve()
    : dispatch('stageAllChanges', null, { root: true });
P
Phil Hughes 已提交
109 110 111

  commit(types.UPDATE_LOADING, true);

P
Phil Hughes 已提交
112
  return stageFilesPromise
113 114 115 116 117 118 119 120 121 122 123
    .then(() => {
      const payload = createCommitPayload({
        branch: getters.branchName,
        newBranch,
        getters,
        state,
        rootState,
      });

      return service.commit(rootState.currentProjectId, payload);
    })
P
Phil Hughes 已提交
124 125 126 127 128
    .then(({ data }) => {
      commit(types.UPDATE_LOADING, false);

      if (!data.short_id) {
        flash(data.message, 'alert', document, null, false, true);
129
        return null;
P
Phil Hughes 已提交
130 131 132 133
      }

      dispatch('setLastCommitMessage', data);
      dispatch('updateCommitMessage', '');
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
      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 已提交
150

151
          commit(rootTypes.CLEAR_STAGED_CHANGES, null, { root: true });
A
André Luís 已提交
152 153 154 155

          setTimeout(() => {
            commit(rootTypes.SET_LAST_COMMIT_MSG, '', { root: true });
          }, 5000);
156
        })
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
        .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(
179
              `/project/${rootState.currentProjectId}/blob/${getters.branchName}/-/${
180 181 182 183 184
                rootGetters.activeFile.path
              }`,
            );
          }
        })
185
        .then(() => dispatch('updateCommitAction', consts.COMMIT_TO_CURRENT_BRANCH))
186 187 188 189 190 191 192 193 194 195
        .then(() =>
          dispatch(
            'refreshLastCommitData',
            {
              projectId: rootState.currentProjectId,
              branchId: rootState.currentBranchId,
            },
            { root: true },
          ),
        );
P
Phil Hughes 已提交
196 197
    })
    .catch(err => {
198 199 200 201 202 203 204 205 206
      if (err.response.status === 400) {
        $('#ide-create-branch-modal').modal('show');
      } else {
        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'));
P
Phil Hughes 已提交
207 208 209 210 211
      }

      commit(types.UPDATE_LOADING, false);
    });
};
212 213 214

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