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

      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 },
  { data, branch },
) => {
  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 },
  );

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

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

113
    eventHub.$emit(`editor.update.model.content.${file.key}`, {
114 115 116
      content: file.content,
      changed: !!changedFile,
    });
P
Phil Hughes 已提交
117 118
  });

119
  if (state.commitAction === consts.COMMIT_TO_NEW_BRANCH && rootGetters.activeFile) {
P
Phil Hughes 已提交
120
    router.push(
121
      `/project/${rootState.currentProjectId}/blob/${branch}/${rootGetters.activeFile.path}`,
P
Phil Hughes 已提交
122 123 124 125
    );
  }
};

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

  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);
151
        return null;
P
Phil Hughes 已提交
152 153 154 155
      }

      dispatch('setLastCommitMessage', data);
      dispatch('updateCommitMessage', '');
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
      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 已提交
172

173
          commit(rootTypes.CLEAR_STAGED_CHANGES, null, { root: true });
174 175
        })
        .then(() => dispatch('updateCommitAction', consts.COMMIT_TO_CURRENT_BRANCH));
P
Phil Hughes 已提交
176 177 178 179 180 181 182 183 184 185 186 187
    })
    .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);
    });
};